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