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 if let ty::CoroutineClosure(def_id, args) = *self_ty.kind()
805 && let sig = args.as_coroutine_closure().coroutine_closure_sig().skip_binder()
806 && let ty::Tuple(inputs) = *sig.tupled_inputs_ty.kind()
807 && inputs.is_empty()
808 && self.tcx.is_lang_item(trait_pred.def_id(), LangItem::Future)
809 && let Some(hir::Node::Expr(hir::Expr {
810 kind:
811 hir::ExprKind::Closure(hir::Closure {
812 kind: hir::ClosureKind::CoroutineClosure(CoroutineDesugaring::Async),
813 fn_arg_span: Some(arg_span),
814 ..
815 }),
816 ..
817 })) = self.tcx.hir_get_if_local(def_id)
818 && obligation.cause.span.contains(*arg_span)
819 {
820 let sm = self.tcx.sess.source_map();
821 let removal_span = if let Ok(snippet) =
822 sm.span_to_snippet(arg_span.with_hi(arg_span.hi() + rustc_span::BytePos(1)))
823 && snippet.ends_with(' ')
824 {
825 arg_span.with_hi(arg_span.hi() + rustc_span::BytePos(1))
827 } else {
828 *arg_span
829 };
830 err.span_suggestion_verbose(
831 removal_span,
832 "use `async {}` instead of `async || {}` to introduce an async block",
833 "",
834 Applicability::MachineApplicable,
835 );
836 return true;
837 }
838
839 let msg = match def_id_or_name {
841 DefIdOrName::DefId(def_id) => match self.tcx.def_kind(def_id) {
842 DefKind::Ctor(CtorOf::Struct, _) => {
843 Cow::from("use parentheses to construct this tuple struct")
844 }
845 DefKind::Ctor(CtorOf::Variant, _) => {
846 Cow::from("use parentheses to construct this tuple variant")
847 }
848 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!(
849 "use parentheses to call this {}",
850 self.tcx.def_kind_descr(kind, def_id)
851 )),
852 },
853 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}")),
854 };
855
856 let args = inputs
857 .into_iter()
858 .map(|ty| {
859 if ty.is_suggestable(self.tcx, false) {
860 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("/* {0} */", ty))
})format!("/* {ty} */")
861 } else {
862 "/* value */".to_string()
863 }
864 })
865 .collect::<Vec<_>>()
866 .join(", ");
867
868 if #[allow(non_exhaustive_omitted_patterns)] match obligation.cause.code() {
ObligationCauseCode::FunctionArg { .. } => true,
_ => false,
}matches!(obligation.cause.code(), ObligationCauseCode::FunctionArg { .. })
869 && obligation.cause.span.can_be_used_for_suggestions()
870 {
871 let (span, sugg) = if let Some(snippet) =
872 self.tcx.sess.source_map().span_to_snippet(obligation.cause.span).ok()
873 && snippet.starts_with("|")
874 {
875 (obligation.cause.span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0})({1})", snippet, args))
})format!("({snippet})({args})"))
876 } else {
877 (obligation.cause.span.shrink_to_hi(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0})", args))
})format!("({args})"))
878 };
879
880 err.span_suggestion_verbose(span, msg, sugg, Applicability::HasPlaceholders);
885 } else if let DefIdOrName::DefId(def_id) = def_id_or_name {
886 let name = match self.tcx.hir_get_if_local(def_id) {
887 Some(hir::Node::Expr(hir::Expr {
888 kind: hir::ExprKind::Closure(hir::Closure { fn_decl_span, .. }),
889 ..
890 })) => {
891 err.span_label(*fn_decl_span, "consider calling this closure");
892 let Some(name) = self.get_closure_name(def_id, err, msg.clone()) else {
893 return false;
894 };
895 name.to_string()
896 }
897 Some(hir::Node::Item(hir::Item {
898 kind: hir::ItemKind::Fn { ident, .. }, ..
899 })) => {
900 err.span_label(ident.span, "consider calling this function");
901 ident.to_string()
902 }
903 Some(hir::Node::Ctor(..)) => {
904 let name = self.tcx.def_path_str(def_id);
905 err.span_label(
906 self.tcx.def_span(def_id),
907 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider calling the constructor for `{0}`",
name))
})format!("consider calling the constructor for `{name}`"),
908 );
909 name
910 }
911 _ => return false,
912 };
913 err.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: `{1}({2})`", msg, name, args))
})format!("{msg}: `{name}({args})`"));
914 }
915 true
916 }
917
918 pub(super) fn check_for_binding_assigned_block_without_tail_expression(
919 &self,
920 obligation: &PredicateObligation<'tcx>,
921 err: &mut Diag<'_>,
922 trait_pred: ty::PolyTraitPredicate<'tcx>,
923 ) {
924 let mut span = obligation.cause.span;
925 while span.from_expansion() {
926 span.remove_mark();
928 }
929 let mut expr_finder = FindExprBySpan::new(span, self.tcx);
930 let Some(body) = self.tcx.hir_maybe_body_owned_by(obligation.cause.body_id) else {
931 return;
932 };
933 expr_finder.visit_expr(body.value);
934 let Some(expr) = expr_finder.result else {
935 return;
936 };
937 let Some(typeck) = &self.typeck_results else {
938 return;
939 };
940 let Some(ty) = typeck.expr_ty_adjusted_opt(expr) else {
941 return;
942 };
943 if !ty.is_unit() {
944 return;
945 };
946 let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind else {
947 return;
948 };
949 let Res::Local(hir_id) = path.res else {
950 return;
951 };
952 let hir::Node::Pat(pat) = self.tcx.hir_node(hir_id) else {
953 return;
954 };
955 let hir::Node::LetStmt(hir::LetStmt { ty: None, init: Some(init), .. }) =
956 self.tcx.parent_hir_node(pat.hir_id)
957 else {
958 return;
959 };
960 let hir::ExprKind::Block(block, None) = init.kind else {
961 return;
962 };
963 if block.expr.is_some() {
964 return;
965 }
966 let [.., stmt] = block.stmts else {
967 err.span_label(block.span, "this empty block is missing a tail expression");
968 return;
969 };
970 if stmt.span.from_expansion() {
973 return;
974 }
975 let hir::StmtKind::Semi(tail_expr) = stmt.kind else {
976 return;
977 };
978 let Some(ty) = typeck.expr_ty_opt(tail_expr) else {
979 err.span_label(block.span, "this block is missing a tail expression");
980 return;
981 };
982 let ty = self.resolve_numeric_literals_with_default(self.resolve_vars_if_possible(ty));
983 let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, ty));
984
985 let new_obligation =
986 self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred_and_self);
987 if !#[allow(non_exhaustive_omitted_patterns)] match tail_expr.kind {
hir::ExprKind::Err(_) => true,
_ => false,
}matches!(tail_expr.kind, hir::ExprKind::Err(_))
988 && self.predicate_must_hold_modulo_regions(&new_obligation)
989 {
990 err.span_suggestion_short(
991 stmt.span.with_lo(tail_expr.span.hi()),
992 "remove this semicolon",
993 "",
994 Applicability::MachineApplicable,
995 );
996 } else {
997 err.span_label(block.span, "this block is missing a tail expression");
998 }
999 }
1000
1001 pub(super) fn suggest_add_clone_to_arg(
1002 &self,
1003 obligation: &PredicateObligation<'tcx>,
1004 err: &mut Diag<'_>,
1005 trait_pred: ty::PolyTraitPredicate<'tcx>,
1006 ) -> bool {
1007 let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
1008 self.enter_forall(self_ty, |ty: Ty<'_>| {
1009 let Some(generics) = self.tcx.hir_get_generics(obligation.cause.body_id) else {
1010 return false;
1011 };
1012 let ty::Ref(_, inner_ty, hir::Mutability::Not) = ty.kind() else { return false };
1013 let ty::Param(param) = inner_ty.kind() else { return false };
1014 let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code()
1015 else {
1016 return false;
1017 };
1018
1019 let clone_trait = self.tcx.require_lang_item(LangItem::Clone, obligation.cause.span);
1020 let has_clone = |ty| {
1021 self.type_implements_trait(clone_trait, [ty], obligation.param_env)
1022 .must_apply_modulo_regions()
1023 };
1024
1025 let existing_clone_call = match self.tcx.hir_node(*arg_hir_id) {
1026 Node::Expr(Expr { kind: hir::ExprKind::Path(_), .. }) => None,
1028 Node::Expr(Expr {
1031 kind:
1032 hir::ExprKind::MethodCall(
1033 hir::PathSegment { ident, .. },
1034 _receiver,
1035 [],
1036 call_span,
1037 ),
1038 hir_id,
1039 ..
1040 }) if ident.name == sym::clone
1041 && !call_span.from_expansion()
1042 && !has_clone(*inner_ty) =>
1043 {
1044 let Some(typeck_results) = self.typeck_results.as_ref() else { return false };
1046 let Some((DefKind::AssocFn, did)) = typeck_results.type_dependent_def(*hir_id)
1047 else {
1048 return false;
1049 };
1050 if self.tcx.trait_of_assoc(did) != Some(clone_trait) {
1051 return false;
1052 }
1053 Some(ident.span)
1054 }
1055 _ => return false,
1056 };
1057
1058 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1059 obligation.param_env,
1060 trait_pred.map_bound(|trait_pred| (trait_pred, *inner_ty)),
1061 );
1062
1063 if self.predicate_may_hold(&new_obligation) && has_clone(ty) {
1064 if !has_clone(param.to_ty(self.tcx)) {
1065 suggest_constraining_type_param(
1066 self.tcx,
1067 generics,
1068 err,
1069 param.name.as_str(),
1070 "Clone",
1071 Some(clone_trait),
1072 None,
1073 );
1074 }
1075 if let Some(existing_clone_call) = existing_clone_call {
1076 err.span_note(
1077 existing_clone_call,
1078 ::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!(
1079 "this `clone()` copies the reference, \
1080 which does not do anything, \
1081 because `{inner_ty}` does not implement `Clone`"
1082 ),
1083 );
1084 } else {
1085 err.span_suggestion_verbose(
1086 obligation.cause.span.shrink_to_hi(),
1087 "consider using clone here",
1088 ".clone()".to_string(),
1089 Applicability::MaybeIncorrect,
1090 );
1091 }
1092 return true;
1093 }
1094 false
1095 })
1096 }
1097
1098 pub fn extract_callable_info(
1102 &self,
1103 body_id: LocalDefId,
1104 param_env: ty::ParamEnv<'tcx>,
1105 found: Ty<'tcx>,
1106 ) -> Option<(DefIdOrName, Ty<'tcx>, Vec<Ty<'tcx>>)> {
1107 let Some((def_id_or_name, output, inputs)) =
1109 (self.autoderef_steps)(found).into_iter().find_map(|(found, _)| match *found.kind() {
1110 ty::FnPtr(sig_tys, _) => Some((
1111 DefIdOrName::Name("function pointer"),
1112 sig_tys.output(),
1113 sig_tys.inputs(),
1114 )),
1115 ty::FnDef(def_id, _) => {
1116 let fn_sig = found.fn_sig(self.tcx);
1117 Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs()))
1118 }
1119 ty::Closure(def_id, args) => {
1120 let fn_sig = args.as_closure().sig();
1121 Some((
1122 DefIdOrName::DefId(def_id),
1123 fn_sig.output(),
1124 fn_sig.inputs().map_bound(|inputs| inputs[0].tuple_fields().as_slice()),
1125 ))
1126 }
1127 ty::CoroutineClosure(def_id, args) => {
1128 let sig_parts = args.as_coroutine_closure().coroutine_closure_sig();
1129 Some((
1130 DefIdOrName::DefId(def_id),
1131 sig_parts.map_bound(|sig| {
1132 sig.to_coroutine(
1133 self.tcx,
1134 args.as_coroutine_closure().parent_args(),
1135 self.next_ty_var(DUMMY_SP),
1138 self.tcx.coroutine_for_closure(def_id),
1139 self.next_ty_var(DUMMY_SP),
1140 )
1141 }),
1142 sig_parts.map_bound(|sig| sig.tupled_inputs_ty.tuple_fields().as_slice()),
1143 ))
1144 }
1145 ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) => {
1146 self.tcx.item_self_bounds(def_id).instantiate(self.tcx, args).iter().find_map(
1147 |pred| {
1148 if let ty::ClauseKind::Projection(proj) = pred.kind().skip_binder()
1149 && self
1150 .tcx
1151 .is_lang_item(proj.projection_term.def_id, LangItem::FnOnceOutput)
1152 && let ty::Tuple(args) = proj.projection_term.args.type_at(1).kind()
1154 {
1155 Some((
1156 DefIdOrName::DefId(def_id),
1157 pred.kind().rebind(proj.term.expect_type()),
1158 pred.kind().rebind(args.as_slice()),
1159 ))
1160 } else {
1161 None
1162 }
1163 },
1164 )
1165 }
1166 ty::Dynamic(data, _) => data.iter().find_map(|pred| {
1167 if let ty::ExistentialPredicate::Projection(proj) = pred.skip_binder()
1168 && self.tcx.is_lang_item(proj.def_id, LangItem::FnOnceOutput)
1169 && let ty::Tuple(args) = proj.args.type_at(0).kind()
1171 {
1172 Some((
1173 DefIdOrName::Name("trait object"),
1174 pred.rebind(proj.term.expect_type()),
1175 pred.rebind(args.as_slice()),
1176 ))
1177 } else {
1178 None
1179 }
1180 }),
1181 ty::Param(param) => {
1182 let generics = self.tcx.generics_of(body_id);
1183 let name = if generics.count() > param.index as usize
1184 && let def = generics.param_at(param.index as usize, self.tcx)
1185 && #[allow(non_exhaustive_omitted_patterns)] match def.kind {
ty::GenericParamDefKind::Type { .. } => true,
_ => false,
}matches!(def.kind, ty::GenericParamDefKind::Type { .. })
1186 && def.name == param.name
1187 {
1188 DefIdOrName::DefId(def.def_id)
1189 } else {
1190 DefIdOrName::Name("type parameter")
1191 };
1192 param_env.caller_bounds().iter().find_map(|pred| {
1193 if let ty::ClauseKind::Projection(proj) = pred.kind().skip_binder()
1194 && self
1195 .tcx
1196 .is_lang_item(proj.projection_term.def_id, LangItem::FnOnceOutput)
1197 && proj.projection_term.self_ty() == found
1198 && let ty::Tuple(args) = proj.projection_term.args.type_at(1).kind()
1200 {
1201 Some((
1202 name,
1203 pred.kind().rebind(proj.term.expect_type()),
1204 pred.kind().rebind(args.as_slice()),
1205 ))
1206 } else {
1207 None
1208 }
1209 })
1210 }
1211 _ => None,
1212 })
1213 else {
1214 return None;
1215 };
1216
1217 let output = self.instantiate_binder_with_fresh_vars(
1218 DUMMY_SP,
1219 BoundRegionConversionTime::FnCall,
1220 output,
1221 );
1222 let inputs = inputs
1223 .skip_binder()
1224 .iter()
1225 .map(|ty| {
1226 self.instantiate_binder_with_fresh_vars(
1227 DUMMY_SP,
1228 BoundRegionConversionTime::FnCall,
1229 inputs.rebind(*ty),
1230 )
1231 })
1232 .collect();
1233
1234 let InferOk { value: output, obligations: _ } =
1238 self.at(&ObligationCause::dummy(), param_env).normalize(output);
1239
1240 if output.is_ty_var() { None } else { Some((def_id_or_name, output, inputs)) }
1241 }
1242
1243 pub(super) fn suggest_add_reference_to_arg(
1244 &self,
1245 obligation: &PredicateObligation<'tcx>,
1246 err: &mut Diag<'_>,
1247 poly_trait_pred: ty::PolyTraitPredicate<'tcx>,
1248 has_custom_message: bool,
1249 ) -> bool {
1250 let span = obligation.cause.span;
1251 let param_env = obligation.param_env;
1252
1253 let mk_result = |trait_pred_and_new_ty| {
1254 let obligation =
1255 self.mk_trait_obligation_with_new_self_ty(param_env, trait_pred_and_new_ty);
1256 self.predicate_must_hold_modulo_regions(&obligation)
1257 };
1258
1259 let code = match obligation.cause.code() {
1260 ObligationCauseCode::FunctionArg { parent_code, .. } => parent_code,
1261 c @ ObligationCauseCode::WhereClauseInExpr(_, _, hir_id, _)
1264 if self.tcx.hir_span(*hir_id).lo() == span.lo() =>
1265 {
1266 if let hir::Node::Expr(expr) = self.tcx.parent_hir_node(*hir_id)
1270 && let hir::ExprKind::Call(base, _) = expr.kind
1271 && let hir::ExprKind::Path(hir::QPath::TypeRelative(ty, segment)) = base.kind
1272 && let hir::Node::Expr(outer) = self.tcx.parent_hir_node(expr.hir_id)
1273 && let hir::ExprKind::AddrOf(hir::BorrowKind::Ref, mtbl, _) = outer.kind
1274 && ty.span == span
1275 {
1276 let trait_pred_and_imm_ref = poly_trait_pred.map_bound(|p| {
1282 (p, Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_static, p.self_ty()))
1283 });
1284 let trait_pred_and_mut_ref = poly_trait_pred.map_bound(|p| {
1285 (p, Ty::new_mut_ref(self.tcx, self.tcx.lifetimes.re_static, p.self_ty()))
1286 });
1287
1288 let imm_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_imm_ref);
1289 let mut_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_mut_ref);
1290 let sugg_msg = |pre: &str| {
1291 ::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!(
1292 "you likely meant to call the associated function `{FN}` for type \
1293 `&{pre}{TY}`, but the code as written calls associated function `{FN}` on \
1294 type `{TY}`",
1295 FN = segment.ident,
1296 TY = poly_trait_pred.self_ty(),
1297 )
1298 };
1299 match (imm_ref_self_ty_satisfies_pred, mut_ref_self_ty_satisfies_pred, mtbl) {
1300 (true, _, hir::Mutability::Not) | (_, true, hir::Mutability::Mut) => {
1301 err.multipart_suggestion(
1302 sugg_msg(mtbl.prefix_str()),
1303 ::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![
1304 (outer.span.shrink_to_lo(), "<".to_string()),
1305 (span.shrink_to_hi(), ">".to_string()),
1306 ],
1307 Applicability::MachineApplicable,
1308 );
1309 }
1310 (true, _, hir::Mutability::Mut) => {
1311 err.multipart_suggestion(
1313 sugg_msg("mut "),
1314 ::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![
1315 (outer.span.shrink_to_lo().until(span), "<&".to_string()),
1316 (span.shrink_to_hi(), ">".to_string()),
1317 ],
1318 Applicability::MachineApplicable,
1319 );
1320 }
1321 (_, true, hir::Mutability::Not) => {
1322 err.multipart_suggestion(
1323 sugg_msg(""),
1324 ::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![
1325 (outer.span.shrink_to_lo().until(span), "<&mut ".to_string()),
1326 (span.shrink_to_hi(), ">".to_string()),
1327 ],
1328 Applicability::MachineApplicable,
1329 );
1330 }
1331 _ => {}
1332 }
1333 return false;
1335 }
1336 c
1337 }
1338 c if #[allow(non_exhaustive_omitted_patterns)] match span.ctxt().outer_expn_data().kind
{
ExpnKind::Desugaring(DesugaringKind::ForLoop) => true,
_ => false,
}matches!(
1339 span.ctxt().outer_expn_data().kind,
1340 ExpnKind::Desugaring(DesugaringKind::ForLoop)
1341 ) =>
1342 {
1343 c
1344 }
1345 _ => return false,
1346 };
1347
1348 let mut never_suggest_borrow: Vec<_> =
1352 [LangItem::Copy, LangItem::Clone, LangItem::Unpin, LangItem::Sized]
1353 .iter()
1354 .filter_map(|lang_item| self.tcx.lang_items().get(*lang_item))
1355 .collect();
1356
1357 if let Some(def_id) = self.tcx.get_diagnostic_item(sym::Send) {
1358 never_suggest_borrow.push(def_id);
1359 }
1360
1361 let mut try_borrowing = |old_pred: ty::PolyTraitPredicate<'tcx>,
1363 blacklist: &[DefId]|
1364 -> bool {
1365 if blacklist.contains(&old_pred.def_id()) {
1366 return false;
1367 }
1368 let trait_pred_and_imm_ref = old_pred.map_bound(|trait_pred| {
1370 (
1371 trait_pred,
1372 Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1373 )
1374 });
1375 let trait_pred_and_mut_ref = old_pred.map_bound(|trait_pred| {
1376 (
1377 trait_pred,
1378 Ty::new_mut_ref(self.tcx, self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1379 )
1380 });
1381
1382 let imm_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_imm_ref);
1383 let mut_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_mut_ref);
1384
1385 let (ref_inner_ty_satisfies_pred, ref_inner_ty_is_mut) =
1386 if let ObligationCauseCode::WhereClauseInExpr(..) = obligation.cause.code()
1387 && let ty::Ref(_, ty, mutability) = old_pred.self_ty().skip_binder().kind()
1388 {
1389 (
1390 mk_result(old_pred.map_bound(|trait_pred| (trait_pred, *ty))),
1391 mutability.is_mut(),
1392 )
1393 } else {
1394 (false, false)
1395 };
1396
1397 let is_immut = imm_ref_self_ty_satisfies_pred
1398 || (ref_inner_ty_satisfies_pred && !ref_inner_ty_is_mut);
1399 let is_mut = mut_ref_self_ty_satisfies_pred || ref_inner_ty_is_mut;
1400 if !is_immut && !is_mut {
1401 return false;
1402 }
1403 let Ok(_snippet) = self.tcx.sess.source_map().span_to_snippet(span) else {
1404 return false;
1405 };
1406 if !#[allow(non_exhaustive_omitted_patterns)] match span.ctxt().outer_expn_data().kind
{
ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop) => true,
_ => false,
}matches!(
1414 span.ctxt().outer_expn_data().kind,
1415 ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop)
1416 ) {
1417 return false;
1418 }
1419 let mut label = || {
1426 let is_sized = match obligation.predicate.kind().skip_binder() {
1429 ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred)) => {
1430 self.tcx.is_lang_item(trait_pred.def_id(), LangItem::Sized)
1431 }
1432 _ => false,
1433 };
1434
1435 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!(
1436 "the trait bound `{}` is not satisfied",
1437 self.tcx.short_string(old_pred, err.long_ty_path()),
1438 );
1439 let self_ty_str = self.tcx.short_string(old_pred.self_ty(), err.long_ty_path());
1440 let trait_path = self
1441 .tcx
1442 .short_string(old_pred.print_modifiers_and_trait_path(), err.long_ty_path());
1443
1444 if has_custom_message {
1445 let msg = if is_sized {
1446 "the trait bound `Sized` is not satisfied".into()
1447 } else {
1448 msg
1449 };
1450 err.note(msg);
1451 } else {
1452 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)];
1453 }
1454 if is_sized {
1455 err.span_label(
1456 span,
1457 ::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}`"),
1458 );
1459 } else {
1460 err.span_label(
1461 span,
1462 ::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}`"),
1463 );
1464 }
1465 };
1466
1467 let mut sugg_prefixes = ::alloc::vec::Vec::new()vec![];
1468 if is_immut {
1469 sugg_prefixes.push("&");
1470 }
1471 if is_mut {
1472 sugg_prefixes.push("&mut ");
1473 }
1474 let sugg_msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider{0} borrowing here",
if is_mut && !is_immut { " mutably" } else { "" }))
})format!(
1475 "consider{} borrowing here",
1476 if is_mut && !is_immut { " mutably" } else { "" },
1477 );
1478
1479 let Some(body) = self.tcx.hir_maybe_body_owned_by(obligation.cause.body_id) else {
1483 return false;
1484 };
1485 let mut expr_finder = FindExprBySpan::new(span, self.tcx);
1486 expr_finder.visit_expr(body.value);
1487
1488 if let Some(ty) = expr_finder.ty_result {
1489 if let hir::Node::Expr(expr) = self.tcx.parent_hir_node(ty.hir_id)
1490 && let hir::ExprKind::Path(hir::QPath::TypeRelative(_, _)) = expr.kind
1491 && ty.span == span
1492 {
1493 label();
1496 err.multipart_suggestions(
1497 sugg_msg,
1498 sugg_prefixes.into_iter().map(|sugg_prefix| {
1499 ::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![
1500 (span.shrink_to_lo(), format!("<{sugg_prefix}")),
1501 (span.shrink_to_hi(), ">".to_string()),
1502 ]
1503 }),
1504 Applicability::MaybeIncorrect,
1505 );
1506 return true;
1507 }
1508 return false;
1509 }
1510 let Some(expr) = expr_finder.result else {
1511 return false;
1512 };
1513 if let hir::ExprKind::AddrOf(_, _, _) = expr.kind {
1514 return false;
1515 }
1516 let needs_parens_post = expr_needs_parens(expr);
1517 let needs_parens_pre = match self.tcx.parent_hir_node(expr.hir_id) {
1518 Node::Expr(e)
1519 if let hir::ExprKind::MethodCall(_, base, _, _) = e.kind
1520 && base.hir_id == expr.hir_id =>
1521 {
1522 true
1523 }
1524 _ => false,
1525 };
1526
1527 label();
1528 let suggestions = sugg_prefixes.into_iter().map(|sugg_prefix| {
1529 match (needs_parens_pre, needs_parens_post) {
1530 (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())],
1531 (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![
1534 (span.shrink_to_lo(), format!("{sugg_prefix}(")),
1535 (span.shrink_to_hi(), ")".to_string()),
1536 ],
1537 (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![
1540 (span.shrink_to_lo(), format!("({sugg_prefix}")),
1541 (span.shrink_to_hi(), ")".to_string()),
1542 ],
1543 (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![
1544 (span.shrink_to_lo(), format!("({sugg_prefix}(")),
1545 (span.shrink_to_hi(), "))".to_string()),
1546 ],
1547 }
1548 });
1549 err.multipart_suggestions(sugg_msg, suggestions, Applicability::MaybeIncorrect);
1550 return true;
1551 };
1552
1553 if let ObligationCauseCode::ImplDerived(cause) = &*code {
1554 try_borrowing(cause.derived.parent_trait_pred, &[])
1555 } else if let ObligationCauseCode::WhereClause(..)
1556 | ObligationCauseCode::WhereClauseInExpr(..) = code
1557 {
1558 try_borrowing(poly_trait_pred, &never_suggest_borrow)
1559 } else {
1560 false
1561 }
1562 }
1563
1564 pub(super) fn suggest_borrowing_for_object_cast(
1566 &self,
1567 err: &mut Diag<'_>,
1568 obligation: &PredicateObligation<'tcx>,
1569 self_ty: Ty<'tcx>,
1570 target_ty: Ty<'tcx>,
1571 ) {
1572 let ty::Ref(_, object_ty, hir::Mutability::Not) = target_ty.kind() else {
1573 return;
1574 };
1575 let ty::Dynamic(predicates, _) = object_ty.kind() else {
1576 return;
1577 };
1578 let self_ref_ty = Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_erased, self_ty);
1579
1580 for predicate in predicates.iter() {
1581 if !self.predicate_must_hold_modulo_regions(
1582 &obligation.with(self.tcx, predicate.with_self_ty(self.tcx, self_ref_ty)),
1583 ) {
1584 return;
1585 }
1586 }
1587
1588 err.span_suggestion_verbose(
1589 obligation.cause.span.shrink_to_lo(),
1590 ::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!(
1591 "consider borrowing the value, since `&{self_ty}` can be coerced into `{target_ty}`"
1592 ),
1593 "&",
1594 Applicability::MaybeIncorrect,
1595 );
1596 }
1597
1598 pub(super) fn suggest_remove_reference(
1601 &self,
1602 obligation: &PredicateObligation<'tcx>,
1603 err: &mut Diag<'_>,
1604 trait_pred: ty::PolyTraitPredicate<'tcx>,
1605 ) -> bool {
1606 let mut span = obligation.cause.span;
1607 let mut trait_pred = trait_pred;
1608 let mut code = obligation.cause.code();
1609 while let Some((c, Some(parent_trait_pred))) = code.parent_with_predicate() {
1610 code = c;
1613 trait_pred = parent_trait_pred;
1614 }
1615 while span.desugaring_kind().is_some() {
1616 span.remove_mark();
1618 }
1619 let mut expr_finder = super::FindExprBySpan::new(span, self.tcx);
1620 let Some(body) = self.tcx.hir_maybe_body_owned_by(obligation.cause.body_id) else {
1621 return false;
1622 };
1623 expr_finder.visit_expr(body.value);
1624 let mut maybe_suggest = |suggested_ty, count, suggestions| {
1625 let trait_pred_and_suggested_ty =
1627 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1628
1629 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1630 obligation.param_env,
1631 trait_pred_and_suggested_ty,
1632 );
1633
1634 if self.predicate_may_hold(&new_obligation) {
1635 let msg = if count == 1 {
1636 "consider removing the leading `&`-reference".to_string()
1637 } else {
1638 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider removing {0} leading `&`-references",
count))
})format!("consider removing {count} leading `&`-references")
1639 };
1640
1641 err.multipart_suggestion(msg, suggestions, Applicability::MachineApplicable);
1642 true
1643 } else {
1644 false
1645 }
1646 };
1647
1648 let mut count = 0;
1651 let mut suggestions = ::alloc::vec::Vec::new()vec![];
1652 let mut suggested_ty = trait_pred.self_ty().skip_binder();
1654 if let Some(mut hir_ty) = expr_finder.ty_result {
1655 while let hir::TyKind::Ref(_, mut_ty) = &hir_ty.kind {
1656 count += 1;
1657 let span = hir_ty.span.until(mut_ty.ty.span);
1658 suggestions.push((span, String::new()));
1659
1660 let ty::Ref(_, inner_ty, _) = suggested_ty.kind() else {
1661 break;
1662 };
1663 suggested_ty = *inner_ty;
1664
1665 hir_ty = mut_ty.ty;
1666
1667 if maybe_suggest(suggested_ty, count, suggestions.clone()) {
1668 return true;
1669 }
1670 }
1671 }
1672
1673 let Some(mut expr) = expr_finder.result else {
1675 return false;
1676 };
1677 let mut count = 0;
1678 let mut suggestions = ::alloc::vec::Vec::new()vec![];
1679 let mut suggested_ty = trait_pred.self_ty().skip_binder();
1681 'outer: loop {
1682 while let hir::ExprKind::AddrOf(_, _, borrowed) = expr.kind {
1683 count += 1;
1684 let span =
1685 if let Some(borrowed_span) = borrowed.span.find_ancestor_inside(expr.span) {
1686 expr.span.until(borrowed_span)
1687 } else {
1688 break 'outer;
1689 };
1690
1691 match self.tcx.sess.source_map().span_to_snippet(span) {
1694 Ok(snippet) if snippet.starts_with("&") => {}
1695 _ => break 'outer,
1696 }
1697
1698 suggestions.push((span, String::new()));
1699
1700 let ty::Ref(_, inner_ty, _) = suggested_ty.kind() else {
1701 break 'outer;
1702 };
1703 suggested_ty = *inner_ty;
1704
1705 expr = borrowed;
1706
1707 if maybe_suggest(suggested_ty, count, suggestions.clone()) {
1708 return true;
1709 }
1710 }
1711 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
1712 && let Res::Local(hir_id) = path.res
1713 && let hir::Node::Pat(binding) = self.tcx.hir_node(hir_id)
1714 && let hir::Node::LetStmt(local) = self.tcx.parent_hir_node(binding.hir_id)
1715 && let None = local.ty
1716 && let Some(binding_expr) = local.init
1717 {
1718 expr = binding_expr;
1719 } else {
1720 break 'outer;
1721 }
1722 }
1723 false
1724 }
1725
1726 pub(super) fn suggest_remove_await(
1727 &self,
1728 obligation: &PredicateObligation<'tcx>,
1729 err: &mut Diag<'_>,
1730 ) {
1731 if let ObligationCauseCode::AwaitableExpr(hir_id) = obligation.cause.code().peel_derives()
1732 && let hir::Node::Expr(expr) = self.tcx.hir_node(*hir_id)
1733 {
1734 if let Some((_, hir::Node::Expr(await_expr))) = self.tcx.hir_parent_iter(*hir_id).nth(1)
1741 && let Some(expr_span) = expr.span.find_ancestor_inside_same_ctxt(await_expr.span)
1742 {
1743 let removal_span = self
1744 .tcx
1745 .sess
1746 .source_map()
1747 .span_extend_while_whitespace(expr_span)
1748 .shrink_to_hi()
1749 .to(await_expr.span.shrink_to_hi());
1750 err.span_suggestion_verbose(
1751 removal_span,
1752 "remove the `.await`",
1753 "",
1754 Applicability::MachineApplicable,
1755 );
1756 } else {
1757 err.span_label(obligation.cause.span, "remove the `.await`");
1758 }
1759 if let hir::Expr { span, kind: hir::ExprKind::Call(base, _), .. } = expr {
1761 if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
1762 obligation.predicate.kind().skip_binder()
1763 {
1764 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()));
1765 }
1766 if let Some(typeck_results) = &self.typeck_results
1767 && let ty = typeck_results.expr_ty_adjusted(base)
1768 && let ty::FnDef(def_id, _args) = ty.kind()
1769 && let Some(hir::Node::Item(item)) = self.tcx.hir_get_if_local(*def_id)
1770 {
1771 let (ident, _, _, _) = item.expect_fn();
1772 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");
1773 if item.vis_span.is_empty() {
1774 err.span_suggestion_verbose(
1775 item.span.shrink_to_lo(),
1776 msg,
1777 "async ",
1778 Applicability::MaybeIncorrect,
1779 );
1780 } else {
1781 err.span_suggestion_verbose(
1782 item.vis_span.shrink_to_hi(),
1783 msg,
1784 " async",
1785 Applicability::MaybeIncorrect,
1786 );
1787 }
1788 }
1789 }
1790 }
1791 }
1792
1793 pub(super) fn suggest_change_mut(
1796 &self,
1797 obligation: &PredicateObligation<'tcx>,
1798 err: &mut Diag<'_>,
1799 trait_pred: ty::PolyTraitPredicate<'tcx>,
1800 ) {
1801 let points_at_arg =
1802 #[allow(non_exhaustive_omitted_patterns)] match obligation.cause.code() {
ObligationCauseCode::FunctionArg { .. } => true,
_ => false,
}matches!(obligation.cause.code(), ObligationCauseCode::FunctionArg { .. },);
1803
1804 let span = obligation.cause.span;
1805 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1806 let refs_number =
1807 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1808 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
1809 return;
1811 }
1812 let trait_pred = self.resolve_vars_if_possible(trait_pred);
1813 if trait_pred.has_non_region_infer() {
1814 return;
1817 }
1818
1819 if let ty::Ref(region, t_type, mutability) = *trait_pred.skip_binder().self_ty().kind()
1821 {
1822 let suggested_ty = match mutability {
1823 hir::Mutability::Mut => Ty::new_imm_ref(self.tcx, region, t_type),
1824 hir::Mutability::Not => Ty::new_mut_ref(self.tcx, region, t_type),
1825 };
1826
1827 let trait_pred_and_suggested_ty =
1829 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1830
1831 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1832 obligation.param_env,
1833 trait_pred_and_suggested_ty,
1834 );
1835 let suggested_ty_would_satisfy_obligation = self
1836 .evaluate_obligation_no_overflow(&new_obligation)
1837 .must_apply_modulo_regions();
1838 if suggested_ty_would_satisfy_obligation {
1839 let sp = self
1840 .tcx
1841 .sess
1842 .source_map()
1843 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1844 if points_at_arg && mutability.is_not() && refs_number > 0 {
1845 if snippet
1847 .trim_start_matches(|c: char| c.is_whitespace() || c == '&')
1848 .starts_with("mut")
1849 {
1850 return;
1851 }
1852 err.span_suggestion_verbose(
1853 sp,
1854 "consider changing this borrow's mutability",
1855 "&mut ",
1856 Applicability::MachineApplicable,
1857 );
1858 } else {
1859 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!(
1860 "`{}` is implemented for `{}`, but not for `{}`",
1861 trait_pred.print_modifiers_and_trait_path(),
1862 suggested_ty,
1863 trait_pred.skip_binder().self_ty(),
1864 ));
1865 }
1866 }
1867 }
1868 }
1869 }
1870
1871 pub(super) fn suggest_semicolon_removal(
1872 &self,
1873 obligation: &PredicateObligation<'tcx>,
1874 err: &mut Diag<'_>,
1875 span: Span,
1876 trait_pred: ty::PolyTraitPredicate<'tcx>,
1877 ) -> bool {
1878 let node = self.tcx.hir_node_by_def_id(obligation.cause.body_id);
1879 if let hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn {sig, body: body_id, .. }, .. }) = node
1880 && let hir::ExprKind::Block(blk, _) = &self.tcx.hir_body(*body_id).value.kind
1881 && sig.decl.output.span().overlaps(span)
1882 && blk.expr.is_none()
1883 && trait_pred.self_ty().skip_binder().is_unit()
1884 && let Some(stmt) = blk.stmts.last()
1885 && let hir::StmtKind::Semi(expr) = stmt.kind
1886 && let Some(typeck_results) = &self.typeck_results
1888 && let Some(ty) = typeck_results.expr_ty_opt(expr)
1889 && self.predicate_may_hold(&self.mk_trait_obligation_with_new_self_ty(
1890 obligation.param_env, trait_pred.map_bound(|trait_pred| (trait_pred, ty))
1891 ))
1892 {
1893 err.span_label(
1894 expr.span,
1895 ::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!(
1896 "this expression has type `{}`, which implements `{}`",
1897 ty,
1898 trait_pred.print_modifiers_and_trait_path()
1899 ),
1900 );
1901 err.span_suggestion(
1902 self.tcx.sess.source_map().end_point(stmt.span),
1903 "remove this semicolon",
1904 "",
1905 Applicability::MachineApplicable,
1906 );
1907 return true;
1908 }
1909 false
1910 }
1911
1912 pub(super) fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span> {
1913 let hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn { sig, .. }, .. }) =
1914 self.tcx.hir_node_by_def_id(obligation.cause.body_id)
1915 else {
1916 return None;
1917 };
1918
1919 if let hir::FnRetTy::Return(ret_ty) = sig.decl.output { Some(ret_ty.span) } else { None }
1920 }
1921
1922 pub(super) fn suggest_impl_trait(
1926 &self,
1927 err: &mut Diag<'_>,
1928 obligation: &PredicateObligation<'tcx>,
1929 trait_pred: ty::PolyTraitPredicate<'tcx>,
1930 ) -> bool {
1931 let ObligationCauseCode::SizedReturnType = obligation.cause.code() else {
1932 return false;
1933 };
1934 let ty::Dynamic(_, _) = trait_pred.self_ty().skip_binder().kind() else {
1935 return false;
1936 };
1937 if let Node::Item(hir::Item { kind: hir::ItemKind::Fn { sig: fn_sig, .. }, .. })
1938 | Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(fn_sig, _), .. })
1939 | Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(fn_sig, _), .. }) =
1940 self.tcx.hir_node_by_def_id(obligation.cause.body_id)
1941 && let hir::FnRetTy::Return(ty) = fn_sig.decl.output
1942 && let hir::TyKind::Path(qpath) = ty.kind
1943 && let hir::QPath::Resolved(None, path) = qpath
1944 && let Res::Def(DefKind::TyAlias, def_id) = path.res
1945 {
1946 err.span_note(self.tcx.def_span(def_id), "this type alias is unsized");
1950 err.multipart_suggestion(
1951 ::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!(
1952 "consider boxing the return type, and wrapping all of the returned values in \
1953 `Box::new`",
1954 ),
1955 ::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![
1956 (ty.span.shrink_to_lo(), "Box<".to_string()),
1957 (ty.span.shrink_to_hi(), ">".to_string()),
1958 ],
1959 Applicability::MaybeIncorrect,
1960 );
1961 return false;
1962 }
1963
1964 err.code(E0746);
1965 err.primary_message("return type cannot be a trait object without pointer indirection");
1966 err.children.clear();
1967
1968 let mut span = obligation.cause.span;
1969 if let DefKind::Closure = self.tcx.def_kind(obligation.cause.body_id)
1970 && let parent = self.tcx.parent(obligation.cause.body_id.into())
1971 && let DefKind::Fn | DefKind::AssocFn = self.tcx.def_kind(parent)
1972 && self.tcx.asyncness(parent).is_async()
1973 && let Some(parent) = parent.as_local()
1974 && let Node::Item(hir::Item { kind: hir::ItemKind::Fn { sig: fn_sig, .. }, .. })
1975 | Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(fn_sig, _), .. })
1976 | Node::TraitItem(hir::TraitItem {
1977 kind: hir::TraitItemKind::Fn(fn_sig, _), ..
1978 }) = self.tcx.hir_node_by_def_id(parent)
1979 {
1980 span = fn_sig.decl.output.span();
1985 err.span(span);
1986 }
1987 let body = self.tcx.hir_body_owned_by(obligation.cause.body_id);
1988
1989 let mut visitor = ReturnsVisitor::default();
1990 visitor.visit_body(&body);
1991
1992 let (pre, impl_span) = if let Ok(snip) = self.tcx.sess.source_map().span_to_snippet(span)
1993 && snip.starts_with("dyn ")
1994 {
1995 ("", span.with_hi(span.lo() + BytePos(4)))
1996 } else {
1997 ("dyn ", span.shrink_to_lo())
1998 };
1999
2000 err.span_suggestion_verbose(
2001 impl_span,
2002 "consider returning an `impl Trait` instead of a `dyn Trait`",
2003 "impl ",
2004 Applicability::MaybeIncorrect,
2005 );
2006
2007 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![
2008 (span.shrink_to_lo(), format!("Box<{pre}")),
2009 (span.shrink_to_hi(), ">".to_string()),
2010 ];
2011 sugg.extend(visitor.returns.into_iter().flat_map(|expr| {
2012 let span =
2013 expr.span.find_ancestor_in_same_ctxt(obligation.cause.span).unwrap_or(expr.span);
2014 if !span.can_be_used_for_suggestions() {
2015 ::alloc::vec::Vec::new()vec![]
2016 } else if let hir::ExprKind::Call(path, ..) = expr.kind
2017 && let hir::ExprKind::Path(hir::QPath::TypeRelative(ty, method)) = path.kind
2018 && method.ident.name == sym::new
2019 && let hir::TyKind::Path(hir::QPath::Resolved(.., box_path)) = ty.kind
2020 && box_path
2021 .res
2022 .opt_def_id()
2023 .is_some_and(|def_id| self.tcx.is_lang_item(def_id, LangItem::OwnedBox))
2024 {
2025 ::alloc::vec::Vec::new()vec![]
2027 } else {
2028 ::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![
2029 (span.shrink_to_lo(), "Box::new(".to_string()),
2030 (span.shrink_to_hi(), ")".to_string()),
2031 ]
2032 }
2033 }));
2034
2035 err.multipart_suggestion(
2036 ::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!(
2037 "alternatively, box the return type, and wrap all of the returned values in \
2038 `Box::new`",
2039 ),
2040 sugg,
2041 Applicability::MaybeIncorrect,
2042 );
2043
2044 true
2045 }
2046
2047 pub(super) fn report_closure_arg_mismatch(
2048 &self,
2049 span: Span,
2050 found_span: Option<Span>,
2051 found: ty::TraitRef<'tcx>,
2052 expected: ty::TraitRef<'tcx>,
2053 cause: &ObligationCauseCode<'tcx>,
2054 found_node: Option<Node<'_>>,
2055 param_env: ty::ParamEnv<'tcx>,
2056 ) -> Diag<'a> {
2057 pub(crate) fn build_fn_sig_ty<'tcx>(
2058 infcx: &InferCtxt<'tcx>,
2059 trait_ref: ty::TraitRef<'tcx>,
2060 ) -> Ty<'tcx> {
2061 let inputs = trait_ref.args.type_at(1);
2062 let sig = match inputs.kind() {
2063 ty::Tuple(inputs) if infcx.tcx.is_fn_trait(trait_ref.def_id) => {
2064 infcx.tcx.mk_fn_sig(
2065 *inputs,
2066 infcx.next_ty_var(DUMMY_SP),
2067 false,
2068 hir::Safety::Safe,
2069 ExternAbi::Rust,
2070 )
2071 }
2072 _ => infcx.tcx.mk_fn_sig(
2073 [inputs],
2074 infcx.next_ty_var(DUMMY_SP),
2075 false,
2076 hir::Safety::Safe,
2077 ExternAbi::Rust,
2078 ),
2079 };
2080
2081 Ty::new_fn_ptr(infcx.tcx, ty::Binder::dummy(sig))
2082 }
2083
2084 let argument_kind = match expected.self_ty().kind() {
2085 ty::Closure(..) => "closure",
2086 ty::Coroutine(..) => "coroutine",
2087 _ => "function",
2088 };
2089 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!(
2090 self.dcx(),
2091 span,
2092 E0631,
2093 "type mismatch in {argument_kind} arguments",
2094 );
2095
2096 err.span_label(span, "expected due to this");
2097
2098 let found_span = found_span.unwrap_or(span);
2099 err.span_label(found_span, "found signature defined here");
2100
2101 let expected = build_fn_sig_ty(self, expected);
2102 let found = build_fn_sig_ty(self, found);
2103
2104 let (expected_str, found_str) = self.cmp(expected, found);
2105
2106 let signature_kind = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} signature", argument_kind))
})format!("{argument_kind} signature");
2107 err.note_expected_found(&signature_kind, expected_str, &signature_kind, found_str);
2108
2109 self.note_conflicting_fn_args(&mut err, cause, expected, found, param_env);
2110 self.note_conflicting_closure_bounds(cause, &mut err);
2111
2112 if let Some(found_node) = found_node {
2113 hint_missing_borrow(self, param_env, span, found, expected, found_node, &mut err);
2114 }
2115
2116 err
2117 }
2118
2119 fn note_conflicting_fn_args(
2120 &self,
2121 err: &mut Diag<'_>,
2122 cause: &ObligationCauseCode<'tcx>,
2123 expected: Ty<'tcx>,
2124 found: Ty<'tcx>,
2125 param_env: ty::ParamEnv<'tcx>,
2126 ) {
2127 let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = cause else {
2128 return;
2129 };
2130 let ty::FnPtr(sig_tys, hdr) = expected.kind() else {
2131 return;
2132 };
2133 let expected = sig_tys.with(*hdr);
2134 let ty::FnPtr(sig_tys, hdr) = found.kind() else {
2135 return;
2136 };
2137 let found = sig_tys.with(*hdr);
2138 let Node::Expr(arg) = self.tcx.hir_node(*arg_hir_id) else {
2139 return;
2140 };
2141 let hir::ExprKind::Path(path) = arg.kind else {
2142 return;
2143 };
2144 let expected_inputs = self.tcx.instantiate_bound_regions_with_erased(expected).inputs();
2145 let found_inputs = self.tcx.instantiate_bound_regions_with_erased(found).inputs();
2146 let both_tys = expected_inputs.iter().copied().zip(found_inputs.iter().copied());
2147
2148 let arg_expr = |infcx: &InferCtxt<'tcx>, name, expected: Ty<'tcx>, found: Ty<'tcx>| {
2149 let (expected_ty, expected_refs) = get_deref_type_and_refs(expected);
2150 let (found_ty, found_refs) = get_deref_type_and_refs(found);
2151
2152 if infcx.can_eq(param_env, found_ty, expected_ty) {
2153 if found_refs.len() == expected_refs.len()
2154 && found_refs.iter().eq(expected_refs.iter())
2155 {
2156 name
2157 } else if found_refs.len() > expected_refs.len() {
2158 let refs = &found_refs[..found_refs.len() - expected_refs.len()];
2159 if found_refs[..expected_refs.len()].iter().eq(expected_refs.iter()) {
2160 ::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!(
2161 "{}{name}",
2162 refs.iter()
2163 .map(|mutbl| format!("&{}", mutbl.prefix_str()))
2164 .collect::<Vec<_>>()
2165 .join(""),
2166 )
2167 } else {
2168 ::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!(
2170 "{}*{name}",
2171 refs.iter()
2172 .map(|mutbl| format!("&{}", mutbl.prefix_str()))
2173 .collect::<Vec<_>>()
2174 .join(""),
2175 )
2176 }
2177 } else if expected_refs.len() > found_refs.len() {
2178 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}",
(0..(expected_refs.len() -
found_refs.len())).map(|_|
"*").collect::<Vec<_>>().join(""), name))
})format!(
2179 "{}{name}",
2180 (0..(expected_refs.len() - found_refs.len()))
2181 .map(|_| "*")
2182 .collect::<Vec<_>>()
2183 .join(""),
2184 )
2185 } else {
2186 ::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!(
2187 "{}{name}",
2188 found_refs
2189 .iter()
2190 .map(|mutbl| format!("&{}", mutbl.prefix_str()))
2191 .chain(found_refs.iter().map(|_| "*".to_string()))
2192 .collect::<Vec<_>>()
2193 .join(""),
2194 )
2195 }
2196 } else {
2197 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("/* {0} */", found))
})format!("/* {found} */")
2198 }
2199 };
2200 let args_have_same_underlying_type = both_tys.clone().all(|(expected, found)| {
2201 let (expected_ty, _) = get_deref_type_and_refs(expected);
2202 let (found_ty, _) = get_deref_type_and_refs(found);
2203 self.can_eq(param_env, found_ty, expected_ty)
2204 });
2205 let (closure_names, call_names): (Vec<_>, Vec<_>) = if args_have_same_underlying_type
2206 && !expected_inputs.is_empty()
2207 && expected_inputs.len() == found_inputs.len()
2208 && let Some(typeck) = &self.typeck_results
2209 && let Res::Def(res_kind, fn_def_id) = typeck.qpath_res(&path, *arg_hir_id)
2210 && res_kind.is_fn_like()
2211 {
2212 let closure: Vec<_> = self
2213 .tcx
2214 .fn_arg_idents(fn_def_id)
2215 .iter()
2216 .enumerate()
2217 .map(|(i, ident)| {
2218 if let Some(ident) = ident
2219 && !#[allow(non_exhaustive_omitted_patterns)] match ident {
Ident { name: kw::Underscore | kw::SelfLower, .. } => true,
_ => false,
}matches!(ident, Ident { name: kw::Underscore | kw::SelfLower, .. })
2220 {
2221 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", ident))
})format!("{ident}")
2222 } else {
2223 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("arg{0}", i))
})format!("arg{i}")
2224 }
2225 })
2226 .collect();
2227 let args = closure
2228 .iter()
2229 .zip(both_tys)
2230 .map(|(name, (expected, found))| {
2231 arg_expr(self.infcx, name.to_owned(), expected, found)
2232 })
2233 .collect();
2234 (closure, args)
2235 } else {
2236 let closure_args = expected_inputs
2237 .iter()
2238 .enumerate()
2239 .map(|(i, _)| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("arg{0}", i))
})format!("arg{i}"))
2240 .collect::<Vec<_>>();
2241 let call_args = both_tys
2242 .enumerate()
2243 .map(|(i, (expected, found))| {
2244 arg_expr(self.infcx, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("arg{0}", i))
})format!("arg{i}"), expected, found)
2245 })
2246 .collect::<Vec<_>>();
2247 (closure_args, call_args)
2248 };
2249 let closure_names: Vec<_> = closure_names
2250 .into_iter()
2251 .zip(expected_inputs.iter())
2252 .map(|(name, ty)| {
2253 ::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!(
2254 "{name}{}",
2255 if ty.has_infer_types() {
2256 String::new()
2257 } else if ty.references_error() {
2258 ": /* type */".to_string()
2259 } else {
2260 format!(": {ty}")
2261 }
2262 )
2263 })
2264 .collect();
2265 err.multipart_suggestion(
2266 "consider wrapping the function in a closure",
2267 ::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![
2268 (arg.span.shrink_to_lo(), format!("|{}| ", closure_names.join(", "))),
2269 (arg.span.shrink_to_hi(), format!("({})", call_names.join(", "))),
2270 ],
2271 Applicability::MaybeIncorrect,
2272 );
2273 }
2274
2275 fn note_conflicting_closure_bounds(
2278 &self,
2279 cause: &ObligationCauseCode<'tcx>,
2280 err: &mut Diag<'_>,
2281 ) {
2282 if let ObligationCauseCode::WhereClauseInExpr(def_id, _, _, idx) = *cause
2286 && let predicates = self.tcx.predicates_of(def_id).instantiate_identity(self.tcx)
2287 && let Some(pred) = predicates.predicates.get(idx)
2288 && let ty::ClauseKind::Trait(trait_pred) = pred.kind().skip_binder()
2289 && self.tcx.is_fn_trait(trait_pred.def_id())
2290 {
2291 let expected_self =
2292 self.tcx.anonymize_bound_vars(pred.kind().rebind(trait_pred.self_ty()));
2293 let expected_args =
2294 self.tcx.anonymize_bound_vars(pred.kind().rebind(trait_pred.trait_ref.args));
2295
2296 let other_pred = predicates.into_iter().enumerate().find(|&(other_idx, (pred, _))| {
2299 match pred.kind().skip_binder() {
2300 ty::ClauseKind::Trait(trait_pred)
2301 if self.tcx.is_fn_trait(trait_pred.def_id())
2302 && other_idx != idx
2303 && expected_self
2306 == self.tcx.anonymize_bound_vars(
2307 pred.kind().rebind(trait_pred.self_ty()),
2308 )
2309 && expected_args
2311 != self.tcx.anonymize_bound_vars(
2312 pred.kind().rebind(trait_pred.trait_ref.args),
2313 ) =>
2314 {
2315 true
2316 }
2317 _ => false,
2318 }
2319 });
2320 if let Some((_, (_, other_pred_span))) = other_pred {
2322 err.span_note(
2323 other_pred_span,
2324 "closure inferred to have a different signature due to this bound",
2325 );
2326 }
2327 }
2328 }
2329
2330 pub(super) fn suggest_fully_qualified_path(
2331 &self,
2332 err: &mut Diag<'_>,
2333 item_def_id: DefId,
2334 span: Span,
2335 trait_ref: DefId,
2336 ) {
2337 if let Some(assoc_item) = self.tcx.opt_associated_item(item_def_id)
2338 && let ty::AssocKind::Const { .. } | ty::AssocKind::Type { .. } = assoc_item.kind
2339 {
2340 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!(
2341 "{}s cannot be accessed directly on a `trait`, they can only be \
2342 accessed through a specific `impl`",
2343 self.tcx.def_kind_descr(assoc_item.as_def_kind(), item_def_id)
2344 ));
2345
2346 if !assoc_item.is_impl_trait_in_trait() {
2347 err.span_suggestion_verbose(
2348 span,
2349 "use the fully qualified path to an implementation",
2350 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<Type as {0}>::{1}",
self.tcx.def_path_str(trait_ref), assoc_item.name()))
})format!(
2351 "<Type as {}>::{}",
2352 self.tcx.def_path_str(trait_ref),
2353 assoc_item.name()
2354 ),
2355 Applicability::HasPlaceholders,
2356 );
2357 }
2358 }
2359 }
2360
2361 #[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(2403u32),
::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:2442",
"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(2442u32),
::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:2449",
"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(2449u32),
::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:2479",
"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(2479u32),
::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:2510",
"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(2510u32),
::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:2520",
"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(2520u32),
::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:2533",
"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(2533u32),
::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:2554",
"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(2554u32),
::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:2578",
"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(2578u32),
::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:2586",
"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(2586u32),
::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:2590",
"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(2590u32),
::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:2593",
"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(2593u32),
::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:2614",
"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(2614u32),
::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))]
2404 pub fn maybe_note_obligation_cause_for_async_await<G: EmissionGuarantee>(
2405 &self,
2406 err: &mut Diag<'_, G>,
2407 obligation: &PredicateObligation<'tcx>,
2408 ) -> bool {
2409 let (mut trait_ref, mut target_ty) = match obligation.predicate.kind().skip_binder() {
2432 ty::PredicateKind::Clause(ty::ClauseKind::Trait(p)) => (Some(p), Some(p.self_ty())),
2433 _ => (None, None),
2434 };
2435 let mut coroutine = None;
2436 let mut outer_coroutine = None;
2437 let mut next_code = Some(obligation.cause.code());
2438
2439 let mut seen_upvar_tys_infer_tuple = false;
2440
2441 while let Some(code) = next_code {
2442 debug!(?code);
2443 match code {
2444 ObligationCauseCode::FunctionArg { parent_code, .. } => {
2445 next_code = Some(parent_code);
2446 }
2447 ObligationCauseCode::ImplDerived(cause) => {
2448 let ty = cause.derived.parent_trait_pred.skip_binder().self_ty();
2449 debug!(
2450 parent_trait_ref = ?cause.derived.parent_trait_pred,
2451 self_ty.kind = ?ty.kind(),
2452 "ImplDerived",
2453 );
2454
2455 match *ty.kind() {
2456 ty::Coroutine(did, ..) | ty::CoroutineWitness(did, _) => {
2457 coroutine = coroutine.or(Some(did));
2458 outer_coroutine = Some(did);
2459 }
2460 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
2461 seen_upvar_tys_infer_tuple = true;
2466 }
2467 _ if coroutine.is_none() => {
2468 trait_ref = Some(cause.derived.parent_trait_pred.skip_binder());
2469 target_ty = Some(ty);
2470 }
2471 _ => {}
2472 }
2473
2474 next_code = Some(&cause.derived.parent_code);
2475 }
2476 ObligationCauseCode::WellFormedDerived(derived_obligation)
2477 | ObligationCauseCode::BuiltinDerived(derived_obligation) => {
2478 let ty = derived_obligation.parent_trait_pred.skip_binder().self_ty();
2479 debug!(
2480 parent_trait_ref = ?derived_obligation.parent_trait_pred,
2481 self_ty.kind = ?ty.kind(),
2482 );
2483
2484 match *ty.kind() {
2485 ty::Coroutine(did, ..) | ty::CoroutineWitness(did, ..) => {
2486 coroutine = coroutine.or(Some(did));
2487 outer_coroutine = Some(did);
2488 }
2489 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
2490 seen_upvar_tys_infer_tuple = true;
2495 }
2496 _ if coroutine.is_none() => {
2497 trait_ref = Some(derived_obligation.parent_trait_pred.skip_binder());
2498 target_ty = Some(ty);
2499 }
2500 _ => {}
2501 }
2502
2503 next_code = Some(&derived_obligation.parent_code);
2504 }
2505 _ => break,
2506 }
2507 }
2508
2509 debug!(?coroutine, ?trait_ref, ?target_ty);
2511 let (Some(coroutine_did), Some(trait_ref), Some(target_ty)) =
2512 (coroutine, trait_ref, target_ty)
2513 else {
2514 return false;
2515 };
2516
2517 let span = self.tcx.def_span(coroutine_did);
2518
2519 let coroutine_did_root = self.tcx.typeck_root_def_id(coroutine_did);
2520 debug!(
2521 ?coroutine_did,
2522 ?coroutine_did_root,
2523 typeck_results.hir_owner = ?self.typeck_results.as_ref().map(|t| t.hir_owner),
2524 ?span,
2525 );
2526
2527 let coroutine_body =
2528 coroutine_did.as_local().and_then(|def_id| self.tcx.hir_maybe_body_owned_by(def_id));
2529 let mut visitor = AwaitsVisitor::default();
2530 if let Some(body) = coroutine_body {
2531 visitor.visit_body(&body);
2532 }
2533 debug!(awaits = ?visitor.awaits);
2534
2535 let target_ty_erased = self.tcx.erase_and_anonymize_regions(target_ty);
2538 let ty_matches = |ty| -> bool {
2539 let ty_erased = self.tcx.instantiate_bound_regions_with_erased(ty);
2552 let ty_erased = self.tcx.erase_and_anonymize_regions(ty_erased);
2553 let eq = ty_erased == target_ty_erased;
2554 debug!(?ty_erased, ?target_ty_erased, ?eq);
2555 eq
2556 };
2557
2558 let coroutine_data = match &self.typeck_results {
2563 Some(t) if t.hir_owner.to_def_id() == coroutine_did_root => CoroutineData(t),
2564 _ if coroutine_did.is_local() => {
2565 CoroutineData(self.tcx.typeck(coroutine_did.expect_local()))
2566 }
2567 _ => return false,
2568 };
2569
2570 let coroutine_within_in_progress_typeck = match &self.typeck_results {
2571 Some(t) => t.hir_owner.to_def_id() == coroutine_did_root,
2572 _ => false,
2573 };
2574
2575 let mut interior_or_upvar_span = None;
2576
2577 let from_awaited_ty = coroutine_data.get_from_await_ty(visitor, self.tcx, ty_matches);
2578 debug!(?from_awaited_ty);
2579
2580 if coroutine_did.is_local()
2582 && !coroutine_within_in_progress_typeck
2584 && let Some(coroutine_info) = self.tcx.mir_coroutine_witnesses(coroutine_did)
2585 {
2586 debug!(?coroutine_info);
2587 'find_source: for (variant, source_info) in
2588 coroutine_info.variant_fields.iter().zip(&coroutine_info.variant_source_info)
2589 {
2590 debug!(?variant);
2591 for &local in variant {
2592 let decl = &coroutine_info.field_tys[local];
2593 debug!(?decl);
2594 if ty_matches(ty::Binder::dummy(decl.ty)) && !decl.ignore_for_traits {
2595 interior_or_upvar_span = Some(CoroutineInteriorOrUpvar::Interior(
2596 decl.source_info.span,
2597 Some((source_info.span, from_awaited_ty)),
2598 ));
2599 break 'find_source;
2600 }
2601 }
2602 }
2603 }
2604
2605 if interior_or_upvar_span.is_none() {
2606 interior_or_upvar_span =
2607 coroutine_data.try_get_upvar_span(self, coroutine_did, ty_matches);
2608 }
2609
2610 if interior_or_upvar_span.is_none() && !coroutine_did.is_local() {
2611 interior_or_upvar_span = Some(CoroutineInteriorOrUpvar::Interior(span, None));
2612 }
2613
2614 debug!(?interior_or_upvar_span);
2615 if let Some(interior_or_upvar_span) = interior_or_upvar_span {
2616 let is_async = self.tcx.coroutine_is_async(coroutine_did);
2617 self.note_obligation_cause_for_async_await(
2618 err,
2619 interior_or_upvar_span,
2620 is_async,
2621 outer_coroutine,
2622 trait_ref,
2623 target_ty,
2624 obligation,
2625 next_code,
2626 );
2627 true
2628 } else {
2629 false
2630 }
2631 }
2632
2633 #[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(2635u32),
::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:2858",
"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(2858u32),
::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)]
2636 fn note_obligation_cause_for_async_await<G: EmissionGuarantee>(
2637 &self,
2638 err: &mut Diag<'_, G>,
2639 interior_or_upvar_span: CoroutineInteriorOrUpvar,
2640 is_async: bool,
2641 outer_coroutine: Option<DefId>,
2642 trait_pred: ty::TraitPredicate<'tcx>,
2643 target_ty: Ty<'tcx>,
2644 obligation: &PredicateObligation<'tcx>,
2645 next_code: Option<&ObligationCauseCode<'tcx>>,
2646 ) {
2647 let source_map = self.tcx.sess.source_map();
2648
2649 let (await_or_yield, an_await_or_yield) =
2650 if is_async { ("await", "an await") } else { ("yield", "a yield") };
2651 let future_or_coroutine = if is_async { "future" } else { "coroutine" };
2652
2653 let trait_explanation = if let Some(name @ (sym::Send | sym::Sync)) =
2656 self.tcx.get_diagnostic_name(trait_pred.def_id())
2657 {
2658 let (trait_name, trait_verb) =
2659 if name == sym::Send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
2660
2661 err.code = None;
2662 err.primary_message(format!(
2663 "{future_or_coroutine} cannot be {trait_verb} between threads safely"
2664 ));
2665
2666 let original_span = err.span.primary_span().unwrap();
2667 let mut span = MultiSpan::from_span(original_span);
2668
2669 let message = outer_coroutine
2670 .and_then(|coroutine_did| {
2671 Some(match self.tcx.coroutine_kind(coroutine_did).unwrap() {
2672 CoroutineKind::Coroutine(_) => format!("coroutine is not {trait_name}"),
2673 CoroutineKind::Desugared(
2674 CoroutineDesugaring::Async,
2675 CoroutineSource::Fn,
2676 ) => self
2677 .tcx
2678 .parent(coroutine_did)
2679 .as_local()
2680 .map(|parent_did| self.tcx.local_def_id_to_hir_id(parent_did))
2681 .and_then(|parent_hir_id| self.tcx.hir_opt_name(parent_hir_id))
2682 .map(|name| {
2683 format!("future returned by `{name}` is not {trait_name}")
2684 })?,
2685 CoroutineKind::Desugared(
2686 CoroutineDesugaring::Async,
2687 CoroutineSource::Block,
2688 ) => {
2689 format!("future created by async block is not {trait_name}")
2690 }
2691 CoroutineKind::Desugared(
2692 CoroutineDesugaring::Async,
2693 CoroutineSource::Closure,
2694 ) => {
2695 format!("future created by async closure is not {trait_name}")
2696 }
2697 CoroutineKind::Desugared(
2698 CoroutineDesugaring::AsyncGen,
2699 CoroutineSource::Fn,
2700 ) => self
2701 .tcx
2702 .parent(coroutine_did)
2703 .as_local()
2704 .map(|parent_did| self.tcx.local_def_id_to_hir_id(parent_did))
2705 .and_then(|parent_hir_id| self.tcx.hir_opt_name(parent_hir_id))
2706 .map(|name| {
2707 format!("async iterator returned by `{name}` is not {trait_name}")
2708 })?,
2709 CoroutineKind::Desugared(
2710 CoroutineDesugaring::AsyncGen,
2711 CoroutineSource::Block,
2712 ) => {
2713 format!("async iterator created by async gen block is not {trait_name}")
2714 }
2715 CoroutineKind::Desugared(
2716 CoroutineDesugaring::AsyncGen,
2717 CoroutineSource::Closure,
2718 ) => {
2719 format!(
2720 "async iterator created by async gen closure is not {trait_name}"
2721 )
2722 }
2723 CoroutineKind::Desugared(CoroutineDesugaring::Gen, CoroutineSource::Fn) => {
2724 self.tcx
2725 .parent(coroutine_did)
2726 .as_local()
2727 .map(|parent_did| self.tcx.local_def_id_to_hir_id(parent_did))
2728 .and_then(|parent_hir_id| self.tcx.hir_opt_name(parent_hir_id))
2729 .map(|name| {
2730 format!("iterator returned by `{name}` is not {trait_name}")
2731 })?
2732 }
2733 CoroutineKind::Desugared(
2734 CoroutineDesugaring::Gen,
2735 CoroutineSource::Block,
2736 ) => {
2737 format!("iterator created by gen block is not {trait_name}")
2738 }
2739 CoroutineKind::Desugared(
2740 CoroutineDesugaring::Gen,
2741 CoroutineSource::Closure,
2742 ) => {
2743 format!("iterator created by gen closure is not {trait_name}")
2744 }
2745 })
2746 })
2747 .unwrap_or_else(|| format!("{future_or_coroutine} is not {trait_name}"));
2748
2749 span.push_span_label(original_span, message);
2750 err.span(span);
2751
2752 format!("is not {trait_name}")
2753 } else {
2754 format!("does not implement `{}`", trait_pred.print_modifiers_and_trait_path())
2755 };
2756
2757 let mut explain_yield = |interior_span: Span, yield_span: Span| {
2758 let mut span = MultiSpan::from_span(yield_span);
2759 let snippet = match source_map.span_to_snippet(interior_span) {
2760 Ok(snippet) if !snippet.contains('\n') => format!("`{snippet}`"),
2763 _ => "the value".to_string(),
2764 };
2765 span.push_span_label(
2782 yield_span,
2783 format!("{await_or_yield} occurs here, with {snippet} maybe used later"),
2784 );
2785 span.push_span_label(
2786 interior_span,
2787 format!("has type `{target_ty}` which {trait_explanation}"),
2788 );
2789 err.span_note(
2790 span,
2791 format!("{future_or_coroutine} {trait_explanation} as this value is used across {an_await_or_yield}"),
2792 );
2793 };
2794 match interior_or_upvar_span {
2795 CoroutineInteriorOrUpvar::Interior(interior_span, interior_extra_info) => {
2796 if let Some((yield_span, from_awaited_ty)) = interior_extra_info {
2797 if let Some(await_span) = from_awaited_ty {
2798 let mut span = MultiSpan::from_span(await_span);
2800 span.push_span_label(
2801 await_span,
2802 format!(
2803 "await occurs here on type `{target_ty}`, which {trait_explanation}"
2804 ),
2805 );
2806 err.span_note(
2807 span,
2808 format!(
2809 "future {trait_explanation} as it awaits another future which {trait_explanation}"
2810 ),
2811 );
2812 } else {
2813 explain_yield(interior_span, yield_span);
2815 }
2816 }
2817 }
2818 CoroutineInteriorOrUpvar::Upvar(upvar_span) => {
2819 let non_send = match target_ty.kind() {
2821 ty::Ref(_, ref_ty, mutability) => match self.evaluate_obligation(obligation) {
2822 Ok(eval) if !eval.may_apply() => Some((ref_ty, mutability.is_mut())),
2823 _ => None,
2824 },
2825 _ => None,
2826 };
2827
2828 let (span_label, span_note) = match non_send {
2829 Some((ref_ty, is_mut)) => {
2833 let ref_ty_trait = if is_mut { "Send" } else { "Sync" };
2834 let ref_kind = if is_mut { "&mut" } else { "&" };
2835 (
2836 format!(
2837 "has type `{target_ty}` which {trait_explanation}, because `{ref_ty}` is not `{ref_ty_trait}`"
2838 ),
2839 format!(
2840 "captured value {trait_explanation} because `{ref_kind}` references cannot be sent unless their referent is `{ref_ty_trait}`"
2841 ),
2842 )
2843 }
2844 None => (
2845 format!("has type `{target_ty}` which {trait_explanation}"),
2846 format!("captured value {trait_explanation}"),
2847 ),
2848 };
2849
2850 let mut span = MultiSpan::from_span(upvar_span);
2851 span.push_span_label(upvar_span, span_label);
2852 err.span_note(span, span_note);
2853 }
2854 }
2855
2856 debug!(?next_code);
2859 self.note_obligation_cause_code(
2860 obligation.cause.body_id,
2861 err,
2862 obligation.predicate,
2863 obligation.param_env,
2864 next_code.unwrap(),
2865 &mut Vec::new(),
2866 &mut Default::default(),
2867 );
2868 }
2869
2870 pub(super) fn note_obligation_cause_code<G: EmissionGuarantee, T>(
2871 &self,
2872 body_id: LocalDefId,
2873 err: &mut Diag<'_, G>,
2874 predicate: T,
2875 param_env: ty::ParamEnv<'tcx>,
2876 cause_code: &ObligationCauseCode<'tcx>,
2877 obligated_types: &mut Vec<Ty<'tcx>>,
2878 seen_requirements: &mut FxHashSet<DefId>,
2879 ) where
2880 T: Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>>,
2881 {
2882 let tcx = self.tcx;
2883 let predicate = predicate.upcast(tcx);
2884 let suggest_remove_deref = |err: &mut Diag<'_, G>, expr: &hir::Expr<'_>| {
2885 if let Some(pred) = predicate.as_trait_clause()
2886 && tcx.is_lang_item(pred.def_id(), LangItem::Sized)
2887 && let hir::ExprKind::Unary(hir::UnOp::Deref, inner) = expr.kind
2888 {
2889 err.span_suggestion_verbose(
2890 expr.span.until(inner.span),
2891 "references are always `Sized`, even if they point to unsized data; consider \
2892 not dereferencing the expression",
2893 String::new(),
2894 Applicability::MaybeIncorrect,
2895 );
2896 }
2897 };
2898 match *cause_code {
2899 ObligationCauseCode::ExprAssignable
2900 | ObligationCauseCode::MatchExpressionArm { .. }
2901 | ObligationCauseCode::Pattern { .. }
2902 | ObligationCauseCode::IfExpression { .. }
2903 | ObligationCauseCode::IfExpressionWithNoElse
2904 | ObligationCauseCode::MainFunctionType
2905 | ObligationCauseCode::LangFunctionType(_)
2906 | ObligationCauseCode::IntrinsicType
2907 | ObligationCauseCode::MethodReceiver
2908 | ObligationCauseCode::ReturnNoExpression
2909 | ObligationCauseCode::Misc
2910 | ObligationCauseCode::WellFormed(..)
2911 | ObligationCauseCode::MatchImpl(..)
2912 | ObligationCauseCode::ReturnValue(_)
2913 | ObligationCauseCode::BlockTailExpression(..)
2914 | ObligationCauseCode::AwaitableExpr(_)
2915 | ObligationCauseCode::ForLoopIterator
2916 | ObligationCauseCode::QuestionMark
2917 | ObligationCauseCode::CheckAssociatedTypeBounds { .. }
2918 | ObligationCauseCode::LetElse
2919 | ObligationCauseCode::UnOp { .. }
2920 | ObligationCauseCode::BinOp { .. }
2921 | ObligationCauseCode::AscribeUserTypeProvePredicate(..)
2922 | ObligationCauseCode::AlwaysApplicableImpl
2923 | ObligationCauseCode::ConstParam(_)
2924 | ObligationCauseCode::ReferenceOutlivesReferent(..)
2925 | ObligationCauseCode::ObjectTypeBound(..) => {}
2926 ObligationCauseCode::RustCall => {
2927 if let Some(pred) = predicate.as_trait_clause()
2928 && tcx.is_lang_item(pred.def_id(), LangItem::Sized)
2929 {
2930 err.note("argument required to be sized due to `extern \"rust-call\"` ABI");
2931 }
2932 }
2933 ObligationCauseCode::SliceOrArrayElem => {
2934 err.note("slice and array elements must have `Sized` type");
2935 }
2936 ObligationCauseCode::ArrayLen(array_ty) => {
2937 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`"));
2938 }
2939 ObligationCauseCode::TupleElem => {
2940 err.note("only the last element of a tuple may have a dynamically sized type");
2941 }
2942 ObligationCauseCode::DynCompatible(span) => {
2943 err.multipart_suggestion(
2944 "you might have meant to use `Self` to refer to the implementing type",
2945 ::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())],
2946 Applicability::MachineApplicable,
2947 );
2948 }
2949 ObligationCauseCode::WhereClause(item_def_id, span)
2950 | ObligationCauseCode::WhereClauseInExpr(item_def_id, span, ..)
2951 | ObligationCauseCode::HostEffectInExpr(item_def_id, span, ..)
2952 if !span.is_dummy() =>
2953 {
2954 if let ObligationCauseCode::WhereClauseInExpr(_, _, hir_id, pos) = &cause_code {
2955 if let Node::Expr(expr) = tcx.parent_hir_node(*hir_id)
2956 && let hir::ExprKind::Call(_, args) = expr.kind
2957 && let Some(expr) = args.get(*pos)
2958 {
2959 suggest_remove_deref(err, &expr);
2960 } else if let Node::Expr(expr) = self.tcx.hir_node(*hir_id)
2961 && let hir::ExprKind::MethodCall(_, _, args, _) = expr.kind
2962 && let Some(expr) = args.get(*pos)
2963 {
2964 suggest_remove_deref(err, &expr);
2965 }
2966 }
2967 let item_name = tcx.def_path_str(item_def_id);
2968 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));
2969 let mut multispan = MultiSpan::from(span);
2970 let sm = tcx.sess.source_map();
2971 if let Some(ident) = tcx.opt_item_ident(item_def_id) {
2972 let same_line =
2973 match (sm.lookup_line(ident.span.hi()), sm.lookup_line(span.lo())) {
2974 (Ok(l), Ok(r)) => l.line == r.line,
2975 _ => true,
2976 };
2977 if ident.span.is_visible(sm) && !ident.span.overlaps(span) && !same_line {
2978 multispan.push_span_label(
2979 ident.span,
2980 ::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!(
2981 "required by a bound in this {}",
2982 tcx.def_kind(item_def_id).descr(item_def_id)
2983 ),
2984 );
2985 }
2986 }
2987 let mut a = "a";
2988 let mut this = "this bound";
2989 let mut note = None;
2990 let mut help = None;
2991 if let ty::PredicateKind::Clause(clause) = predicate.kind().skip_binder() {
2992 match clause {
2993 ty::ClauseKind::Trait(trait_pred) => {
2994 let def_id = trait_pred.def_id();
2995 let visible_item = if let Some(local) = def_id.as_local() {
2996 let ty = trait_pred.self_ty();
2997 if let ty::Adt(adt, _) = ty.kind() {
3001 let visibilities = &tcx.resolutions(()).effective_visibilities;
3002 visibilities.effective_vis(local).is_none_or(|v| {
3003 v.at_level(Level::Reexported)
3004 .is_accessible_from(adt.did(), tcx)
3005 })
3006 } else {
3007 true
3009 }
3010 } else {
3011 tcx.visible_parent_map(()).get(&def_id).is_some()
3013 };
3014 if tcx.is_lang_item(def_id, LangItem::Sized) {
3015 if tcx
3017 .generics_of(item_def_id)
3018 .own_params
3019 .iter()
3020 .any(|param| tcx.def_span(param.def_id) == span)
3021 {
3022 a = "an implicit `Sized`";
3023 this =
3024 "the implicit `Sized` requirement on this type parameter";
3025 }
3026 if let Some(hir::Node::TraitItem(hir::TraitItem {
3027 generics,
3028 kind: hir::TraitItemKind::Type(bounds, None),
3029 ..
3030 })) = tcx.hir_get_if_local(item_def_id)
3031 && !bounds.iter()
3033 .filter_map(|bound| bound.trait_ref())
3034 .any(|tr| tr.trait_def_id().is_some_and(|def_id| tcx.is_lang_item(def_id, LangItem::Sized)))
3035 {
3036 let (span, separator) = if let [.., last] = bounds {
3037 (last.span().shrink_to_hi(), " +")
3038 } else {
3039 (generics.span.shrink_to_hi(), ":")
3040 };
3041 err.span_suggestion_verbose(
3042 span,
3043 "consider relaxing the implicit `Sized` restriction",
3044 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} ?Sized", separator))
})format!("{separator} ?Sized"),
3045 Applicability::MachineApplicable,
3046 );
3047 }
3048 }
3049 if let DefKind::Trait = tcx.def_kind(item_def_id)
3050 && !visible_item
3051 {
3052 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!(
3053 "`{short_item_name}` is a \"sealed trait\", because to implement it \
3054 you also need to implement `{}`, which is not accessible; this is \
3055 usually done to force you to use one of the provided types that \
3056 already implement it",
3057 with_no_trimmed_paths!(tcx.def_path_str(def_id)),
3058 ));
3059 let impls_of = tcx.trait_impls_of(def_id);
3060 let impls = impls_of
3061 .non_blanket_impls()
3062 .values()
3063 .flatten()
3064 .chain(impls_of.blanket_impls().iter())
3065 .collect::<Vec<_>>();
3066 if !impls.is_empty() {
3067 let len = impls.len();
3068 let mut types = impls
3069 .iter()
3070 .map(|&&t| {
3071 {
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!(
3072 " {}",
3073 tcx.type_of(t).instantiate_identity(),
3074 ))
3075 })
3076 .collect::<Vec<_>>();
3077 let post = if types.len() > 9 {
3078 types.truncate(8);
3079 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\nand {0} others", len - 8))
})format!("\nand {} others", len - 8)
3080 } else {
3081 String::new()
3082 };
3083 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!(
3084 "the following type{} implement{} the trait:\n{}{post}",
3085 pluralize!(len),
3086 if len == 1 { "s" } else { "" },
3087 types.join("\n"),
3088 ));
3089 }
3090 }
3091 }
3092 ty::ClauseKind::ConstArgHasType(..) => {
3093 let descr =
3094 ::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}`");
3095 if span.is_visible(sm) {
3096 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("required by this const generic parameter in `{0}`",
short_item_name))
})format!(
3097 "required by this const generic parameter in `{short_item_name}`"
3098 );
3099 multispan.push_span_label(span, msg);
3100 err.span_note(multispan, descr);
3101 } else {
3102 err.span_note(tcx.def_span(item_def_id), descr);
3103 }
3104 return;
3105 }
3106 _ => (),
3107 }
3108 }
3109
3110 let is_in_fmt_lit = if let Some(s) = err.span.primary_span() {
3113 #[allow(non_exhaustive_omitted_patterns)] match s.desugaring_kind() {
Some(DesugaringKind::FormatLiteral { .. }) => true,
_ => false,
}matches!(s.desugaring_kind(), Some(DesugaringKind::FormatLiteral { .. }))
3114 } else {
3115 false
3116 };
3117 if !is_in_fmt_lit {
3118 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}`");
3119 if span.is_visible(sm) {
3120 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}`");
3121 multispan.push_span_label(span, msg);
3122 err.span_note(multispan, descr);
3123 } else {
3124 err.span_note(tcx.def_span(item_def_id), descr);
3125 }
3126 }
3127 if let Some(note) = note {
3128 err.note(note);
3129 }
3130 if let Some(help) = help {
3131 err.help(help);
3132 }
3133 }
3134 ObligationCauseCode::WhereClause(..)
3135 | ObligationCauseCode::WhereClauseInExpr(..)
3136 | ObligationCauseCode::HostEffectInExpr(..) => {
3137 }
3140 ObligationCauseCode::OpaqueTypeBound(span, definition_def_id) => {
3141 err.span_note(span, "required by a bound in an opaque type");
3142 if let Some(definition_def_id) = definition_def_id
3143 && self.tcx.typeck(definition_def_id).coroutine_stalled_predicates.is_empty()
3147 {
3148 err.span_note(
3151 tcx.def_span(definition_def_id),
3152 "this definition site has more where clauses than the opaque type",
3153 );
3154 }
3155 }
3156 ObligationCauseCode::Coercion { source, target } => {
3157 let source =
3158 tcx.short_string(self.resolve_vars_if_possible(source), err.long_ty_path());
3159 let target =
3160 tcx.short_string(self.resolve_vars_if_possible(target), err.long_ty_path());
3161 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!(
3162 "required for the cast from `{source}` to `{target}`",
3163 )));
3164 }
3165 ObligationCauseCode::RepeatElementCopy { is_constable, elt_span } => {
3166 err.note(
3167 "the `Copy` trait is required because this value will be copied for each element of the array",
3168 );
3169 let sm = tcx.sess.source_map();
3170 if #[allow(non_exhaustive_omitted_patterns)] match is_constable {
IsConstable::Fn | IsConstable::Ctor => true,
_ => false,
}matches!(is_constable, IsConstable::Fn | IsConstable::Ctor)
3171 && let Ok(_) = sm.span_to_snippet(elt_span)
3172 {
3173 err.multipart_suggestion(
3174 "create an inline `const` block",
3175 ::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![
3176 (elt_span.shrink_to_lo(), "const { ".to_string()),
3177 (elt_span.shrink_to_hi(), " }".to_string()),
3178 ],
3179 Applicability::MachineApplicable,
3180 );
3181 } else {
3182 err.help("consider using `core::array::from_fn` to initialize the array");
3184 err.help("see https://doc.rust-lang.org/stable/std/array/fn.from_fn.html for more information");
3185 }
3186 }
3187 ObligationCauseCode::VariableType(hir_id) => {
3188 if let Some(typeck_results) = &self.typeck_results
3189 && let Some(ty) = typeck_results.node_type_opt(hir_id)
3190 && let ty::Error(_) = ty.kind()
3191 {
3192 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!(
3193 "`{predicate}` isn't satisfied, but the type of this pattern is \
3194 `{{type error}}`",
3195 ));
3196 err.downgrade_to_delayed_bug();
3197 }
3198 let mut local = true;
3199 match tcx.parent_hir_node(hir_id) {
3200 Node::LetStmt(hir::LetStmt { ty: Some(ty), .. }) => {
3201 err.span_suggestion_verbose(
3202 ty.span.shrink_to_lo(),
3203 "consider borrowing here",
3204 "&",
3205 Applicability::MachineApplicable,
3206 );
3207 }
3208 Node::LetStmt(hir::LetStmt {
3209 init: Some(hir::Expr { kind: hir::ExprKind::Index(..), span, .. }),
3210 ..
3211 }) => {
3212 err.span_suggestion_verbose(
3216 span.shrink_to_lo(),
3217 "consider borrowing here",
3218 "&",
3219 Applicability::MachineApplicable,
3220 );
3221 }
3222 Node::LetStmt(hir::LetStmt { init: Some(expr), .. }) => {
3223 suggest_remove_deref(err, &expr);
3226 }
3227 Node::Param(param) => {
3228 err.span_suggestion_verbose(
3229 param.ty_span.shrink_to_lo(),
3230 "function arguments must have a statically known size, borrowed types \
3231 always have a known size",
3232 "&",
3233 Applicability::MachineApplicable,
3234 );
3235 local = false;
3236 }
3237 _ => {}
3238 }
3239 if local {
3240 err.note("all local variables must have a statically known size");
3241 }
3242 }
3243 ObligationCauseCode::SizedArgumentType(hir_id) => {
3244 let mut ty = None;
3245 let borrowed_msg = "function arguments must have a statically known size, borrowed \
3246 types always have a known size";
3247 if let Some(hir_id) = hir_id
3248 && let hir::Node::Param(param) = self.tcx.hir_node(hir_id)
3249 && let Some(decl) = self.tcx.parent_hir_node(hir_id).fn_decl()
3250 && let Some(t) = decl.inputs.iter().find(|t| param.ty_span.contains(t.span))
3251 {
3252 ty = Some(t);
3260 } else if let Some(hir_id) = hir_id
3261 && let hir::Node::Ty(t) = self.tcx.hir_node(hir_id)
3262 {
3263 ty = Some(t);
3264 }
3265 if let Some(ty) = ty {
3266 match ty.kind {
3267 hir::TyKind::TraitObject(traits, _) => {
3268 let (span, kw) = match traits {
3269 [first, ..] if first.span.lo() == ty.span.lo() => {
3270 (ty.span.shrink_to_lo(), "dyn ")
3272 }
3273 [first, ..] => (ty.span.until(first.span), ""),
3274 [] => ::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:?}"),
3275 };
3276 let needs_parens = traits.len() != 1;
3277 if let Some(hir_id) = hir_id
3279 && #[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!(
3280 self.tcx.parent_hir_node(hir_id),
3281 hir::Node::Item(hir::Item {
3282 kind: hir::ItemKind::Fn { .. },
3283 ..
3284 })
3285 )
3286 {
3287 err.span_suggestion_verbose(
3288 span,
3289 "you can use `impl Trait` as the argument type",
3290 "impl ",
3291 Applicability::MaybeIncorrect,
3292 );
3293 }
3294 let sugg = if !needs_parens {
3295 ::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}"))]
3296 } else {
3297 ::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![
3298 (span.shrink_to_lo(), format!("&({kw}")),
3299 (ty.span.shrink_to_hi(), ")".to_string()),
3300 ]
3301 };
3302 err.multipart_suggestion(
3303 borrowed_msg,
3304 sugg,
3305 Applicability::MachineApplicable,
3306 );
3307 }
3308 hir::TyKind::Slice(_ty) => {
3309 err.span_suggestion_verbose(
3310 ty.span.shrink_to_lo(),
3311 "function arguments must have a statically known size, borrowed \
3312 slices always have a known size",
3313 "&",
3314 Applicability::MachineApplicable,
3315 );
3316 }
3317 hir::TyKind::Path(_) => {
3318 err.span_suggestion_verbose(
3319 ty.span.shrink_to_lo(),
3320 borrowed_msg,
3321 "&",
3322 Applicability::MachineApplicable,
3323 );
3324 }
3325 _ => {}
3326 }
3327 } else {
3328 err.note("all function arguments must have a statically known size");
3329 }
3330 if tcx.sess.opts.unstable_features.is_nightly_build()
3331 && !tcx.features().unsized_fn_params()
3332 {
3333 err.help("unsized fn params are gated as an unstable feature");
3334 }
3335 }
3336 ObligationCauseCode::SizedReturnType | ObligationCauseCode::SizedCallReturnType => {
3337 err.note("the return type of a function must have a statically known size");
3338 }
3339 ObligationCauseCode::SizedYieldType => {
3340 err.note("the yield type of a coroutine must have a statically known size");
3341 }
3342 ObligationCauseCode::AssignmentLhsSized => {
3343 err.note("the left-hand-side of an assignment must have a statically known size");
3344 }
3345 ObligationCauseCode::TupleInitializerSized => {
3346 err.note("tuples must have a statically known size to be initialized");
3347 }
3348 ObligationCauseCode::StructInitializerSized => {
3349 err.note("structs must have a statically known size to be initialized");
3350 }
3351 ObligationCauseCode::FieldSized { adt_kind: ref item, last, span } => {
3352 match *item {
3353 AdtKind::Struct => {
3354 if last {
3355 err.note(
3356 "the last field of a packed struct may only have a \
3357 dynamically sized type if it does not need drop to be run",
3358 );
3359 } else {
3360 err.note(
3361 "only the last field of a struct may have a dynamically sized type",
3362 );
3363 }
3364 }
3365 AdtKind::Union => {
3366 err.note("no field of a union may have a dynamically sized type");
3367 }
3368 AdtKind::Enum => {
3369 err.note("no field of an enum variant may have a dynamically sized type");
3370 }
3371 }
3372 err.help("change the field's type to have a statically known size");
3373 err.span_suggestion_verbose(
3374 span.shrink_to_lo(),
3375 "borrowed types always have a statically known size",
3376 "&",
3377 Applicability::MachineApplicable,
3378 );
3379 err.multipart_suggestion(
3380 "the `Box` type always has a statically known size and allocates its contents \
3381 in the heap",
3382 ::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![
3383 (span.shrink_to_lo(), "Box<".to_string()),
3384 (span.shrink_to_hi(), ">".to_string()),
3385 ],
3386 Applicability::MachineApplicable,
3387 );
3388 }
3389 ObligationCauseCode::SizedConstOrStatic => {
3390 err.note("statics and constants must have a statically known size");
3391 }
3392 ObligationCauseCode::InlineAsmSized => {
3393 err.note("all inline asm arguments must have a statically known size");
3394 }
3395 ObligationCauseCode::SizedClosureCapture(closure_def_id) => {
3396 err.note(
3397 "all values captured by value by a closure must have a statically known size",
3398 );
3399 let hir::ExprKind::Closure(closure) =
3400 tcx.hir_node_by_def_id(closure_def_id).expect_expr().kind
3401 else {
3402 ::rustc_middle::util::bug::bug_fmt(format_args!("expected closure in SizedClosureCapture obligation"));bug!("expected closure in SizedClosureCapture obligation");
3403 };
3404 if let hir::CaptureBy::Value { .. } = closure.capture_clause
3405 && let Some(span) = closure.fn_arg_span
3406 {
3407 err.span_label(span, "this closure captures all values by move");
3408 }
3409 }
3410 ObligationCauseCode::SizedCoroutineInterior(coroutine_def_id) => {
3411 let what = match tcx.coroutine_kind(coroutine_def_id) {
3412 None
3413 | Some(hir::CoroutineKind::Coroutine(_))
3414 | Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, _)) => {
3415 "yield"
3416 }
3417 Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)) => {
3418 "await"
3419 }
3420 Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, _)) => {
3421 "yield`/`await"
3422 }
3423 };
3424 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("all values live across `{0}` must have a statically known size",
what))
})format!(
3425 "all values live across `{what}` must have a statically known size"
3426 ));
3427 }
3428 ObligationCauseCode::SharedStatic => {
3429 err.note("shared static variables must have a type that implements `Sync`");
3430 }
3431 ObligationCauseCode::BuiltinDerived(ref data) => {
3432 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
3433 let ty = parent_trait_ref.skip_binder().self_ty();
3434 if parent_trait_ref.references_error() {
3435 err.downgrade_to_delayed_bug();
3438 return;
3439 }
3440
3441 let is_upvar_tys_infer_tuple = if !#[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
ty::Tuple(..) => true,
_ => false,
}matches!(ty.kind(), ty::Tuple(..)) {
3444 false
3445 } else if let ObligationCauseCode::BuiltinDerived(data) = &*data.parent_code {
3446 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
3447 let nested_ty = parent_trait_ref.skip_binder().self_ty();
3448 #[allow(non_exhaustive_omitted_patterns)] match nested_ty.kind() {
ty::Coroutine(..) => true,
_ => false,
}matches!(nested_ty.kind(), ty::Coroutine(..))
3449 || #[allow(non_exhaustive_omitted_patterns)] match nested_ty.kind() {
ty::Closure(..) => true,
_ => false,
}matches!(nested_ty.kind(), ty::Closure(..))
3450 } else {
3451 false
3452 };
3453
3454 let is_builtin_async_fn_trait =
3455 tcx.async_fn_trait_kind_from_def_id(data.parent_trait_pred.def_id()).is_some();
3456
3457 if !is_upvar_tys_infer_tuple && !is_builtin_async_fn_trait {
3458 let mut msg = || {
3459 let ty_str = tcx.short_string(ty, err.long_ty_path());
3460 ::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}`")
3461 };
3462 match *ty.kind() {
3463 ty::Adt(def, _) => {
3464 let msg = msg();
3465 match tcx.opt_item_ident(def.did()) {
3466 Some(ident) => {
3467 err.span_note(ident.span, msg);
3468 }
3469 None => {
3470 err.note(msg);
3471 }
3472 }
3473 }
3474 ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) => {
3475 let is_future = tcx.ty_is_opaque_future(ty);
3478 {
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:3478",
"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(3478u32),
::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!(
3479 ?obligated_types,
3480 ?is_future,
3481 "note_obligation_cause_code: check for async fn"
3482 );
3483 if is_future
3484 && obligated_types.last().is_some_and(|ty| match ty.kind() {
3485 ty::Coroutine(last_def_id, ..) => {
3486 tcx.coroutine_is_async(*last_def_id)
3487 }
3488 _ => false,
3489 })
3490 {
3491 } else {
3493 let msg = msg();
3494 err.span_note(tcx.def_span(def_id), msg);
3495 }
3496 }
3497 ty::Coroutine(def_id, _) => {
3498 let sp = tcx.def_span(def_id);
3499
3500 let kind = tcx.coroutine_kind(def_id).unwrap();
3502 err.span_note(
3503 sp,
3504 {
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!(
3505 "required because it's used within this {kind:#}",
3506 )),
3507 );
3508 }
3509 ty::CoroutineWitness(..) => {
3510 }
3513 ty::Closure(def_id, _) | ty::CoroutineClosure(def_id, _) => {
3514 err.span_note(
3515 tcx.def_span(def_id),
3516 "required because it's used within this closure",
3517 );
3518 }
3519 ty::Str => {
3520 err.note("`str` is considered to contain a `[u8]` slice for auto trait purposes");
3521 }
3522 _ => {
3523 let msg = msg();
3524 err.note(msg);
3525 }
3526 };
3527 }
3528
3529 obligated_types.push(ty);
3530
3531 let parent_predicate = parent_trait_ref;
3532 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
3533 ensure_sufficient_stack(|| {
3535 self.note_obligation_cause_code(
3536 body_id,
3537 err,
3538 parent_predicate,
3539 param_env,
3540 &data.parent_code,
3541 obligated_types,
3542 seen_requirements,
3543 )
3544 });
3545 } else {
3546 ensure_sufficient_stack(|| {
3547 self.note_obligation_cause_code(
3548 body_id,
3549 err,
3550 parent_predicate,
3551 param_env,
3552 cause_code.peel_derives(),
3553 obligated_types,
3554 seen_requirements,
3555 )
3556 });
3557 }
3558 }
3559 ObligationCauseCode::ImplDerived(ref data) => {
3560 let mut parent_trait_pred =
3561 self.resolve_vars_if_possible(data.derived.parent_trait_pred);
3562 let parent_def_id = parent_trait_pred.def_id();
3563 if tcx.is_diagnostic_item(sym::FromResidual, parent_def_id)
3564 && !tcx.features().enabled(sym::try_trait_v2)
3565 {
3566 return;
3570 }
3571 if tcx.is_diagnostic_item(sym::PinDerefMutHelper, parent_def_id) {
3572 let parent_predicate =
3573 self.resolve_vars_if_possible(data.derived.parent_trait_pred);
3574
3575 ensure_sufficient_stack(|| {
3577 self.note_obligation_cause_code(
3578 body_id,
3579 err,
3580 parent_predicate,
3581 param_env,
3582 &data.derived.parent_code,
3583 obligated_types,
3584 seen_requirements,
3585 )
3586 });
3587 return;
3588 }
3589 let self_ty_str =
3590 tcx.short_string(parent_trait_pred.skip_binder().self_ty(), err.long_ty_path());
3591 let trait_name = tcx.short_string(
3592 parent_trait_pred.print_modifiers_and_trait_path(),
3593 err.long_ty_path(),
3594 );
3595 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}`");
3596 let mut is_auto_trait = false;
3597 match tcx.hir_get_if_local(data.impl_or_alias_def_id) {
3598 Some(Node::Item(hir::Item {
3599 kind: hir::ItemKind::Trait(_, is_auto, _, ident, ..),
3600 ..
3601 })) => {
3602 is_auto_trait = #[allow(non_exhaustive_omitted_patterns)] match is_auto {
hir::IsAuto::Yes => true,
_ => false,
}matches!(is_auto, hir::IsAuto::Yes);
3605 err.span_note(ident.span, msg);
3606 }
3607 Some(Node::Item(hir::Item {
3608 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, generics, .. }),
3609 ..
3610 })) => {
3611 let mut spans = Vec::with_capacity(2);
3612 if let Some(of_trait) = of_trait
3613 && !of_trait.trait_ref.path.span.in_derive_expansion()
3614 {
3615 spans.push(of_trait.trait_ref.path.span);
3616 }
3617 spans.push(self_ty.span);
3618 let mut spans: MultiSpan = spans.into();
3619 let mut derived = false;
3620 if #[allow(non_exhaustive_omitted_patterns)] match self_ty.span.ctxt().outer_expn_data().kind
{
ExpnKind::Macro(MacroKind::Derive, _) => true,
_ => false,
}matches!(
3621 self_ty.span.ctxt().outer_expn_data().kind,
3622 ExpnKind::Macro(MacroKind::Derive, _)
3623 ) || #[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!(
3624 of_trait.map(|t| t.trait_ref.path.span.ctxt().outer_expn_data().kind),
3625 Some(ExpnKind::Macro(MacroKind::Derive, _))
3626 ) {
3627 derived = true;
3628 spans.push_span_label(
3629 data.span,
3630 if data.span.in_derive_expansion() {
3631 ::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}`")
3632 } else {
3633 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unsatisfied trait bound"))
})format!("unsatisfied trait bound")
3634 },
3635 );
3636 } else if !data.span.is_dummy() && !data.span.overlaps(self_ty.span) {
3637 if let Some(pred) = predicate.as_trait_clause()
3640 && self.tcx.is_lang_item(pred.def_id(), LangItem::Sized)
3641 && self
3642 .tcx
3643 .generics_of(data.impl_or_alias_def_id)
3644 .own_params
3645 .iter()
3646 .any(|param| self.tcx.def_span(param.def_id) == data.span)
3647 {
3648 spans.push_span_label(
3649 data.span,
3650 "unsatisfied trait bound implicitly introduced here",
3651 );
3652 } else {
3653 spans.push_span_label(
3654 data.span,
3655 "unsatisfied trait bound introduced here",
3656 );
3657 }
3658 }
3659 err.span_note(spans, msg);
3660 if derived && trait_name != "Copy" {
3661 err.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider manually implementing `{0}` to avoid undesired bounds",
trait_name))
})format!(
3662 "consider manually implementing `{trait_name}` to avoid undesired \
3663 bounds",
3664 ));
3665 }
3666 point_at_assoc_type_restriction(
3667 tcx,
3668 err,
3669 &self_ty_str,
3670 &trait_name,
3671 predicate,
3672 &generics,
3673 &data,
3674 );
3675 }
3676 _ => {
3677 err.note(msg);
3678 }
3679 };
3680
3681 let mut parent_predicate = parent_trait_pred;
3682 let mut data = &data.derived;
3683 let mut count = 0;
3684 seen_requirements.insert(parent_def_id);
3685 if is_auto_trait {
3686 while let ObligationCauseCode::BuiltinDerived(derived) = &*data.parent_code {
3689 let child_trait_ref =
3690 self.resolve_vars_if_possible(derived.parent_trait_pred);
3691 let child_def_id = child_trait_ref.def_id();
3692 if seen_requirements.insert(child_def_id) {
3693 break;
3694 }
3695 data = derived;
3696 parent_predicate = child_trait_ref.upcast(tcx);
3697 parent_trait_pred = child_trait_ref;
3698 }
3699 }
3700 while let ObligationCauseCode::ImplDerived(child) = &*data.parent_code {
3701 let child_trait_pred =
3703 self.resolve_vars_if_possible(child.derived.parent_trait_pred);
3704 let child_def_id = child_trait_pred.def_id();
3705 if seen_requirements.insert(child_def_id) {
3706 break;
3707 }
3708 count += 1;
3709 data = &child.derived;
3710 parent_predicate = child_trait_pred.upcast(tcx);
3711 parent_trait_pred = child_trait_pred;
3712 }
3713 if count > 0 {
3714 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} redundant requirement{1} hidden",
count, if count == 1 { "" } else { "s" }))
})format!(
3715 "{} redundant requirement{} hidden",
3716 count,
3717 pluralize!(count)
3718 ));
3719 let self_ty = tcx.short_string(
3720 parent_trait_pred.skip_binder().self_ty(),
3721 err.long_ty_path(),
3722 );
3723 let trait_path = tcx.short_string(
3724 parent_trait_pred.print_modifiers_and_trait_path(),
3725 err.long_ty_path(),
3726 );
3727 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}`"));
3728 }
3729 ensure_sufficient_stack(|| {
3731 self.note_obligation_cause_code(
3732 body_id,
3733 err,
3734 parent_predicate,
3735 param_env,
3736 &data.parent_code,
3737 obligated_types,
3738 seen_requirements,
3739 )
3740 });
3741 }
3742 ObligationCauseCode::ImplDerivedHost(ref data) => {
3743 let self_ty = tcx.short_string(
3744 self.resolve_vars_if_possible(data.derived.parent_host_pred.self_ty()),
3745 err.long_ty_path(),
3746 );
3747 let trait_path = tcx.short_string(
3748 data.derived
3749 .parent_host_pred
3750 .map_bound(|pred| pred.trait_ref)
3751 .print_only_trait_path(),
3752 err.long_ty_path(),
3753 );
3754 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!(
3755 "required for `{self_ty}` to implement `{} {trait_path}`",
3756 data.derived.parent_host_pred.skip_binder().constness,
3757 );
3758 match tcx.hir_get_if_local(data.impl_def_id) {
3759 Some(Node::Item(hir::Item {
3760 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
3761 ..
3762 })) => {
3763 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];
3764 spans.extend(of_trait.map(|t| t.trait_ref.path.span));
3765 let mut spans: MultiSpan = spans.into();
3766 spans.push_span_label(data.span, "unsatisfied trait bound introduced here");
3767 err.span_note(spans, msg);
3768 }
3769 _ => {
3770 err.note(msg);
3771 }
3772 }
3773 ensure_sufficient_stack(|| {
3774 self.note_obligation_cause_code(
3775 body_id,
3776 err,
3777 data.derived.parent_host_pred,
3778 param_env,
3779 &data.derived.parent_code,
3780 obligated_types,
3781 seen_requirements,
3782 )
3783 });
3784 }
3785 ObligationCauseCode::BuiltinDerivedHost(ref data) => {
3786 ensure_sufficient_stack(|| {
3787 self.note_obligation_cause_code(
3788 body_id,
3789 err,
3790 data.parent_host_pred,
3791 param_env,
3792 &data.parent_code,
3793 obligated_types,
3794 seen_requirements,
3795 )
3796 });
3797 }
3798 ObligationCauseCode::WellFormedDerived(ref data) => {
3799 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
3800 let parent_predicate = parent_trait_ref;
3801 ensure_sufficient_stack(|| {
3803 self.note_obligation_cause_code(
3804 body_id,
3805 err,
3806 parent_predicate,
3807 param_env,
3808 &data.parent_code,
3809 obligated_types,
3810 seen_requirements,
3811 )
3812 });
3813 }
3814 ObligationCauseCode::TypeAlias(ref nested, span, def_id) => {
3815 ensure_sufficient_stack(|| {
3817 self.note_obligation_cause_code(
3818 body_id,
3819 err,
3820 predicate,
3821 param_env,
3822 nested,
3823 obligated_types,
3824 seen_requirements,
3825 )
3826 });
3827 let mut multispan = MultiSpan::from(span);
3828 multispan.push_span_label(span, "required by this bound");
3829 err.span_note(
3830 multispan,
3831 ::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)),
3832 );
3833 }
3834 ObligationCauseCode::FunctionArg {
3835 arg_hir_id, call_hir_id, ref parent_code, ..
3836 } => {
3837 self.note_function_argument_obligation(
3838 body_id,
3839 err,
3840 arg_hir_id,
3841 parent_code,
3842 param_env,
3843 predicate,
3844 call_hir_id,
3845 );
3846 ensure_sufficient_stack(|| {
3847 self.note_obligation_cause_code(
3848 body_id,
3849 err,
3850 predicate,
3851 param_env,
3852 parent_code,
3853 obligated_types,
3854 seen_requirements,
3855 )
3856 });
3857 }
3858 ObligationCauseCode::CompareImplItem { trait_item_def_id, .. }
3861 if tcx.is_impl_trait_in_trait(trait_item_def_id) => {}
3862 ObligationCauseCode::CompareImplItem { trait_item_def_id, kind, .. } => {
3863 let item_name = tcx.item_name(trait_item_def_id);
3864 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!(
3865 "the requirement `{predicate}` appears on the `impl`'s {kind} \
3866 `{item_name}` but not on the corresponding trait's {kind}",
3867 );
3868 let sp = tcx
3869 .opt_item_ident(trait_item_def_id)
3870 .map(|i| i.span)
3871 .unwrap_or_else(|| tcx.def_span(trait_item_def_id));
3872 let mut assoc_span: MultiSpan = sp.into();
3873 assoc_span.push_span_label(
3874 sp,
3875 ::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}`"),
3876 );
3877 if let Some(ident) = tcx
3878 .opt_associated_item(trait_item_def_id)
3879 .and_then(|i| tcx.opt_item_ident(i.container_id(tcx)))
3880 {
3881 assoc_span.push_span_label(ident.span, "in this trait");
3882 }
3883 err.span_note(assoc_span, msg);
3884 }
3885 ObligationCauseCode::TrivialBound => {
3886 tcx.disabled_nightly_features(err, [(String::new(), sym::trivial_bounds)]);
3887 }
3888 ObligationCauseCode::OpaqueReturnType(expr_info) => {
3889 let (expr_ty, expr) = if let Some((expr_ty, hir_id)) = expr_info {
3890 let expr_ty = tcx.short_string(expr_ty, err.long_ty_path());
3891 let expr = tcx.hir_expect_expr(hir_id);
3892 (expr_ty, expr)
3893 } else if let Some(body_id) = tcx.hir_node_by_def_id(body_id).body_id()
3894 && let body = tcx.hir_body(body_id)
3895 && let hir::ExprKind::Block(block, _) = body.value.kind
3896 && let Some(expr) = block.expr
3897 && let Some(expr_ty) = self
3898 .typeck_results
3899 .as_ref()
3900 .and_then(|typeck| typeck.node_type_opt(expr.hir_id))
3901 && let Some(pred) = predicate.as_clause()
3902 && let ty::ClauseKind::Trait(pred) = pred.kind().skip_binder()
3903 && self.can_eq(param_env, pred.self_ty(), expr_ty)
3904 {
3905 let expr_ty = tcx.short_string(expr_ty, err.long_ty_path());
3906 (expr_ty, expr)
3907 } else {
3908 return;
3909 };
3910 err.span_label(
3911 expr.span,
3912 {
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!(
3913 "return type was inferred to be `{expr_ty}` here",
3914 )),
3915 );
3916 suggest_remove_deref(err, &expr);
3917 }
3918 ObligationCauseCode::UnsizedNonPlaceExpr(span) => {
3919 err.span_note(
3920 span,
3921 "unsized values must be place expressions and cannot be put in temporaries",
3922 );
3923 }
3924 ObligationCauseCode::CompareEii { .. } => {
3925 {
::core::panicking::panic_fmt(format_args!("trait bounds on EII not yet supported "));
}panic!("trait bounds on EII not yet supported ")
3926 }
3927 }
3928 }
3929
3930 #[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(3930u32),
::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:3965",
"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(3965u32),
::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:3972",
"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(3972u32),
::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(
3931 level = "debug", skip(self, err), fields(trait_pred.self_ty = ?trait_pred.self_ty())
3932 )]
3933 pub(super) fn suggest_await_before_try(
3934 &self,
3935 err: &mut Diag<'_>,
3936 obligation: &PredicateObligation<'tcx>,
3937 trait_pred: ty::PolyTraitPredicate<'tcx>,
3938 span: Span,
3939 ) {
3940 let future_trait = self.tcx.require_lang_item(LangItem::Future, span);
3941
3942 let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
3943 let impls_future = self.type_implements_trait(
3944 future_trait,
3945 [self.tcx.instantiate_bound_regions_with_erased(self_ty)],
3946 obligation.param_env,
3947 );
3948 if !impls_future.must_apply_modulo_regions() {
3949 return;
3950 }
3951
3952 let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
3953 let projection_ty = trait_pred.map_bound(|trait_pred| {
3955 Ty::new_projection(
3956 self.tcx,
3957 item_def_id,
3958 [trait_pred.self_ty()],
3960 )
3961 });
3962 let InferOk { value: projection_ty, .. } =
3963 self.at(&obligation.cause, obligation.param_env).normalize(projection_ty);
3964
3965 debug!(
3966 normalized_projection_type = ?self.resolve_vars_if_possible(projection_ty)
3967 );
3968 let try_obligation = self.mk_trait_obligation_with_new_self_ty(
3969 obligation.param_env,
3970 trait_pred.map_bound(|trait_pred| (trait_pred, projection_ty.skip_binder())),
3971 );
3972 debug!(try_trait_obligation = ?try_obligation);
3973 if self.predicate_may_hold(&try_obligation)
3974 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
3975 && snippet.ends_with('?')
3976 {
3977 match self.tcx.coroutine_kind(obligation.cause.body_id) {
3978 Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)) => {
3979 err.span_suggestion_verbose(
3980 span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(),
3981 "consider `await`ing on the `Future`",
3982 ".await",
3983 Applicability::MaybeIncorrect,
3984 );
3985 }
3986 _ => {
3987 let mut span: MultiSpan = span.with_lo(span.hi() - BytePos(1)).into();
3988 span.push_span_label(
3989 self.tcx.def_span(obligation.cause.body_id),
3990 "this is not `async`",
3991 );
3992 err.span_note(
3993 span,
3994 "this implements `Future` and its output type supports \
3995 `?`, but the future cannot be awaited in a synchronous function",
3996 );
3997 }
3998 }
3999 }
4000 }
4001
4002 pub(super) fn suggest_floating_point_literal(
4003 &self,
4004 obligation: &PredicateObligation<'tcx>,
4005 err: &mut Diag<'_>,
4006 trait_pred: ty::PolyTraitPredicate<'tcx>,
4007 ) {
4008 let rhs_span = match obligation.cause.code() {
4009 ObligationCauseCode::BinOp { rhs_span, rhs_is_lit, .. } if *rhs_is_lit => rhs_span,
4010 _ => return,
4011 };
4012 if let ty::Float(_) = trait_pred.skip_binder().self_ty().kind()
4013 && let ty::Infer(InferTy::IntVar(_)) =
4014 trait_pred.skip_binder().trait_ref.args.type_at(1).kind()
4015 {
4016 err.span_suggestion_verbose(
4017 rhs_span.shrink_to_hi(),
4018 "consider using a floating-point literal by writing it with `.0`",
4019 ".0",
4020 Applicability::MaybeIncorrect,
4021 );
4022 }
4023 }
4024
4025 pub fn can_suggest_derive(
4026 &self,
4027 obligation: &PredicateObligation<'tcx>,
4028 trait_pred: ty::PolyTraitPredicate<'tcx>,
4029 ) -> bool {
4030 if trait_pred.polarity() == ty::PredicatePolarity::Negative {
4031 return false;
4032 }
4033 let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else {
4034 return false;
4035 };
4036 let (adt, args) = match trait_pred.skip_binder().self_ty().kind() {
4037 ty::Adt(adt, args) if adt.did().is_local() => (adt, args),
4038 _ => return false,
4039 };
4040 let is_derivable_trait = match diagnostic_name {
4041 sym::Default => !adt.is_enum(),
4042 sym::PartialEq | sym::PartialOrd => {
4043 let rhs_ty = trait_pred.skip_binder().trait_ref.args.type_at(1);
4044 trait_pred.skip_binder().self_ty() == rhs_ty
4045 }
4046 sym::Eq | sym::Ord | sym::Clone | sym::Copy | sym::Hash | sym::Debug => true,
4047 _ => false,
4048 };
4049 is_derivable_trait &&
4050 adt.all_fields().all(|field| {
4052 let field_ty = ty::GenericArg::from(field.ty(self.tcx, args));
4053 let trait_args = match diagnostic_name {
4054 sym::PartialEq | sym::PartialOrd => {
4055 Some(field_ty)
4056 }
4057 _ => None,
4058 };
4059 let trait_pred = trait_pred.map_bound_ref(|tr| ty::TraitPredicate {
4060 trait_ref: ty::TraitRef::new(self.tcx,
4061 trait_pred.def_id(),
4062 [field_ty].into_iter().chain(trait_args),
4063 ),
4064 ..*tr
4065 });
4066 let field_obl = Obligation::new(
4067 self.tcx,
4068 obligation.cause.clone(),
4069 obligation.param_env,
4070 trait_pred,
4071 );
4072 self.predicate_must_hold_modulo_regions(&field_obl)
4073 })
4074 }
4075
4076 pub fn suggest_derive(
4077 &self,
4078 obligation: &PredicateObligation<'tcx>,
4079 err: &mut Diag<'_>,
4080 trait_pred: ty::PolyTraitPredicate<'tcx>,
4081 ) {
4082 let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else {
4083 return;
4084 };
4085 let adt = match trait_pred.skip_binder().self_ty().kind() {
4086 ty::Adt(adt, _) if adt.did().is_local() => adt,
4087 _ => return,
4088 };
4089 if self.can_suggest_derive(obligation, trait_pred) {
4090 err.span_suggestion_verbose(
4091 self.tcx.def_span(adt.did()).shrink_to_lo(),
4092 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider annotating `{0}` with `#[derive({1})]`",
trait_pred.skip_binder().self_ty(), diagnostic_name))
})format!(
4093 "consider annotating `{}` with `#[derive({})]`",
4094 trait_pred.skip_binder().self_ty(),
4095 diagnostic_name,
4096 ),
4097 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("#[derive({0})]\n",
diagnostic_name))
})format!("#[derive({diagnostic_name})]\n"),
4099 Applicability::MaybeIncorrect,
4100 );
4101 }
4102 }
4103
4104 pub(super) fn suggest_dereferencing_index(
4105 &self,
4106 obligation: &PredicateObligation<'tcx>,
4107 err: &mut Diag<'_>,
4108 trait_pred: ty::PolyTraitPredicate<'tcx>,
4109 ) {
4110 if let ObligationCauseCode::ImplDerived(_) = obligation.cause.code()
4111 && self
4112 .tcx
4113 .is_diagnostic_item(sym::SliceIndex, trait_pred.skip_binder().trait_ref.def_id)
4114 && let ty::Slice(_) = trait_pred.skip_binder().trait_ref.args.type_at(1).kind()
4115 && let ty::Ref(_, inner_ty, _) = trait_pred.skip_binder().self_ty().kind()
4116 && let ty::Uint(ty::UintTy::Usize) = inner_ty.kind()
4117 {
4118 err.span_suggestion_verbose(
4119 obligation.cause.span.shrink_to_lo(),
4120 "dereference this index",
4121 '*',
4122 Applicability::MachineApplicable,
4123 );
4124 }
4125 }
4126
4127 fn note_function_argument_obligation<G: EmissionGuarantee>(
4128 &self,
4129 body_id: LocalDefId,
4130 err: &mut Diag<'_, G>,
4131 arg_hir_id: HirId,
4132 parent_code: &ObligationCauseCode<'tcx>,
4133 param_env: ty::ParamEnv<'tcx>,
4134 failed_pred: ty::Predicate<'tcx>,
4135 call_hir_id: HirId,
4136 ) {
4137 let tcx = self.tcx;
4138 if let Node::Expr(expr) = tcx.hir_node(arg_hir_id)
4139 && let Some(typeck_results) = &self.typeck_results
4140 {
4141 if let hir::Expr { kind: hir::ExprKind::MethodCall(_, rcvr, _, _), .. } = expr
4142 && let Some(ty) = typeck_results.node_type_opt(rcvr.hir_id)
4143 && let Some(failed_pred) = failed_pred.as_trait_clause()
4144 && let pred = failed_pred.map_bound(|pred| pred.with_replaced_self_ty(tcx, ty))
4145 && self.predicate_must_hold_modulo_regions(&Obligation::misc(
4146 tcx, expr.span, body_id, param_env, pred,
4147 ))
4148 && expr.span.hi() != rcvr.span.hi()
4149 {
4150 let should_sugg = match tcx.hir_node(call_hir_id) {
4151 Node::Expr(hir::Expr {
4152 kind: hir::ExprKind::MethodCall(_, call_receiver, _, _),
4153 ..
4154 }) if let Some((DefKind::AssocFn, did)) =
4155 typeck_results.type_dependent_def(call_hir_id)
4156 && call_receiver.hir_id == arg_hir_id =>
4157 {
4158 if tcx.inherent_impl_of_assoc(did).is_some() {
4162 Some(ty) == typeck_results.node_type_opt(arg_hir_id)
4164 } else {
4165 let trait_id = tcx
4167 .trait_of_assoc(did)
4168 .unwrap_or_else(|| tcx.impl_trait_id(tcx.parent(did)));
4169 let args = typeck_results.node_args(call_hir_id);
4170 let tr = ty::TraitRef::from_assoc(tcx, trait_id, args)
4171 .with_replaced_self_ty(tcx, ty);
4172 self.type_implements_trait(tr.def_id, tr.args, param_env)
4173 .must_apply_modulo_regions()
4174 }
4175 }
4176 _ => true,
4177 };
4178
4179 if should_sugg {
4180 err.span_suggestion_verbose(
4181 expr.span.with_lo(rcvr.span.hi()),
4182 ::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!(
4183 "consider removing this method call, as the receiver has type `{ty}` and \
4184 `{pred}` trivially holds",
4185 ),
4186 "",
4187 Applicability::MaybeIncorrect,
4188 );
4189 }
4190 }
4191 if let hir::Expr { kind: hir::ExprKind::Block(block, _), .. } = expr {
4192 let inner_expr = expr.peel_blocks();
4193 let ty = typeck_results
4194 .expr_ty_adjusted_opt(inner_expr)
4195 .unwrap_or(Ty::new_misc_error(tcx));
4196 let span = inner_expr.span;
4197 if Some(span) != err.span.primary_span()
4198 && !span.in_external_macro(tcx.sess.source_map())
4199 {
4200 err.span_label(
4201 span,
4202 if ty.references_error() {
4203 String::new()
4204 } else {
4205 let ty = { let _guard = ForceTrimmedGuard::new(); self.ty_to_string(ty) }with_forced_trimmed_paths!(self.ty_to_string(ty));
4206 ::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}`")
4207 },
4208 );
4209 if let ty::PredicateKind::Clause(clause) = failed_pred.kind().skip_binder()
4210 && let ty::ClauseKind::Trait(pred) = clause
4211 && tcx.fn_trait_kind_from_def_id(pred.def_id()).is_some()
4212 {
4213 if let [stmt, ..] = block.stmts
4214 && let hir::StmtKind::Semi(value) = stmt.kind
4215 && let hir::ExprKind::Closure(hir::Closure {
4216 body, fn_decl_span, ..
4217 }) = value.kind
4218 && let body = tcx.hir_body(*body)
4219 && !#[allow(non_exhaustive_omitted_patterns)] match body.value.kind {
hir::ExprKind::Block(..) => true,
_ => false,
}matches!(body.value.kind, hir::ExprKind::Block(..))
4220 {
4221 err.multipart_suggestion(
4224 "you might have meant to open the closure body instead of placing \
4225 a closure within a block",
4226 ::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![
4227 (expr.span.with_hi(value.span.lo()), String::new()),
4228 (fn_decl_span.shrink_to_hi(), " {".to_string()),
4229 ],
4230 Applicability::MaybeIncorrect,
4231 );
4232 } else {
4233 err.span_suggestion_verbose(
4235 expr.span.shrink_to_lo(),
4236 "you might have meant to create the closure instead of a block",
4237 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("|{0}| ",
(0..pred.trait_ref.args.len() -
1).map(|_| "_").collect::<Vec<_>>().join(", ")))
})format!(
4238 "|{}| ",
4239 (0..pred.trait_ref.args.len() - 1)
4240 .map(|_| "_")
4241 .collect::<Vec<_>>()
4242 .join(", ")
4243 ),
4244 Applicability::MaybeIncorrect,
4245 );
4246 }
4247 }
4248 }
4249 }
4250
4251 let mut type_diffs = ::alloc::vec::Vec::new()vec![];
4256 if let ObligationCauseCode::WhereClauseInExpr(def_id, _, _, idx) = *parent_code
4257 && let Some(node_args) = typeck_results.node_args_opt(call_hir_id)
4258 && let where_clauses =
4259 self.tcx.predicates_of(def_id).instantiate(self.tcx, node_args)
4260 && let Some(where_pred) = where_clauses.predicates.get(idx)
4261 {
4262 if let Some(where_pred) = where_pred.as_trait_clause()
4263 && let Some(failed_pred) = failed_pred.as_trait_clause()
4264 && where_pred.def_id() == failed_pred.def_id()
4265 {
4266 self.enter_forall(where_pred, |where_pred| {
4267 let failed_pred = self.instantiate_binder_with_fresh_vars(
4268 expr.span,
4269 BoundRegionConversionTime::FnCall,
4270 failed_pred,
4271 );
4272
4273 let zipped =
4274 iter::zip(where_pred.trait_ref.args, failed_pred.trait_ref.args);
4275 for (expected, actual) in zipped {
4276 self.probe(|_| {
4277 match self
4278 .at(&ObligationCause::misc(expr.span, body_id), param_env)
4279 .eq(DefineOpaqueTypes::Yes, expected, actual)
4282 {
4283 Ok(_) => (), Err(err) => type_diffs.push(err),
4285 }
4286 })
4287 }
4288 })
4289 } else if let Some(where_pred) = where_pred.as_projection_clause()
4290 && let Some(failed_pred) = failed_pred.as_projection_clause()
4291 && let Some(found) = failed_pred.skip_binder().term.as_type()
4292 {
4293 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 {
4294 expected: where_pred
4295 .skip_binder()
4296 .projection_term
4297 .expect_ty(self.tcx)
4298 .to_ty(self.tcx),
4299 found,
4300 })];
4301 }
4302 }
4303 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
4304 && let hir::Path { res: Res::Local(hir_id), .. } = path
4305 && let hir::Node::Pat(binding) = self.tcx.hir_node(*hir_id)
4306 && let hir::Node::LetStmt(local) = self.tcx.parent_hir_node(binding.hir_id)
4307 && let Some(binding_expr) = local.init
4308 {
4309 self.point_at_chain(binding_expr, typeck_results, type_diffs, param_env, err);
4313 } else {
4314 self.point_at_chain(expr, typeck_results, type_diffs, param_env, err);
4315 }
4316 }
4317 let call_node = tcx.hir_node(call_hir_id);
4318 if let Node::Expr(hir::Expr { kind: hir::ExprKind::MethodCall(path, rcvr, ..), .. }) =
4319 call_node
4320 {
4321 if Some(rcvr.span) == err.span.primary_span() {
4322 err.replace_span_with(path.ident.span, true);
4323 }
4324 }
4325
4326 if let Node::Expr(expr) = call_node {
4327 if let hir::ExprKind::Call(hir::Expr { span, .. }, _)
4328 | hir::ExprKind::MethodCall(
4329 hir::PathSegment { ident: Ident { span, .. }, .. },
4330 ..,
4331 ) = expr.kind
4332 {
4333 if Some(*span) != err.span.primary_span() {
4334 let msg = if span.is_desugaring(DesugaringKind::FormatLiteral { source: true })
4335 {
4336 "required by this formatting parameter"
4337 } else if span.is_desugaring(DesugaringKind::FormatLiteral { source: false }) {
4338 "required by a formatting parameter in this expression"
4339 } else {
4340 "required by a bound introduced by this call"
4341 };
4342 err.span_label(*span, msg);
4343 }
4344 }
4345
4346 if let hir::ExprKind::MethodCall(_, expr, ..) = expr.kind {
4347 self.suggest_option_method_if_applicable(failed_pred, param_env, err, expr);
4348 }
4349 }
4350 }
4351
4352 fn suggest_option_method_if_applicable<G: EmissionGuarantee>(
4353 &self,
4354 failed_pred: ty::Predicate<'tcx>,
4355 param_env: ty::ParamEnv<'tcx>,
4356 err: &mut Diag<'_, G>,
4357 expr: &hir::Expr<'_>,
4358 ) {
4359 let tcx = self.tcx;
4360 let infcx = self.infcx;
4361 let Some(typeck_results) = self.typeck_results.as_ref() else { return };
4362
4363 let Some(option_ty_adt) = typeck_results.expr_ty_adjusted(expr).ty_adt_def() else {
4365 return;
4366 };
4367 if !tcx.is_diagnostic_item(sym::Option, option_ty_adt.did()) {
4368 return;
4369 }
4370
4371 if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(ty::TraitPredicate { trait_ref, .. }))
4374 = failed_pred.kind().skip_binder()
4375 && tcx.is_fn_trait(trait_ref.def_id)
4376 && let [self_ty, found_ty] = trait_ref.args.as_slice()
4377 && let Some(fn_ty) = self_ty.as_type().filter(|ty| ty.is_fn())
4378 && let fn_sig @ ty::FnSig {
4379 abi: ExternAbi::Rust,
4380 c_variadic: false,
4381 safety: hir::Safety::Safe,
4382 ..
4383 } = fn_ty.fn_sig(tcx).skip_binder()
4384
4385 && let Some(&ty::Ref(_, target_ty, needs_mut)) = fn_sig.inputs().first().map(|t| t.kind())
4387 && !target_ty.has_escaping_bound_vars()
4388
4389 && let Some(ty::Tuple(tys)) = found_ty.as_type().map(Ty::kind)
4391 && let &[found_ty] = tys.as_slice()
4392 && !found_ty.has_escaping_bound_vars()
4393
4394 && let Some(deref_target_did) = tcx.lang_items().deref_target()
4396 && let projection = Ty::new_projection_from_args(tcx,deref_target_did, tcx.mk_args(&[ty::GenericArg::from(found_ty)]))
4397 && let InferOk { value: deref_target, obligations } = infcx.at(&ObligationCause::dummy(), param_env).normalize(projection)
4398 && obligations.iter().all(|obligation| infcx.predicate_must_hold_modulo_regions(obligation))
4399 && infcx.can_eq(param_env, deref_target, target_ty)
4400 {
4401 let help = if let hir::Mutability::Mut = needs_mut
4402 && let Some(deref_mut_did) = tcx.lang_items().deref_mut_trait()
4403 && infcx
4404 .type_implements_trait(deref_mut_did, iter::once(found_ty), param_env)
4405 .must_apply_modulo_regions()
4406 {
4407 Some(("call `Option::as_deref_mut()` first", ".as_deref_mut()"))
4408 } else if let hir::Mutability::Not = needs_mut {
4409 Some(("call `Option::as_deref()` first", ".as_deref()"))
4410 } else {
4411 None
4412 };
4413
4414 if let Some((msg, sugg)) = help {
4415 err.span_suggestion_with_style(
4416 expr.span.shrink_to_hi(),
4417 msg,
4418 sugg,
4419 Applicability::MaybeIncorrect,
4420 SuggestionStyle::ShowAlways,
4421 );
4422 }
4423 }
4424 }
4425
4426 fn look_for_iterator_item_mistakes<G: EmissionGuarantee>(
4427 &self,
4428 assocs_in_this_method: &[Option<(Span, (DefId, Ty<'tcx>))>],
4429 typeck_results: &TypeckResults<'tcx>,
4430 type_diffs: &[TypeError<'tcx>],
4431 param_env: ty::ParamEnv<'tcx>,
4432 path_segment: &hir::PathSegment<'_>,
4433 args: &[hir::Expr<'_>],
4434 prev_ty: Ty<'_>,
4435 err: &mut Diag<'_, G>,
4436 ) {
4437 let tcx = self.tcx;
4438 for entry in assocs_in_this_method {
4441 let Some((_span, (def_id, ty))) = entry else {
4442 continue;
4443 };
4444 for diff in type_diffs {
4445 let TypeError::Sorts(expected_found) = diff else {
4446 continue;
4447 };
4448 if tcx.is_diagnostic_item(sym::IntoIteratorItem, *def_id)
4449 && path_segment.ident.name == sym::iter
4450 && self.can_eq(
4451 param_env,
4452 Ty::new_ref(
4453 tcx,
4454 tcx.lifetimes.re_erased,
4455 expected_found.found,
4456 ty::Mutability::Not,
4457 ),
4458 *ty,
4459 )
4460 && let [] = args
4461 {
4462 err.span_suggestion_verbose(
4464 path_segment.ident.span,
4465 ::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`"),
4466 "into_iter".to_string(),
4467 Applicability::MachineApplicable,
4468 );
4469 }
4470 if tcx.is_diagnostic_item(sym::IntoIteratorItem, *def_id)
4471 && path_segment.ident.name == sym::into_iter
4472 && self.can_eq(
4473 param_env,
4474 expected_found.found,
4475 Ty::new_ref(tcx, tcx.lifetimes.re_erased, *ty, ty::Mutability::Not),
4476 )
4477 && let [] = args
4478 {
4479 err.span_suggestion_verbose(
4481 path_segment.ident.span,
4482 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider not consuming the `{0}` to construct the `Iterator`",
prev_ty))
})format!(
4483 "consider not consuming the `{prev_ty}` to construct the `Iterator`"
4484 ),
4485 "iter".to_string(),
4486 Applicability::MachineApplicable,
4487 );
4488 }
4489 if tcx.is_diagnostic_item(sym::IteratorItem, *def_id)
4490 && path_segment.ident.name == sym::map
4491 && self.can_eq(param_env, expected_found.found, *ty)
4492 && let [arg] = args
4493 && let hir::ExprKind::Closure(closure) = arg.kind
4494 {
4495 let body = tcx.hir_body(closure.body);
4496 if let hir::ExprKind::Block(block, None) = body.value.kind
4497 && let None = block.expr
4498 && let [.., stmt] = block.stmts
4499 && let hir::StmtKind::Semi(expr) = stmt.kind
4500 && expected_found.found.is_unit()
4504 && expr.span.hi() != stmt.span.hi()
4509 {
4510 err.span_suggestion_verbose(
4511 expr.span.shrink_to_hi().with_hi(stmt.span.hi()),
4512 "consider removing this semicolon",
4513 String::new(),
4514 Applicability::MachineApplicable,
4515 );
4516 }
4517 let expr = if let hir::ExprKind::Block(block, None) = body.value.kind
4518 && let Some(expr) = block.expr
4519 {
4520 expr
4521 } else {
4522 body.value
4523 };
4524 if let hir::ExprKind::MethodCall(path_segment, rcvr, [], span) = expr.kind
4525 && path_segment.ident.name == sym::clone
4526 && let Some(expr_ty) = typeck_results.expr_ty_opt(expr)
4527 && let Some(rcvr_ty) = typeck_results.expr_ty_opt(rcvr)
4528 && self.can_eq(param_env, expr_ty, rcvr_ty)
4529 && let ty::Ref(_, ty, _) = expr_ty.kind()
4530 {
4531 err.span_label(
4532 span,
4533 ::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!(
4534 "this method call is cloning the reference `{expr_ty}`, not \
4535 `{ty}` which doesn't implement `Clone`",
4536 ),
4537 );
4538 let ty::Param(..) = ty.kind() else {
4539 continue;
4540 };
4541 let node =
4542 tcx.hir_node_by_def_id(tcx.hir_get_parent_item(expr.hir_id).def_id);
4543
4544 let pred = ty::Binder::dummy(ty::TraitPredicate {
4545 trait_ref: ty::TraitRef::new(
4546 tcx,
4547 tcx.require_lang_item(LangItem::Clone, span),
4548 [*ty],
4549 ),
4550 polarity: ty::PredicatePolarity::Positive,
4551 });
4552 let Some(generics) = node.generics() else {
4553 continue;
4554 };
4555 let Some(body_id) = node.body_id() else {
4556 continue;
4557 };
4558 suggest_restriction(
4559 tcx,
4560 tcx.hir_body_owner_def_id(body_id),
4561 generics,
4562 &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("type parameter `{0}`", ty))
})format!("type parameter `{ty}`"),
4563 err,
4564 node.fn_sig(),
4565 None,
4566 pred,
4567 None,
4568 );
4569 }
4570 }
4571 }
4572 }
4573 }
4574
4575 fn point_at_chain<G: EmissionGuarantee>(
4576 &self,
4577 expr: &hir::Expr<'_>,
4578 typeck_results: &TypeckResults<'tcx>,
4579 type_diffs: Vec<TypeError<'tcx>>,
4580 param_env: ty::ParamEnv<'tcx>,
4581 err: &mut Diag<'_, G>,
4582 ) {
4583 let mut primary_spans = ::alloc::vec::Vec::new()vec![];
4584 let mut span_labels = ::alloc::vec::Vec::new()vec![];
4585
4586 let tcx = self.tcx;
4587
4588 let mut print_root_expr = true;
4589 let mut assocs = ::alloc::vec::Vec::new()vec![];
4590 let mut expr = expr;
4591 let mut prev_ty = self.resolve_vars_if_possible(
4592 typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(tcx)),
4593 );
4594 while let hir::ExprKind::MethodCall(path_segment, rcvr_expr, args, span) = expr.kind {
4595 expr = rcvr_expr;
4599 let assocs_in_this_method =
4600 self.probe_assoc_types_at_expr(&type_diffs, span, prev_ty, expr.hir_id, param_env);
4601 prev_ty = self.resolve_vars_if_possible(
4602 typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(tcx)),
4603 );
4604 self.look_for_iterator_item_mistakes(
4605 &assocs_in_this_method,
4606 typeck_results,
4607 &type_diffs,
4608 param_env,
4609 path_segment,
4610 args,
4611 prev_ty,
4612 err,
4613 );
4614 assocs.push(assocs_in_this_method);
4615
4616 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
4617 && let hir::Path { res: Res::Local(hir_id), .. } = path
4618 && let hir::Node::Pat(binding) = self.tcx.hir_node(*hir_id)
4619 {
4620 let parent = self.tcx.parent_hir_node(binding.hir_id);
4621 if let hir::Node::LetStmt(local) = parent
4623 && let Some(binding_expr) = local.init
4624 {
4625 expr = binding_expr;
4627 }
4628 if let hir::Node::Param(param) = parent {
4629 let prev_ty = self.resolve_vars_if_possible(
4631 typeck_results
4632 .node_type_opt(param.hir_id)
4633 .unwrap_or(Ty::new_misc_error(tcx)),
4634 );
4635 let assocs_in_this_method = self.probe_assoc_types_at_expr(
4636 &type_diffs,
4637 param.ty_span,
4638 prev_ty,
4639 param.hir_id,
4640 param_env,
4641 );
4642 if assocs_in_this_method.iter().any(|a| a.is_some()) {
4643 assocs.push(assocs_in_this_method);
4644 print_root_expr = false;
4645 }
4646 break;
4647 }
4648 }
4649 }
4650 if let Some(ty) = typeck_results.expr_ty_opt(expr)
4653 && print_root_expr
4654 {
4655 let ty = { let _guard = ForceTrimmedGuard::new(); self.ty_to_string(ty) }with_forced_trimmed_paths!(self.ty_to_string(ty));
4656 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}`")));
4660 };
4661 let mut assocs = assocs.into_iter().peekable();
4664 while let Some(assocs_in_method) = assocs.next() {
4665 let Some(prev_assoc_in_method) = assocs.peek() else {
4666 for entry in assocs_in_method {
4667 let Some((span, (assoc, ty))) = entry else {
4668 continue;
4669 };
4670 if primary_spans.is_empty()
4671 || type_diffs.iter().any(|diff| {
4672 let TypeError::Sorts(expected_found) = diff else {
4673 return false;
4674 };
4675 self.can_eq(param_env, expected_found.found, ty)
4676 })
4677 {
4678 primary_spans.push(span);
4684 }
4685 span_labels.push((
4686 span,
4687 {
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!(
4688 "`{}` is `{ty}` here",
4689 self.tcx.def_path_str(assoc),
4690 )),
4691 ));
4692 }
4693 break;
4694 };
4695 for (entry, prev_entry) in
4696 assocs_in_method.into_iter().zip(prev_assoc_in_method.into_iter())
4697 {
4698 match (entry, prev_entry) {
4699 (Some((span, (assoc, ty))), Some((_, (_, prev_ty)))) => {
4700 let ty_str = { let _guard = ForceTrimmedGuard::new(); self.ty_to_string(ty) }with_forced_trimmed_paths!(self.ty_to_string(ty));
4701
4702 let assoc = { let _guard = ForceTrimmedGuard::new(); self.tcx.def_path_str(assoc) }with_forced_trimmed_paths!(self.tcx.def_path_str(assoc));
4703 if !self.can_eq(param_env, ty, *prev_ty) {
4704 if type_diffs.iter().any(|diff| {
4705 let TypeError::Sorts(expected_found) = diff else {
4706 return false;
4707 };
4708 self.can_eq(param_env, expected_found.found, ty)
4709 }) {
4710 primary_spans.push(span);
4711 }
4712 span_labels
4713 .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")));
4714 } else {
4715 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")));
4716 }
4717 }
4718 (Some((span, (assoc, ty))), None) => {
4719 span_labels.push((
4720 span,
4721 {
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!(
4722 "`{}` is `{}` here",
4723 self.tcx.def_path_str(assoc),
4724 self.ty_to_string(ty),
4725 )),
4726 ));
4727 }
4728 (None, Some(_)) | (None, None) => {}
4729 }
4730 }
4731 }
4732 if !primary_spans.is_empty() {
4733 let mut multi_span: MultiSpan = primary_spans.into();
4734 for (span, label) in span_labels {
4735 multi_span.push_span_label(span, label);
4736 }
4737 err.span_note(
4738 multi_span,
4739 "the method call chain might not have had the expected associated types",
4740 );
4741 }
4742 }
4743
4744 fn probe_assoc_types_at_expr(
4745 &self,
4746 type_diffs: &[TypeError<'tcx>],
4747 span: Span,
4748 prev_ty: Ty<'tcx>,
4749 body_id: HirId,
4750 param_env: ty::ParamEnv<'tcx>,
4751 ) -> Vec<Option<(Span, (DefId, Ty<'tcx>))>> {
4752 let ocx = ObligationCtxt::new(self.infcx);
4753 let mut assocs_in_this_method = Vec::with_capacity(type_diffs.len());
4754 for diff in type_diffs {
4755 let TypeError::Sorts(expected_found) = diff else {
4756 continue;
4757 };
4758 let ty::Alias(ty::Projection, proj) = expected_found.expected.kind() else {
4759 continue;
4760 };
4761
4762 let args = GenericArgs::for_item(self.tcx, proj.def_id, |param, _| {
4766 if param.index == 0 {
4767 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 { .. });
4768 return prev_ty.into();
4769 }
4770 self.var_for_def(span, param)
4771 });
4772 let ty = self.infcx.next_ty_var(span);
4776 let projection = ty::Binder::dummy(ty::PredicateKind::Clause(
4778 ty::ClauseKind::Projection(ty::ProjectionPredicate {
4779 projection_term: ty::AliasTerm::new_from_args(self.tcx, proj.def_id, args),
4780 term: ty.into(),
4781 }),
4782 ));
4783 let body_def_id = self.tcx.hir_enclosing_body_owner(body_id);
4784 ocx.register_obligation(Obligation::misc(
4786 self.tcx,
4787 span,
4788 body_def_id,
4789 param_env,
4790 projection,
4791 ));
4792 if ocx.try_evaluate_obligations().is_empty()
4793 && let ty = self.resolve_vars_if_possible(ty)
4794 && !ty.is_ty_var()
4795 {
4796 assocs_in_this_method.push(Some((span, (proj.def_id, ty))));
4797 } else {
4798 assocs_in_this_method.push(None);
4803 }
4804 }
4805 assocs_in_this_method
4806 }
4807
4808 pub(super) fn suggest_convert_to_slice(
4812 &self,
4813 err: &mut Diag<'_>,
4814 obligation: &PredicateObligation<'tcx>,
4815 trait_pred: ty::PolyTraitPredicate<'tcx>,
4816 candidate_impls: &[ImplCandidate<'tcx>],
4817 span: Span,
4818 ) {
4819 let (ObligationCauseCode::BinOp { .. } | ObligationCauseCode::FunctionArg { .. }) =
4822 obligation.cause.code()
4823 else {
4824 return;
4825 };
4826
4827 let (element_ty, mut mutability) = match *trait_pred.skip_binder().self_ty().kind() {
4832 ty::Array(element_ty, _) => (element_ty, None),
4833
4834 ty::Ref(_, pointee_ty, mutability) => match *pointee_ty.kind() {
4835 ty::Array(element_ty, _) => (element_ty, Some(mutability)),
4836 _ => return,
4837 },
4838
4839 _ => return,
4840 };
4841
4842 let mut is_slice = |candidate: Ty<'tcx>| match *candidate.kind() {
4845 ty::RawPtr(t, m) | ty::Ref(_, t, m) => {
4846 if let ty::Slice(e) = *t.kind()
4847 && e == element_ty
4848 && m == mutability.unwrap_or(m)
4849 {
4850 mutability = Some(m);
4852 true
4853 } else {
4854 false
4855 }
4856 }
4857 _ => false,
4858 };
4859
4860 if let Some(slice_ty) = candidate_impls
4862 .iter()
4863 .map(|trait_ref| trait_ref.trait_ref.self_ty())
4864 .find(|t| is_slice(*t))
4865 {
4866 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");
4867
4868 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
4869 let mut suggestions = ::alloc::vec::Vec::new()vec![];
4870 if snippet.starts_with('&') {
4871 } else if let Some(hir::Mutability::Mut) = mutability {
4872 suggestions.push((span.shrink_to_lo(), "&mut ".into()));
4873 } else {
4874 suggestions.push((span.shrink_to_lo(), "&".into()));
4875 }
4876 suggestions.push((span.shrink_to_hi(), "[..]".into()));
4877 err.multipart_suggestion(msg, suggestions, Applicability::MaybeIncorrect);
4878 } else {
4879 err.span_help(span, msg);
4880 }
4881 }
4882 }
4883
4884 pub(super) fn suggest_tuple_wrapping(
4889 &self,
4890 err: &mut Diag<'_>,
4891 root_obligation: &PredicateObligation<'tcx>,
4892 obligation: &PredicateObligation<'tcx>,
4893 ) {
4894 let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code() else {
4895 return;
4896 };
4897
4898 let Some(root_pred) = root_obligation.predicate.as_trait_clause() else { return };
4899
4900 let trait_ref = root_pred.map_bound(|root_pred| {
4901 root_pred.trait_ref.with_replaced_self_ty(
4902 self.tcx,
4903 Ty::new_tup(self.tcx, &[root_pred.trait_ref.self_ty()]),
4904 )
4905 });
4906
4907 let obligation =
4908 Obligation::new(self.tcx, obligation.cause.clone(), obligation.param_env, trait_ref);
4909
4910 if self.predicate_must_hold_modulo_regions(&obligation) {
4911 let arg_span = self.tcx.hir_span(*arg_hir_id);
4912 err.multipart_suggestion(
4913 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use a unary tuple instead"))
})format!("use a unary tuple instead"),
4914 ::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())],
4915 Applicability::MaybeIncorrect,
4916 );
4917 }
4918 }
4919
4920 pub(super) fn explain_hrtb_projection(
4921 &self,
4922 diag: &mut Diag<'_>,
4923 pred: ty::PolyTraitPredicate<'tcx>,
4924 param_env: ty::ParamEnv<'tcx>,
4925 cause: &ObligationCause<'tcx>,
4926 ) {
4927 if pred.skip_binder().has_escaping_bound_vars() && pred.skip_binder().has_non_region_infer()
4928 {
4929 self.probe(|_| {
4930 let ocx = ObligationCtxt::new(self);
4931 self.enter_forall(pred, |pred| {
4932 let pred = ocx.normalize(&ObligationCause::dummy(), param_env, pred);
4933 ocx.register_obligation(Obligation::new(
4934 self.tcx,
4935 ObligationCause::dummy(),
4936 param_env,
4937 pred,
4938 ));
4939 });
4940 if !ocx.try_evaluate_obligations().is_empty() {
4941 return;
4943 }
4944
4945 if let ObligationCauseCode::FunctionArg {
4946 call_hir_id,
4947 arg_hir_id,
4948 parent_code: _,
4949 } = cause.code()
4950 {
4951 let arg_span = self.tcx.hir_span(*arg_hir_id);
4952 let mut sp: MultiSpan = arg_span.into();
4953
4954 sp.push_span_label(
4955 arg_span,
4956 "the trait solver is unable to infer the \
4957 generic types that should be inferred from this argument",
4958 );
4959 sp.push_span_label(
4960 self.tcx.hir_span(*call_hir_id),
4961 "add turbofish arguments to this call to \
4962 specify the types manually, even if it's redundant",
4963 );
4964 diag.span_note(
4965 sp,
4966 "this is a known limitation of the trait solver that \
4967 will be lifted in the future",
4968 );
4969 } else {
4970 let mut sp: MultiSpan = cause.span.into();
4971 sp.push_span_label(
4972 cause.span,
4973 "try adding turbofish arguments to this expression to \
4974 specify the types manually, even if it's redundant",
4975 );
4976 diag.span_note(
4977 sp,
4978 "this is a known limitation of the trait solver that \
4979 will be lifted in the future",
4980 );
4981 }
4982 });
4983 }
4984 }
4985
4986 pub(super) fn suggest_desugaring_async_fn_in_trait(
4987 &self,
4988 err: &mut Diag<'_>,
4989 trait_pred: ty::PolyTraitPredicate<'tcx>,
4990 ) {
4991 if self.tcx.features().return_type_notation() {
4993 return;
4994 }
4995
4996 let trait_def_id = trait_pred.def_id();
4997
4998 if !self.tcx.trait_is_auto(trait_def_id) {
5000 return;
5001 }
5002
5003 let ty::Alias(ty::Projection, alias_ty) = trait_pred.self_ty().skip_binder().kind() else {
5005 return;
5006 };
5007 let Some(ty::ImplTraitInTraitData::Trait { fn_def_id, opaque_def_id }) =
5008 self.tcx.opt_rpitit_info(alias_ty.def_id)
5009 else {
5010 return;
5011 };
5012
5013 let auto_trait = self.tcx.def_path_str(trait_def_id);
5014 let Some(fn_def_id) = fn_def_id.as_local() else {
5016 if self.tcx.asyncness(fn_def_id).is_async() {
5018 err.span_note(
5019 self.tcx.def_span(fn_def_id),
5020 ::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!(
5021 "`{}::{}` is an `async fn` in trait, which does not \
5022 automatically imply that its future is `{auto_trait}`",
5023 alias_ty.trait_ref(self.tcx),
5024 self.tcx.item_name(fn_def_id)
5025 ),
5026 );
5027 }
5028 return;
5029 };
5030 let hir::Node::TraitItem(item) = self.tcx.hir_node_by_def_id(fn_def_id) else {
5031 return;
5032 };
5033
5034 let (sig, body) = item.expect_fn();
5036 let hir::FnRetTy::Return(hir::Ty { kind: hir::TyKind::OpaqueDef(opaq_def, ..), .. }) =
5037 sig.decl.output
5038 else {
5039 return;
5041 };
5042
5043 if opaq_def.def_id.to_def_id() != opaque_def_id {
5046 return;
5047 }
5048
5049 let Some(sugg) = suggest_desugaring_async_fn_to_impl_future_in_trait(
5050 self.tcx,
5051 *sig,
5052 *body,
5053 opaque_def_id.expect_local(),
5054 &::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" + {0}", auto_trait))
})format!(" + {auto_trait}"),
5055 ) else {
5056 return;
5057 };
5058
5059 let function_name = self.tcx.def_path_str(fn_def_id);
5060 err.multipart_suggestion(
5061 ::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!(
5062 "`{auto_trait}` can be made part of the associated future's \
5063 guarantees for all implementations of `{function_name}`"
5064 ),
5065 sugg,
5066 Applicability::MachineApplicable,
5067 );
5068 }
5069
5070 pub fn ty_kind_suggestion(
5071 &self,
5072 param_env: ty::ParamEnv<'tcx>,
5073 ty: Ty<'tcx>,
5074 ) -> Option<String> {
5075 let tcx = self.infcx.tcx;
5076 let implements_default = |ty| {
5077 let Some(default_trait) = tcx.get_diagnostic_item(sym::Default) else {
5078 return false;
5079 };
5080 self.type_implements_trait(default_trait, [ty], param_env).must_apply_modulo_regions()
5081 };
5082
5083 Some(match *ty.kind() {
5084 ty::Never | ty::Error(_) => return None,
5085 ty::Bool => "false".to_string(),
5086 ty::Char => "\'x\'".to_string(),
5087 ty::Int(_) | ty::Uint(_) => "42".into(),
5088 ty::Float(_) => "3.14159".into(),
5089 ty::Slice(_) => "[]".to_string(),
5090 ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::Vec) => {
5091 "vec![]".to_string()
5092 }
5093 ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::String) => {
5094 "String::new()".to_string()
5095 }
5096 ty::Adt(def, args) if def.is_box() => {
5097 ::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())?)
5098 }
5099 ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::Option) => {
5100 "None".to_string()
5101 }
5102 ty::Adt(def, args) if Some(def.did()) == tcx.get_diagnostic_item(sym::Result) => {
5103 ::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())?)
5104 }
5105 ty::Adt(_, _) if implements_default(ty) => "Default::default()".to_string(),
5106 ty::Ref(_, ty, mutability) => {
5107 if let (ty::Str, hir::Mutability::Not) = (ty.kind(), mutability) {
5108 "\"\"".to_string()
5109 } else {
5110 let ty = self.ty_kind_suggestion(param_env, ty)?;
5111 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&{0}{1}", mutability.prefix_str(),
ty))
})format!("&{}{ty}", mutability.prefix_str())
5112 }
5113 }
5114 ty::Array(ty, len) if let Some(len) = len.try_to_target_usize(tcx) => {
5115 if len == 0 {
5116 "[]".to_string()
5117 } else if self.type_is_copy_modulo_regions(param_env, ty) || len == 1 {
5118 ::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)
5120 } else {
5121 "/* value */".to_string()
5122 }
5123 }
5124 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!(
5125 "({}{})",
5126 tys.iter()
5127 .map(|ty| self.ty_kind_suggestion(param_env, ty))
5128 .collect::<Option<Vec<String>>>()?
5129 .join(", "),
5130 if tys.len() == 1 { "," } else { "" }
5131 ),
5132 _ => "/* value */".to_string(),
5133 })
5134 }
5135
5136 pub(super) fn suggest_add_result_as_return_type(
5140 &self,
5141 obligation: &PredicateObligation<'tcx>,
5142 err: &mut Diag<'_>,
5143 trait_pred: ty::PolyTraitPredicate<'tcx>,
5144 ) {
5145 if ObligationCauseCode::QuestionMark != *obligation.cause.code().peel_derives() {
5146 return;
5147 }
5148
5149 fn choose_suggest_items<'tcx, 'hir>(
5156 tcx: TyCtxt<'tcx>,
5157 node: hir::Node<'hir>,
5158 ) -> Option<(&'hir hir::FnDecl<'hir>, hir::BodyId)> {
5159 match node {
5160 hir::Node::Item(item)
5161 if let hir::ItemKind::Fn { sig, body: body_id, .. } = item.kind =>
5162 {
5163 Some((sig.decl, body_id))
5164 }
5165 hir::Node::ImplItem(item)
5166 if let hir::ImplItemKind::Fn(sig, body_id) = item.kind =>
5167 {
5168 let parent = tcx.parent_hir_node(item.hir_id());
5169 if let hir::Node::Item(item) = parent
5170 && let hir::ItemKind::Impl(imp) = item.kind
5171 && imp.of_trait.is_none()
5172 {
5173 return Some((sig.decl, body_id));
5174 }
5175 None
5176 }
5177 _ => None,
5178 }
5179 }
5180
5181 let node = self.tcx.hir_node_by_def_id(obligation.cause.body_id);
5182 if let Some((fn_decl, body_id)) = choose_suggest_items(self.tcx, node)
5183 && let hir::FnRetTy::DefaultReturn(ret_span) = fn_decl.output
5184 && self.tcx.is_diagnostic_item(sym::FromResidual, trait_pred.def_id())
5185 && trait_pred.skip_binder().trait_ref.args.type_at(0).is_unit()
5186 && let ty::Adt(def, _) = trait_pred.skip_binder().trait_ref.args.type_at(1).kind()
5187 && self.tcx.is_diagnostic_item(sym::Result, def.did())
5188 {
5189 let mut sugg_spans =
5190 ::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())];
5191 let body = self.tcx.hir_body(body_id);
5192 if let hir::ExprKind::Block(b, _) = body.value.kind
5193 && b.expr.is_none()
5194 {
5195 let span = self.tcx.sess.source_map().end_point(b.span);
5197 sugg_spans.push((
5198 span.shrink_to_lo(),
5199 ::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!(
5200 "{}{}",
5201 " Ok(())\n",
5202 self.tcx.sess.source_map().indentation_before(span).unwrap_or_default(),
5203 ),
5204 ));
5205 }
5206 err.multipart_suggestion(
5207 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider adding return type"))
})format!("consider adding return type"),
5208 sugg_spans,
5209 Applicability::MaybeIncorrect,
5210 );
5211 }
5212 }
5213
5214 #[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(5214u32),
::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:5234",
"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(5234u32),
::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:5247",
"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(5247u32),
::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:5248",
"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(5248u32),
::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:5261",
"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(5261u32),
::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)]
5215 pub(super) fn suggest_unsized_bound_if_applicable(
5216 &self,
5217 err: &mut Diag<'_>,
5218 obligation: &PredicateObligation<'tcx>,
5219 ) {
5220 let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
5221 obligation.predicate.kind().skip_binder()
5222 else {
5223 return;
5224 };
5225 let (ObligationCauseCode::WhereClause(item_def_id, span)
5226 | ObligationCauseCode::WhereClauseInExpr(item_def_id, span, ..)) =
5227 *obligation.cause.code().peel_derives()
5228 else {
5229 return;
5230 };
5231 if span.is_dummy() {
5232 return;
5233 }
5234 debug!(?pred, ?item_def_id, ?span);
5235
5236 let (Some(node), true) = (
5237 self.tcx.hir_get_if_local(item_def_id),
5238 self.tcx.is_lang_item(pred.def_id(), LangItem::Sized),
5239 ) else {
5240 return;
5241 };
5242
5243 let Some(generics) = node.generics() else {
5244 return;
5245 };
5246 let sized_trait = self.tcx.lang_items().sized_trait();
5247 debug!(?generics.params);
5248 debug!(?generics.predicates);
5249 let Some(param) = generics.params.iter().find(|param| param.span == span) else {
5250 return;
5251 };
5252 let explicitly_sized = generics
5255 .bounds_for_param(param.def_id)
5256 .flat_map(|bp| bp.bounds)
5257 .any(|bound| bound.trait_ref().and_then(|tr| tr.trait_def_id()) == sized_trait);
5258 if explicitly_sized {
5259 return;
5260 }
5261 debug!(?param);
5262 match node {
5263 hir::Node::Item(
5264 item @ hir::Item {
5265 kind:
5267 hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) | hir::ItemKind::Union(..),
5268 ..
5269 },
5270 ) => {
5271 if self.suggest_indirection_for_unsized(err, item, param) {
5272 return;
5273 }
5274 }
5275 _ => {}
5276 };
5277
5278 let (span, separator, open_paren_sp) =
5280 if let Some((s, open_paren_sp)) = generics.bounds_span_for_suggestions(param.def_id) {
5281 (s, " +", open_paren_sp)
5282 } else {
5283 (param.name.ident().span.shrink_to_hi(), ":", None)
5284 };
5285
5286 let mut suggs = vec![];
5287 let suggestion = format!("{separator} ?Sized");
5288
5289 if let Some(open_paren_sp) = open_paren_sp {
5290 suggs.push((open_paren_sp, "(".to_string()));
5291 suggs.push((span, format!("){suggestion}")));
5292 } else {
5293 suggs.push((span, suggestion));
5294 }
5295
5296 err.multipart_suggestion(
5297 "consider relaxing the implicit `Sized` restriction",
5298 suggs,
5299 Applicability::MachineApplicable,
5300 );
5301 }
5302
5303 fn suggest_indirection_for_unsized(
5304 &self,
5305 err: &mut Diag<'_>,
5306 item: &hir::Item<'tcx>,
5307 param: &hir::GenericParam<'tcx>,
5308 ) -> bool {
5309 let mut visitor = FindTypeParam { param: param.name.ident().name, .. };
5313 visitor.visit_item(item);
5314 if visitor.invalid_spans.is_empty() {
5315 return false;
5316 }
5317 let mut multispan: MultiSpan = param.span.into();
5318 multispan.push_span_label(
5319 param.span,
5320 ::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()),
5321 );
5322 for sp in visitor.invalid_spans {
5323 multispan.push_span_label(
5324 sp,
5325 ::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()),
5326 );
5327 }
5328 err.span_help(
5329 multispan,
5330 ::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!(
5331 "you could relax the implicit `Sized` bound on `{T}` if it were \
5332 used through indirection like `&{T}` or `Box<{T}>`",
5333 T = param.name.ident(),
5334 ),
5335 );
5336 true
5337 }
5338 pub(crate) fn suggest_swapping_lhs_and_rhs<T>(
5339 &self,
5340 err: &mut Diag<'_>,
5341 predicate: T,
5342 param_env: ty::ParamEnv<'tcx>,
5343 cause_code: &ObligationCauseCode<'tcx>,
5344 ) where
5345 T: Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>>,
5346 {
5347 let tcx = self.tcx;
5348 let predicate = predicate.upcast(tcx);
5349 match *cause_code {
5350 ObligationCauseCode::BinOp { lhs_hir_id, rhs_hir_id, rhs_span, .. }
5351 if let Some(typeck_results) = &self.typeck_results
5352 && let hir::Node::Expr(lhs) = tcx.hir_node(lhs_hir_id)
5353 && let hir::Node::Expr(rhs) = tcx.hir_node(rhs_hir_id)
5354 && let Some(lhs_ty) = typeck_results.expr_ty_opt(lhs)
5355 && let Some(rhs_ty) = typeck_results.expr_ty_opt(rhs) =>
5356 {
5357 if let Some(pred) = predicate.as_trait_clause()
5358 && tcx.is_lang_item(pred.def_id(), LangItem::PartialEq)
5359 && self
5360 .infcx
5361 .type_implements_trait(pred.def_id(), [rhs_ty, lhs_ty], param_env)
5362 .must_apply_modulo_regions()
5363 {
5364 let lhs_span = tcx.hir_span(lhs_hir_id);
5365 let sm = tcx.sess.source_map();
5366 if let Ok(rhs_snippet) = sm.span_to_snippet(rhs_span)
5367 && let Ok(lhs_snippet) = sm.span_to_snippet(lhs_span)
5368 {
5369 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}>`"));
5370 err.multipart_suggestion(
5371 "consider swapping the equality",
5372 ::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)],
5373 Applicability::MaybeIncorrect,
5374 );
5375 }
5376 }
5377 }
5378 _ => {}
5379 }
5380 }
5381}
5382
5383fn hint_missing_borrow<'tcx>(
5385 infcx: &InferCtxt<'tcx>,
5386 param_env: ty::ParamEnv<'tcx>,
5387 span: Span,
5388 found: Ty<'tcx>,
5389 expected: Ty<'tcx>,
5390 found_node: Node<'_>,
5391 err: &mut Diag<'_>,
5392) {
5393 if #[allow(non_exhaustive_omitted_patterns)] match found_node {
Node::TraitItem(..) => true,
_ => false,
}matches!(found_node, Node::TraitItem(..)) {
5394 return;
5395 }
5396
5397 let found_args = match found.kind() {
5398 ty::FnPtr(sig_tys, _) => infcx.enter_forall(*sig_tys, |sig_tys| sig_tys.inputs().iter()),
5399 kind => {
5400 ::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)
5401 }
5402 };
5403 let expected_args = match expected.kind() {
5404 ty::FnPtr(sig_tys, _) => infcx.enter_forall(*sig_tys, |sig_tys| sig_tys.inputs().iter()),
5405 kind => {
5406 ::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)
5407 }
5408 };
5409
5410 let Some(fn_decl) = found_node.fn_decl() else {
5412 return;
5413 };
5414
5415 let args = fn_decl.inputs.iter();
5416
5417 let mut to_borrow = Vec::new();
5418 let mut remove_borrow = Vec::new();
5419
5420 for ((found_arg, expected_arg), arg) in found_args.zip(expected_args).zip(args) {
5421 let (found_ty, found_refs) = get_deref_type_and_refs(*found_arg);
5422 let (expected_ty, expected_refs) = get_deref_type_and_refs(*expected_arg);
5423
5424 if infcx.can_eq(param_env, found_ty, expected_ty) {
5425 if found_refs.len() < expected_refs.len()
5427 && found_refs[..] == expected_refs[expected_refs.len() - found_refs.len()..]
5428 {
5429 to_borrow.push((
5430 arg.span.shrink_to_lo(),
5431 expected_refs[..expected_refs.len() - found_refs.len()]
5432 .iter()
5433 .map(|mutbl| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&{0}", mutbl.prefix_str()))
})format!("&{}", mutbl.prefix_str()))
5434 .collect::<Vec<_>>()
5435 .join(""),
5436 ));
5437 } else if found_refs.len() > expected_refs.len() {
5438 let mut span = arg.span.shrink_to_lo();
5439 let mut left = found_refs.len() - expected_refs.len();
5440 let mut ty = arg;
5441 while let hir::TyKind::Ref(_, mut_ty) = &ty.kind
5442 && left > 0
5443 {
5444 span = span.with_hi(mut_ty.ty.span.lo());
5445 ty = mut_ty.ty;
5446 left -= 1;
5447 }
5448 if left == 0 {
5449 remove_borrow.push((span, String::new()));
5450 }
5451 }
5452 }
5453 }
5454
5455 if !to_borrow.is_empty() {
5456 err.subdiagnostic(errors::AdjustSignatureBorrow::Borrow { to_borrow });
5457 }
5458
5459 if !remove_borrow.is_empty() {
5460 err.subdiagnostic(errors::AdjustSignatureBorrow::RemoveBorrow { remove_borrow });
5461 }
5462}
5463
5464#[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)]
5467pub struct SelfVisitor<'v> {
5468 pub paths: Vec<&'v hir::Ty<'v>> = Vec::new(),
5469 pub name: Option<Symbol>,
5470}
5471
5472impl<'v> Visitor<'v> for SelfVisitor<'v> {
5473 fn visit_ty(&mut self, ty: &'v hir::Ty<'v, AmbigArg>) {
5474 if let hir::TyKind::Path(path) = ty.kind
5475 && let hir::QPath::TypeRelative(inner_ty, segment) = path
5476 && (Some(segment.ident.name) == self.name || self.name.is_none())
5477 && let hir::TyKind::Path(inner_path) = inner_ty.kind
5478 && let hir::QPath::Resolved(None, inner_path) = inner_path
5479 && let Res::SelfTyAlias { .. } = inner_path.res
5480 {
5481 self.paths.push(ty.as_unambig_ty());
5482 }
5483 hir::intravisit::walk_ty(self, ty);
5484 }
5485}
5486
5487#[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)]
5490pub struct ReturnsVisitor<'v> {
5491 pub returns: Vec<&'v hir::Expr<'v>>,
5492 in_block_tail: bool,
5493}
5494
5495impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
5496 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
5497 match ex.kind {
5502 hir::ExprKind::Ret(Some(ex)) => {
5503 self.returns.push(ex);
5504 }
5505 hir::ExprKind::Block(block, _) if self.in_block_tail => {
5506 self.in_block_tail = false;
5507 for stmt in block.stmts {
5508 hir::intravisit::walk_stmt(self, stmt);
5509 }
5510 self.in_block_tail = true;
5511 if let Some(expr) = block.expr {
5512 self.visit_expr(expr);
5513 }
5514 }
5515 hir::ExprKind::If(_, then, else_opt) if self.in_block_tail => {
5516 self.visit_expr(then);
5517 if let Some(el) = else_opt {
5518 self.visit_expr(el);
5519 }
5520 }
5521 hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
5522 for arm in arms {
5523 self.visit_expr(arm.body);
5524 }
5525 }
5526 _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
5528 _ => self.returns.push(ex),
5529 }
5530 }
5531
5532 fn visit_body(&mut self, body: &hir::Body<'v>) {
5533 if !!self.in_block_tail {
::core::panicking::panic("assertion failed: !self.in_block_tail")
};assert!(!self.in_block_tail);
5534 self.in_block_tail = true;
5535 hir::intravisit::walk_body(self, body);
5536 }
5537}
5538
5539#[derive(#[automatically_derived]
impl ::core::default::Default for AwaitsVisitor {
#[inline]
fn default() -> AwaitsVisitor {
AwaitsVisitor { awaits: ::core::default::Default::default() }
}
}Default)]
5541struct AwaitsVisitor {
5542 awaits: Vec<HirId>,
5543}
5544
5545impl<'v> Visitor<'v> for AwaitsVisitor {
5546 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
5547 if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
5548 self.awaits.push(id)
5549 }
5550 hir::intravisit::walk_expr(self, ex)
5551 }
5552}
5553
5554pub trait NextTypeParamName {
5558 fn next_type_param_name(&self, name: Option<&str>) -> String;
5559}
5560
5561impl NextTypeParamName for &[hir::GenericParam<'_>] {
5562 fn next_type_param_name(&self, name: Option<&str>) -> String {
5563 let name = name.and_then(|n| n.chars().next()).map(|c| c.to_uppercase().to_string());
5565 let name = name.as_deref();
5566
5567 let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
5569
5570 let used_names: Vec<Symbol> = self
5572 .iter()
5573 .filter_map(|param| match param.name {
5574 hir::ParamName::Plain(ident) => Some(ident.name),
5575 _ => None,
5576 })
5577 .collect();
5578
5579 possible_names
5581 .iter()
5582 .find(|n| !used_names.contains(&Symbol::intern(n)))
5583 .unwrap_or(&"ParamName")
5584 .to_string()
5585 }
5586}
5587
5588struct ReplaceImplTraitVisitor<'a> {
5590 ty_spans: &'a mut Vec<Span>,
5591 param_did: DefId,
5592}
5593
5594impl<'a, 'hir> hir::intravisit::Visitor<'hir> for ReplaceImplTraitVisitor<'a> {
5595 fn visit_ty(&mut self, t: &'hir hir::Ty<'hir, AmbigArg>) {
5596 if let hir::TyKind::Path(hir::QPath::Resolved(
5597 None,
5598 hir::Path { res: Res::Def(_, segment_did), .. },
5599 )) = t.kind
5600 {
5601 if self.param_did == *segment_did {
5602 self.ty_spans.push(t.span);
5607 return;
5608 }
5609 }
5610
5611 hir::intravisit::walk_ty(self, t);
5612 }
5613}
5614
5615pub(super) fn get_explanation_based_on_obligation<'tcx>(
5616 tcx: TyCtxt<'tcx>,
5617 obligation: &PredicateObligation<'tcx>,
5618 trait_predicate: ty::PolyTraitPredicate<'tcx>,
5619 pre_message: String,
5620 long_ty_path: &mut Option<PathBuf>,
5621) -> String {
5622 if let ObligationCauseCode::MainFunctionType = obligation.cause.code() {
5623 "consider using `()`, or a `Result`".to_owned()
5624 } else {
5625 let ty_desc = match trait_predicate.self_ty().skip_binder().kind() {
5626 ty::FnDef(_, _) => Some("fn item"),
5627 ty::Closure(_, _) => Some("closure"),
5628 _ => None,
5629 };
5630
5631 let desc = match ty_desc {
5632 Some(desc) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" {0}", desc))
})format!(" {desc}"),
5633 None => String::new(),
5634 };
5635 if let ty::PredicatePolarity::Positive = trait_predicate.polarity() {
5636 let mention_unstable = !tcx.sess.opts.unstable_opts.force_unstable_if_unmarked
5641 && try { tcx.lookup_stability(trait_predicate.def_id())?.level.is_stable() }
5642 == Some(false);
5643 let unstable = if mention_unstable { "nightly-only, unstable " } else { "" };
5644
5645 ::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!(
5646 "{pre_message}the {unstable}trait `{}` is not implemented for{desc} `{}`",
5647 trait_predicate.print_modifiers_and_trait_path(),
5648 tcx.short_string(trait_predicate.self_ty().skip_binder(), long_ty_path),
5649 )
5650 } else {
5651 ::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")
5655 }
5656 }
5657}
5658
5659struct ReplaceImplTraitFolder<'tcx> {
5661 tcx: TyCtxt<'tcx>,
5662 param: &'tcx ty::GenericParamDef,
5663 replace_ty: Ty<'tcx>,
5664}
5665
5666impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ReplaceImplTraitFolder<'tcx> {
5667 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
5668 if let ty::Param(ty::ParamTy { index, .. }) = t.kind() {
5669 if self.param.index == *index {
5670 return self.replace_ty;
5671 }
5672 }
5673 t.super_fold_with(self)
5674 }
5675
5676 fn cx(&self) -> TyCtxt<'tcx> {
5677 self.tcx
5678 }
5679}
5680
5681pub fn suggest_desugaring_async_fn_to_impl_future_in_trait<'tcx>(
5682 tcx: TyCtxt<'tcx>,
5683 sig: hir::FnSig<'tcx>,
5684 body: hir::TraitFn<'tcx>,
5685 opaque_def_id: LocalDefId,
5686 add_bounds: &str,
5687) -> Option<Vec<(Span, String)>> {
5688 let hir::IsAsync::Async(async_span) = sig.header.asyncness else {
5689 return None;
5690 };
5691 let async_span = tcx.sess.source_map().span_extend_while_whitespace(async_span);
5692
5693 let future = tcx.hir_node_by_def_id(opaque_def_id).expect_opaque_ty();
5694 let [hir::GenericBound::Trait(trait_ref)] = future.bounds else {
5695 return None;
5697 };
5698 let Some(hir::PathSegment { args: Some(args), .. }) = trait_ref.trait_ref.path.segments.last()
5699 else {
5700 return None;
5702 };
5703 let Some(future_output_ty) = args.constraints.first().and_then(|constraint| constraint.ty())
5704 else {
5705 return None;
5707 };
5708
5709 let mut sugg = if future_output_ty.span.is_empty() {
5710 ::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![
5711 (async_span, String::new()),
5712 (
5713 future_output_ty.span,
5714 format!(" -> impl std::future::Future<Output = ()>{add_bounds}"),
5715 ),
5716 ]
5717 } else {
5718 ::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![
5719 (future_output_ty.span.shrink_to_lo(), "impl std::future::Future<Output = ".to_owned()),
5720 (future_output_ty.span.shrink_to_hi(), format!(">{add_bounds}")),
5721 (async_span, String::new()),
5722 ]
5723 };
5724
5725 if let hir::TraitFn::Provided(body) = body {
5727 let body = tcx.hir_body(body);
5728 let body_span = body.value.span;
5729 let body_span_without_braces =
5730 body_span.with_lo(body_span.lo() + BytePos(1)).with_hi(body_span.hi() - BytePos(1));
5731 if body_span_without_braces.is_empty() {
5732 sugg.push((body_span_without_braces, " async {} ".to_owned()));
5733 } else {
5734 sugg.extend([
5735 (body_span_without_braces.shrink_to_lo(), "async {".to_owned()),
5736 (body_span_without_braces.shrink_to_hi(), "} ".to_owned()),
5737 ]);
5738 }
5739 }
5740
5741 Some(sugg)
5742}
5743
5744fn point_at_assoc_type_restriction<G: EmissionGuarantee>(
5747 tcx: TyCtxt<'_>,
5748 err: &mut Diag<'_, G>,
5749 self_ty_str: &str,
5750 trait_name: &str,
5751 predicate: ty::Predicate<'_>,
5752 generics: &hir::Generics<'_>,
5753 data: &ImplDerivedCause<'_>,
5754) {
5755 let ty::PredicateKind::Clause(clause) = predicate.kind().skip_binder() else {
5756 return;
5757 };
5758 let ty::ClauseKind::Projection(proj) = clause else {
5759 return;
5760 };
5761 let name = tcx.item_name(proj.projection_term.def_id);
5762 let mut predicates = generics.predicates.iter().peekable();
5763 let mut prev: Option<(&hir::WhereBoundPredicate<'_>, Span)> = None;
5764 while let Some(pred) = predicates.next() {
5765 let curr_span = pred.span;
5766 let hir::WherePredicateKind::BoundPredicate(pred) = pred.kind else {
5767 continue;
5768 };
5769 let mut bounds = pred.bounds.iter();
5770 while let Some(bound) = bounds.next() {
5771 let Some(trait_ref) = bound.trait_ref() else {
5772 continue;
5773 };
5774 if bound.span() != data.span {
5775 continue;
5776 }
5777 if let hir::TyKind::Path(path) = pred.bounded_ty.kind
5778 && let hir::QPath::TypeRelative(ty, segment) = path
5779 && segment.ident.name == name
5780 && let hir::TyKind::Path(inner_path) = ty.kind
5781 && let hir::QPath::Resolved(None, inner_path) = inner_path
5782 && let Res::SelfTyAlias { .. } = inner_path.res
5783 {
5784 let span = if pred.origin == hir::PredicateOrigin::WhereClause
5787 && generics
5788 .predicates
5789 .iter()
5790 .filter(|p| {
5791 #[allow(non_exhaustive_omitted_patterns)] match p.kind {
hir::WherePredicateKind::BoundPredicate(p) if
hir::PredicateOrigin::WhereClause == p.origin => true,
_ => false,
}matches!(
5792 p.kind,
5793 hir::WherePredicateKind::BoundPredicate(p)
5794 if hir::PredicateOrigin::WhereClause == p.origin
5795 )
5796 })
5797 .count()
5798 == 1
5799 {
5800 generics.where_clause_span
5803 } else if let Some(next_pred) = predicates.peek()
5804 && let hir::WherePredicateKind::BoundPredicate(next) = next_pred.kind
5805 && pred.origin == next.origin
5806 {
5807 curr_span.until(next_pred.span)
5809 } else if let Some((prev, prev_span)) = prev
5810 && pred.origin == prev.origin
5811 {
5812 prev_span.shrink_to_hi().to(curr_span)
5814 } else if pred.origin == hir::PredicateOrigin::WhereClause {
5815 curr_span.with_hi(generics.where_clause_span.hi())
5816 } else {
5817 curr_span
5818 };
5819
5820 err.span_suggestion_verbose(
5821 span,
5822 "associated type for the current `impl` cannot be restricted in `where` \
5823 clauses, remove this bound",
5824 "",
5825 Applicability::MaybeIncorrect,
5826 );
5827 }
5828 if let Some(new) =
5829 tcx.associated_items(data.impl_or_alias_def_id).find_by_ident_and_kind(
5830 tcx,
5831 Ident::with_dummy_span(name),
5832 ty::AssocTag::Type,
5833 data.impl_or_alias_def_id,
5834 )
5835 {
5836 let span = tcx.def_span(new.def_id);
5839 err.span_label(
5840 span,
5841 ::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!(
5842 "associated type `<{self_ty_str} as {trait_name}>::{name}` is specified \
5843 here",
5844 ),
5845 );
5846 let mut visitor = SelfVisitor { name: Some(name), .. };
5849 visitor.visit_trait_ref(trait_ref);
5850 for path in visitor.paths {
5851 err.span_suggestion_verbose(
5852 path.span,
5853 "replace the associated type with the type specified in this `impl`",
5854 tcx.type_of(new.def_id).skip_binder(),
5855 Applicability::MachineApplicable,
5856 );
5857 }
5858 } else {
5859 let mut visitor = SelfVisitor { name: None, .. };
5860 visitor.visit_trait_ref(trait_ref);
5861 let span: MultiSpan =
5862 visitor.paths.iter().map(|p| p.span).collect::<Vec<Span>>().into();
5863 err.span_note(
5864 span,
5865 "associated types for the current `impl` cannot be restricted in `where` \
5866 clauses",
5867 );
5868 }
5869 }
5870 prev = Some((pred, curr_span));
5871 }
5872}
5873
5874fn get_deref_type_and_refs(mut ty: Ty<'_>) -> (Ty<'_>, Vec<hir::Mutability>) {
5875 let mut refs = ::alloc::vec::Vec::new()vec![];
5876
5877 while let ty::Ref(_, new_ty, mutbl) = ty.kind() {
5878 ty = *new_ty;
5879 refs.push(*mutbl);
5880 }
5881
5882 (ty, refs)
5883}
5884
5885struct FindTypeParam {
5888 param: rustc_span::Symbol,
5889 invalid_spans: Vec<Span> = Vec::new(),
5890 nested: bool = false,
5891}
5892
5893impl<'v> Visitor<'v> for FindTypeParam {
5894 fn visit_where_predicate(&mut self, _: &'v hir::WherePredicate<'v>) {
5895 }
5897
5898 fn visit_ty(&mut self, ty: &hir::Ty<'_, AmbigArg>) {
5899 match ty.kind {
5906 hir::TyKind::Ptr(_) | hir::TyKind::Ref(..) | hir::TyKind::TraitObject(..) => {}
5907 hir::TyKind::Path(hir::QPath::Resolved(None, path))
5908 if let [segment] = path.segments
5909 && segment.ident.name == self.param =>
5910 {
5911 if !self.nested {
5912 {
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:5912",
"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(5912u32),
::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");
5913 self.invalid_spans.push(ty.span);
5914 }
5915 }
5916 hir::TyKind::Path(_) => {
5917 let prev = self.nested;
5918 self.nested = true;
5919 hir::intravisit::walk_ty(self, ty);
5920 self.nested = prev;
5921 }
5922 _ => {
5923 hir::intravisit::walk_ty(self, ty);
5924 }
5925 }
5926 }
5927}
5928
5929struct ParamFinder {
5932 params: Vec<Symbol> = Vec::new(),
5933}
5934
5935impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ParamFinder {
5936 fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
5937 match t.kind() {
5938 ty::Param(p) => self.params.push(p.name),
5939 _ => {}
5940 }
5941 t.super_visit_with(self)
5942 }
5943}
5944
5945impl ParamFinder {
5946 fn can_suggest_bound(&self, generics: &hir::Generics<'_>) -> bool {
5949 if self.params.is_empty() {
5950 return true;
5953 }
5954 generics.params.iter().any(|p| match p.name {
5955 hir::ParamName::Plain(p_name) => {
5956 self.params.iter().any(|p| *p == p_name.name || *p == kw::SelfUpper)
5958 }
5959 _ => true,
5960 })
5961 }
5962}