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