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 PrintPolyTraitClauseExt as _, PrintPolyTraitRefExt, PrintTraitClauseExt 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::PolyTraitClause<'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::PolyTraitClause<'tcx>,
468 associated_ty: Option<(&'static str, Ty<'tcx>)>,
469 mut body_def_id: LocalDefId,
470 ) {
471 if trait_pred.skip_binder().polarity != ty::ClausePolarity::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::PolyTraitClause<'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::TraitClause {
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::PolyTraitClause<'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 let callee_hir_id = match obligation.cause.code() {
1123 ObligationCauseCode::FunctionArg { arg_hir_id, .. }
1124 if obligation.cause.span.can_be_used_for_suggestions() =>
1125 {
1126 Some(*arg_hir_id)
1127 }
1128 code => match code.peel_derives() {
1132 ObligationCauseCode::ForLoopIterator(iter_hir_id)
1133 if self.tcx.hir_span(*iter_hir_id).can_be_used_for_suggestions() =>
1134 {
1135 Some(*iter_hir_id)
1136 }
1137 _ => None,
1138 },
1139 };
1140
1141 if let Some(callee_hir_id) = callee_hir_id {
1142 let span = obligation.cause.span;
1143
1144 let arg_expr = match self.tcx.hir_node(callee_hir_id) {
1145 hir::Node::Expr(expr) => Some(expr),
1146 _ => None,
1147 };
1148
1149 let is_closure_expr =
1150 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(..)));
1151
1152 if args.is_empty()
1155 && let Some(expr) = arg_expr
1156 && let hir::ExprKind::Closure(closure) = expr.kind
1157 {
1158 let mut body = self.tcx.hir_body(closure.body).value;
1159
1160 if let hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async) =
1162 closure.kind
1163 {
1164 let peeled = body.peel_blocks().peel_drop_temps();
1165 if let hir::ExprKind::Closure(inner) = peeled.kind {
1166 body = self.tcx.hir_body(inner.body).value;
1167 }
1168 }
1169
1170 let peeled_body = body.peel_blocks().peel_drop_temps();
1171 if let hir::ExprKind::Call(callee, call_args) = peeled_body.kind
1172 && call_args.is_empty()
1173 && let hir::ExprKind::Block(..) = callee.peel_blocks().peel_drop_temps().kind
1174 {
1175 return false;
1176 }
1177 }
1178
1179 if is_closure_expr {
1180 err.multipart_suggestions(
1181 msg,
1182 ::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![
1183 (span.shrink_to_lo(), "(".to_string()),
1184 (span.shrink_to_hi(), format!(")({args})")),
1185 ]],
1186 Applicability::HasPlaceholders,
1187 );
1188 } else {
1189 err.span_suggestion_verbose(
1190 span.shrink_to_hi(),
1191 msg,
1192 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0})", args))
})format!("({args})"),
1193 Applicability::HasPlaceholders,
1194 );
1195 }
1196 } else if let DefIdOrName::DefId(def_id) = def_id_or_name {
1197 let name = match self.tcx.hir_get_if_local(def_id) {
1198 Some(hir::Node::Expr(hir::Expr {
1199 kind: hir::ExprKind::Closure(hir::Closure { fn_decl_span, .. }),
1200 ..
1201 })) => {
1202 err.span_label(*fn_decl_span, "consider calling this closure");
1203 let Some(name) = self.get_closure_name(def_id, err, msg.clone()) else {
1204 return false;
1205 };
1206 name.to_string()
1207 }
1208 Some(hir::Node::Item(hir::Item {
1209 kind: hir::ItemKind::Fn { ident, .. }, ..
1210 })) => {
1211 err.span_label(ident.span, "consider calling this function");
1212 ident.to_string()
1213 }
1214 Some(hir::Node::Ctor(..)) => {
1215 let name = self.tcx.def_path_str(def_id);
1216 err.span_label(
1217 self.tcx.def_span(def_id),
1218 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider calling the constructor for `{0}`",
name))
})format!("consider calling the constructor for `{name}`"),
1219 );
1220 name
1221 }
1222 _ => return false,
1223 };
1224 err.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: `{1}({2})`", msg, name, args))
})format!("{msg}: `{name}({args})`"));
1225 }
1226 true
1227 }
1228
1229 pub(super) fn suggest_cast_to_fn_pointer(
1230 &self,
1231 obligation: &PredicateObligation<'tcx>,
1232 err: &mut Diag<'_>,
1233 leaf_trait_predicate: ty::PolyTraitClause<'tcx>,
1234 main_trait_predicate: ty::PolyTraitClause<'tcx>,
1235 span: Span,
1236 ) -> bool {
1237 let &[candidate] = &self.find_similar_impl_candidates(leaf_trait_predicate)[..] else {
1238 return false;
1239 };
1240 let candidate = candidate.trait_ref;
1241
1242 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!(
1243 (candidate.self_ty().kind(), main_trait_predicate.self_ty().skip_binder().kind(),),
1244 (ty::FnPtr(..), ty::FnDef(..))
1245 ) {
1246 return false;
1247 }
1248
1249 let parenthesized_cast = |span: Span| {
1250 ::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![
1251 (span.shrink_to_lo(), "(".to_string()),
1252 (span.shrink_to_hi(), format!(" as {})", candidate.self_ty())),
1253 ]
1254 };
1255 let suggestion = if self.tcx.sess.source_map().span_followed_by(span, ".").is_some() {
1257 parenthesized_cast(span)
1258 } else if let Some(body) = self.tcx.hir_maybe_body_owned_by(obligation.cause.body_def_id) {
1259 let mut expr_finder = FindExprBySpan::new(span, self.tcx);
1260 expr_finder.visit_expr(body.value);
1261 if let Some(expr) = expr_finder.result
1262 && let hir::ExprKind::AddrOf(_, _, expr) = expr.kind
1263 {
1264 parenthesized_cast(expr.span)
1265 } else {
1266 ::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()))]
1267 }
1268 } else {
1269 ::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()))]
1270 };
1271
1272 let trait_ = self.tcx.short_string(candidate.print_trait_sugared(), err.long_ty_path());
1273 let self_ty = self.tcx.short_string(candidate.self_ty(), err.long_ty_path());
1274 err.multipart_suggestion(
1275 ::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!(
1276 "the trait `{trait_}` is implemented for fn pointer \
1277 `{self_ty}`, try casting using `as`",
1278 ),
1279 suggestion,
1280 Applicability::MaybeIncorrect,
1281 );
1282 true
1283 }
1284
1285 pub(super) fn check_for_binding_assigned_block_without_tail_expression(
1286 &self,
1287 obligation: &PredicateObligation<'tcx>,
1288 err: &mut Diag<'_>,
1289 trait_pred: ty::PolyTraitClause<'tcx>,
1290 ) {
1291 let mut span = obligation.cause.span;
1292 while span.from_expansion() {
1293 span.remove_mark();
1295 }
1296 let mut expr_finder = FindExprBySpan::new(span, self.tcx);
1297 let Some(body) = self.tcx.hir_maybe_body_owned_by(obligation.cause.body_def_id) else {
1298 return;
1299 };
1300 expr_finder.visit_expr(body.value);
1301 let Some(expr) = expr_finder.result else {
1302 return;
1303 };
1304 let Some(typeck) = &self.typeck_results else {
1305 return;
1306 };
1307 let Some(ty) = typeck.expr_ty_adjusted_opt(expr) else {
1308 return;
1309 };
1310 if !ty.is_unit() {
1311 return;
1312 };
1313 let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind else {
1314 return;
1315 };
1316 let Res::Local(hir_id) = path.res else {
1317 return;
1318 };
1319 let hir::Node::Pat(pat) = self.tcx.hir_node(hir_id) else {
1320 return;
1321 };
1322 let hir::Node::LetStmt(hir::LetStmt { ty: None, init: Some(init), .. }) =
1323 self.tcx.parent_hir_node(pat.hir_id)
1324 else {
1325 return;
1326 };
1327 let hir::ExprKind::Block(block, None) = init.kind else {
1328 return;
1329 };
1330 if block.expr.is_some() {
1331 return;
1332 }
1333 let [.., stmt] = block.stmts else {
1334 err.span_label(block.span, "this empty block is missing a tail expression");
1335 return;
1336 };
1337 if stmt.span.from_expansion() {
1340 return;
1341 }
1342 let hir::StmtKind::Semi(tail_expr) = stmt.kind else {
1343 return;
1344 };
1345 let Some(ty) = typeck.expr_ty_opt(tail_expr) else {
1346 err.span_label(block.span, "this block is missing a tail expression");
1347 return;
1348 };
1349 let ty = self.resolve_numeric_literals_with_default(self.resolve_vars_if_possible(ty));
1350 let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, ty));
1351
1352 let new_obligation =
1353 self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred_and_self);
1354 if !#[allow(non_exhaustive_omitted_patterns)] match tail_expr.kind {
hir::ExprKind::Err(_) => true,
_ => false,
}matches!(tail_expr.kind, hir::ExprKind::Err(_))
1355 && self.predicate_must_hold_modulo_regions(&new_obligation)
1356 {
1357 err.span_suggestion_short(
1358 stmt.span.with_lo(tail_expr.span.hi()),
1359 "remove this semicolon",
1360 "",
1361 Applicability::MachineApplicable,
1362 );
1363 } else {
1364 err.span_label(block.span, "this block is missing a tail expression");
1365 }
1366 }
1367
1368 pub(super) fn suggest_add_clone_to_arg(
1369 &self,
1370 obligation: &PredicateObligation<'tcx>,
1371 err: &mut Diag<'_>,
1372 trait_pred: ty::PolyTraitClause<'tcx>,
1373 ) -> bool {
1374 let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
1375 self.enter_forall(self_ty, |ty: Ty<'_>| {
1376 let Some(generics) = self.tcx.hir_get_generics(obligation.cause.body_def_id) else {
1377 return false;
1378 };
1379 let ty::Ref(_, inner_ty, hir::Mutability::Not) = ty.kind() else { return false };
1380 let ty::Param(param) = inner_ty.kind() else { return false };
1381 let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code()
1382 else {
1383 return false;
1384 };
1385
1386 let clone_trait = self.tcx.require_lang_item(LangItem::Clone, obligation.cause.span);
1387 let has_clone = |ty| {
1388 self.type_implements_trait(clone_trait, [ty], obligation.param_env)
1389 .must_apply_modulo_regions()
1390 };
1391
1392 let existing_clone_call = match self.tcx.hir_node(*arg_hir_id) {
1393 Node::Expr(Expr { kind: hir::ExprKind::Path(_), .. }) => None,
1395 Node::Expr(Expr {
1398 kind:
1399 hir::ExprKind::MethodCall(
1400 hir::PathSegment { ident, .. },
1401 _receiver,
1402 [],
1403 call_span,
1404 ),
1405 hir_id,
1406 ..
1407 }) if ident.name == sym::clone
1408 && !call_span.from_expansion()
1409 && !has_clone(*inner_ty) =>
1410 {
1411 let Some(typeck_results) = self.typeck_results.as_ref() else { return false };
1413 let Some((DefKind::AssocFn, did)) = typeck_results.type_dependent_def(*hir_id)
1414 else {
1415 return false;
1416 };
1417 if self.tcx.trait_of_assoc(did) != Some(clone_trait) {
1418 return false;
1419 }
1420 Some(ident.span)
1421 }
1422 _ => return false,
1423 };
1424
1425 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1426 obligation.param_env,
1427 trait_pred.map_bound(|trait_pred| (trait_pred, *inner_ty)),
1428 );
1429
1430 if self.predicate_may_hold(&new_obligation) && has_clone(ty) {
1431 if !has_clone(param.to_ty(self.tcx)) {
1432 suggest_constraining_type_param(
1433 self.tcx,
1434 generics,
1435 err,
1436 param.name.as_str(),
1437 "Clone",
1438 Some(clone_trait),
1439 None,
1440 );
1441 }
1442 if let Some(existing_clone_call) = existing_clone_call {
1443 err.span_note(
1444 existing_clone_call,
1445 ::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!(
1446 "this `clone()` copies the reference, \
1447 which does not do anything, \
1448 because `{inner_ty}` does not implement `Clone`"
1449 ),
1450 );
1451 } else {
1452 err.span_suggestion_verbose(
1453 obligation.cause.span.shrink_to_hi(),
1454 "consider using clone here",
1455 ".clone()".to_string(),
1456 Applicability::MaybeIncorrect,
1457 );
1458 }
1459 return true;
1460 }
1461 false
1462 })
1463 }
1464
1465 pub fn extract_callable_info(
1469 &self,
1470 body_def_id: LocalDefId,
1471 param_env: ty::ParamEnv<'tcx>,
1472 found: Ty<'tcx>,
1473 ) -> Option<(DefIdOrName, Ty<'tcx>, Vec<Ty<'tcx>>)> {
1474 let Some((def_id_or_name, output, inputs)) =
1476 (self.autoderef_steps)(found).into_iter().find_map(|(found, _)| match *found.kind() {
1477 ty::FnPtr(sig_tys, _) => Some((
1478 DefIdOrName::Name("function pointer"),
1479 sig_tys.output(),
1480 sig_tys.inputs(),
1481 )),
1482 ty::FnDef(def_id, _) => {
1483 let fn_sig = found.fn_sig(self.tcx);
1484 Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs()))
1485 }
1486 ty::Closure(def_id, args) => {
1487 let fn_sig = args.as_closure().sig();
1488 Some((
1489 DefIdOrName::DefId(def_id),
1490 fn_sig.output(),
1491 fn_sig.inputs().map_bound(|inputs| inputs[0].tuple_fields().as_slice()),
1492 ))
1493 }
1494 ty::CoroutineClosure(def_id, args) => {
1495 let sig_parts = args.as_coroutine_closure().coroutine_closure_sig();
1496 Some((
1497 DefIdOrName::DefId(def_id),
1498 sig_parts.map_bound(|sig| {
1499 sig.to_coroutine(
1500 self.tcx,
1501 args.as_coroutine_closure().parent_args(),
1502 self.next_ty_var(DUMMY_SP),
1505 self.tcx.coroutine_for_closure(def_id),
1506 self.next_ty_var(DUMMY_SP),
1507 )
1508 }),
1509 sig_parts.map_bound(|sig| sig.tupled_inputs_ty.tuple_fields().as_slice()),
1510 ))
1511 }
1512 ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, args, .. }) => {
1513 self.tcx
1514 .item_self_bounds(def_id)
1515 .instantiate(self.tcx, args)
1516 .skip_norm_wip()
1517 .iter()
1518 .find_map(|pred| {
1519 if let ty::ClauseKind::Projection(proj) = pred.kind().skip_binder()
1520 && self
1521 .tcx
1522 .is_lang_item(proj.def_id(), LangItem::FnOnceOutput)
1523 && let ty::Tuple(args) = proj.projection_term.args.type_at(1).kind()
1525 {
1526 Some((
1527 DefIdOrName::DefId(def_id),
1528 pred.kind().rebind(proj.term.expect_type()),
1529 pred.kind().rebind(args.as_slice()),
1530 ))
1531 } else {
1532 None
1533 }
1534 })
1535 }
1536 ty::Dynamic(data, _) => data.iter().find_map(|pred| {
1537 if let ty::ExistentialPredicate::Projection(proj) = pred.skip_binder()
1538 && self.tcx.is_lang_item(proj.def_id, LangItem::FnOnceOutput)
1539 && let ty::Tuple(args) = proj.args.type_at(0).kind()
1541 {
1542 Some((
1543 DefIdOrName::Name("trait object"),
1544 pred.rebind(proj.term.expect_type()),
1545 pred.rebind(args.as_slice()),
1546 ))
1547 } else {
1548 None
1549 }
1550 }),
1551 ty::Param(param) => {
1552 let generics = self.tcx.generics_of(body_def_id);
1553 let name = if generics.count() > param.index as usize
1554 && let def = generics.param_at(param.index as usize, self.tcx)
1555 && #[allow(non_exhaustive_omitted_patterns)] match def.kind {
ty::GenericParamDefKind::Type { .. } => true,
_ => false,
}matches!(def.kind, ty::GenericParamDefKind::Type { .. })
1556 && def.name == param.name
1557 {
1558 DefIdOrName::DefId(def.def_id)
1559 } else {
1560 DefIdOrName::Name("type parameter")
1561 };
1562 param_env.caller_bounds().find_map(|clause| {
1563 if let ty::ClauseKind::Projection(proj) = clause.kind().skip_binder()
1564 && self
1565 .tcx
1566 .is_lang_item(proj.def_id(), LangItem::FnOnceOutput)
1567 && proj.projection_term.self_ty() == found
1568 && let ty::Tuple(args) = proj.projection_term.args.type_at(1).kind()
1570 {
1571 Some((
1572 name,
1573 clause.kind().rebind(proj.term.expect_type()),
1574 clause.kind().rebind(args.as_slice()),
1575 ))
1576 } else {
1577 None
1578 }
1579 })
1580 }
1581 _ => None,
1582 })
1583 else {
1584 return None;
1585 };
1586
1587 let output = self.instantiate_binder_with_fresh_vars(
1588 DUMMY_SP,
1589 BoundRegionConversionTime::FnCall,
1590 output,
1591 );
1592 let inputs = inputs
1593 .skip_binder()
1594 .iter()
1595 .map(|ty| {
1596 self.instantiate_binder_with_fresh_vars(
1597 DUMMY_SP,
1598 BoundRegionConversionTime::FnCall,
1599 inputs.rebind(*ty),
1600 )
1601 })
1602 .collect();
1603
1604 let InferOk { value: output, obligations: _ } =
1608 self.at(&ObligationCause::dummy(), param_env).normalize(Unnormalized::new_wip(output));
1609
1610 if output.is_ty_var() { None } else { Some((def_id_or_name, output, inputs)) }
1611 }
1612
1613 pub(super) fn where_clause_expr_matches_failed_self_ty(
1614 &self,
1615 obligation: &PredicateObligation<'tcx>,
1616 old_self_ty: Ty<'tcx>,
1617 ) -> bool {
1618 let ObligationCauseCode::WhereClauseInExpr(..) = obligation.cause.code() else {
1619 return true;
1620 };
1621 let (Some(typeck_results), Some(body)) = (
1622 self.typeck_results.as_ref(),
1623 self.tcx.hir_maybe_body_owned_by(obligation.cause.body_def_id),
1624 ) else {
1625 return true;
1626 };
1627
1628 let mut expr_finder = FindExprBySpan::new(obligation.cause.span, self.tcx);
1629 expr_finder.visit_expr(body.value);
1630 let Some(expr) = expr_finder.result else {
1631 return true;
1632 };
1633
1634 let inner_old_self_ty = match old_self_ty.kind() {
1635 ty::Ref(_, inner_ty, _) => Some(*inner_ty),
1636 _ => None,
1637 };
1638
1639 typeck_results.expr_ty_adjusted_opt(expr).is_some_and(|expr_ty| {
1640 self.can_eq(obligation.param_env, expr_ty, old_self_ty)
1641 || inner_old_self_ty
1642 .is_some_and(|inner_ty| self.can_eq(obligation.param_env, expr_ty, inner_ty))
1643 })
1644 }
1645
1646 pub(super) fn suggest_add_reference_to_arg(
1647 &self,
1648 obligation: &PredicateObligation<'tcx>,
1649 err: &mut Diag<'_>,
1650 poly_trait_pred: ty::PolyTraitClause<'tcx>,
1651 has_custom_message: bool,
1652 ) -> bool {
1653 let span = obligation.cause.span;
1654 let param_env = obligation.param_env;
1655
1656 let mk_result = |trait_pred_and_new_ty| {
1657 let obligation =
1658 self.mk_trait_obligation_with_new_self_ty(param_env, trait_pred_and_new_ty);
1659 self.predicate_must_hold_modulo_regions(&obligation)
1660 };
1661
1662 let trait_pred_and_imm_ref = poly_trait_pred.map_bound(|p| {
1663 (p, Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_static, p.self_ty()))
1664 });
1665 let trait_pred_and_mut_ref = poly_trait_pred.map_bound(|p| {
1666 (p, Ty::new_mut_ref(self.tcx, self.tcx.lifetimes.re_static, p.self_ty()))
1667 });
1668
1669 let imm_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_imm_ref);
1670 let mut_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_mut_ref);
1671
1672 let mut point_at_relevant_args =
1673 |pred_ty: Ty<'tcx>, args_and_inputs: Vec<(hir::Expr<'_>, Ty<'tcx>)>| {
1674 let Some(typeck_results) = &self.typeck_results else { return false };
1675
1676 let erased_self_ty =
1677 self.tcx.instantiate_bound_regions_with_erased(poly_trait_pred.self_ty());
1678 let mut spans = ::alloc::vec::Vec::new()vec![];
1679 for (arg, input) in args_and_inputs {
1680 let Some(arg_ty) = typeck_results.expr_ty_adjusted_opt(&arg) else { continue };
1681 let pred_has_arg_type = self.infcx.can_eq(param_env, arg_ty, erased_self_ty);
1682 let arg_is_type_param = self.infcx.can_eq(param_env, pred_ty, input);
1683 if pred_has_arg_type && arg_is_type_param {
1684 err.span_label(
1685 arg.span,
1686 ::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"),
1687 );
1688 spans.push(arg.span);
1689 }
1690 }
1691 let this = if spans.len() == 1 { "this" } else { "these" }pluralize!("this", spans.len());
1692 if !spans.is_empty() {
1693 if imm_ref_self_ty_satisfies_pred {
1694 err.multipart_suggestion(
1695 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider borrowing {0} argument",
this))
})format!("consider borrowing {this} argument"),
1696 spans.iter().map(|sp| (sp.shrink_to_lo(), "&".into())).collect(),
1697 Applicability::MaybeIncorrect,
1698 );
1699 }
1700 if mut_ref_self_ty_satisfies_pred {
1701 err.multipart_suggestion(
1702 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider mutably borrowing {0} argument",
this))
})format!("consider mutably borrowing {this} argument"),
1703 spans.iter().map(|sp| (sp.shrink_to_lo(), "&mut ".into())).collect(),
1704 Applicability::MaybeIncorrect,
1705 );
1706 }
1707 }
1708 !spans.is_empty()
1709 };
1710 let code = match obligation.cause.code() {
1711 ObligationCauseCode::FunctionArg { parent_code, .. } => parent_code,
1712 c @ ObligationCauseCode::WhereClauseInExpr(def_id, _, hir_id, idx)
1715 if self.tcx.hir_span(*hir_id).lo() == span.lo() =>
1716 {
1717 if let hir::Node::Expr(expr) = self.tcx.parent_hir_node(*hir_id) {
1719 if let hir::ExprKind::Call(base, _) = expr.kind
1722 && let hir::ExprKind::Path(hir::QPath::TypeRelative(ty, segment)) =
1723 base.kind
1724 && let hir::Node::Expr(outer) = self.tcx.parent_hir_node(expr.hir_id)
1725 && let hir::ExprKind::AddrOf(hir::BorrowKind::Ref, mtbl, _) = outer.kind
1726 && ty.span == span
1727 {
1728 let sugg_msg = |pre: &str| {
1734 ::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!(
1735 "you likely meant to call the associated function `{FN}` for type \
1736 `&{pre}{TY}`, but the code as written calls associated function `{FN}` on \
1737 type `{TY}`",
1738 FN = segment.ident,
1739 TY = poly_trait_pred.self_ty(),
1740 )
1741 };
1742 match (imm_ref_self_ty_satisfies_pred, mut_ref_self_ty_satisfies_pred, mtbl)
1743 {
1744 (true, _, hir::Mutability::Not) | (_, true, hir::Mutability::Mut) => {
1745 err.multipart_suggestion(
1746 sugg_msg(mtbl.prefix_str()),
1747 ::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![
1748 (outer.span.shrink_to_lo(), "<".to_string()),
1749 (span.shrink_to_hi(), ">".to_string()),
1750 ],
1751 Applicability::MachineApplicable,
1752 );
1753 }
1754 (true, _, hir::Mutability::Mut) => {
1755 err.multipart_suggestion(
1757 sugg_msg("mut "),
1758 ::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![
1759 (outer.span.shrink_to_lo().until(span), "<&".to_string()),
1760 (span.shrink_to_hi(), ">".to_string()),
1761 ],
1762 Applicability::MachineApplicable,
1763 );
1764 }
1765 (_, true, hir::Mutability::Not) => {
1766 err.multipart_suggestion(
1767 sugg_msg(""),
1768 ::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![
1769 (
1770 outer.span.shrink_to_lo().until(span),
1771 "<&mut ".to_string(),
1772 ),
1773 (span.shrink_to_hi(), ">".to_string()),
1774 ],
1775 Applicability::MachineApplicable,
1776 );
1777 }
1778 _ => {}
1779 }
1780 return false;
1782 } else if let hir::ExprKind::Call(_, args) = expr.kind {
1783 if #[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(*def_id) {
DefKind::AssocFn | DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) => true,
_ => false,
}matches!(
1785 self.tcx.def_kind(*def_id),
1786 DefKind::AssocFn | DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn)
1787 ) && let Some(pred) = self
1788 .tcx
1789 .clauses_of(*def_id)
1790 .instantiate_identity(self.tcx)
1791 .clauses
1792 .into_iter()
1793 .nth(*idx)
1794 && let Some(pred) = pred.as_trait_clause()
1795 && !self.tcx.features().non_lifetime_binders()
1798 {
1799 let pred_ty = self.tcx.instantiate_bound_regions_with_erased(
1800 pred.self_ty().skip_norm_wip(),
1801 );
1802 let fn_sig = self.tcx.instantiate_bound_regions_with_erased(
1803 self.tcx.fn_sig(*def_id).instantiate_identity().skip_norm_wip(),
1804 );
1805 if point_at_relevant_args(
1806 pred_ty,
1807 args.into_iter()
1808 .zip(fn_sig.inputs())
1809 .map(|(e, t)| (*e, *t))
1810 .collect(),
1811 ) {
1812 return false;
1813 }
1814 }
1815 }
1816 }
1817 c
1818 }
1819 c @ ObligationCauseCode::WhereClauseInExpr(def_id, _, hir_id, idx)
1820 if let hir::Node::Expr(expr) = self.tcx.hir_node(*hir_id)
1821 && let hir::ExprKind::MethodCall(_segment, rcvr, args, ..) = expr.kind
1822 && #[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(*def_id) {
DefKind::AssocFn | DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) => true,
_ => false,
}matches!(
1824 self.tcx.def_kind(*def_id),
1825 DefKind::AssocFn | DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn)
1826 )
1827 && let Some(pred) = self
1828 .tcx
1829 .clauses_of(*def_id)
1830 .instantiate_identity(self.tcx)
1831 .clauses
1832 .into_iter()
1833 .nth(*idx)
1834 && let Some(pred) = pred.as_trait_clause()
1835 && !self.tcx.features().non_lifetime_binders() =>
1838 {
1839 let fn_sig = self.tcx.instantiate_bound_regions_with_erased(
1840 self.tcx.fn_sig(*def_id).instantiate_identity().skip_norm_wip(),
1841 );
1842 let pred_ty =
1844 self.tcx.instantiate_bound_regions_with_erased(pred.self_ty().skip_norm_wip());
1845 if point_at_relevant_args(
1846 pred_ty,
1847 [rcvr]
1848 .into_iter()
1849 .chain(args.into_iter())
1850 .zip(fn_sig.inputs())
1851 .map(|(e, t)| (*e, *t))
1852 .collect(),
1853 ) {
1854 return false;
1855 }
1856 c
1857 }
1858 c if #[allow(non_exhaustive_omitted_patterns)] match span.ctxt().outer_expn_data().kind
{
ExpnKind::Desugaring(DesugaringKind::ForLoop) => true,
_ => false,
}matches!(
1859 span.ctxt().outer_expn_data().kind,
1860 ExpnKind::Desugaring(DesugaringKind::ForLoop)
1861 ) =>
1862 {
1863 c
1864 }
1865 _ => return false,
1866 };
1867
1868 let mut never_suggest_borrow: Vec<_> =
1872 [LangItem::Copy, LangItem::Clone, LangItem::Unpin, LangItem::Sized]
1873 .iter()
1874 .filter_map(|lang_item| self.tcx.lang_items().get(*lang_item))
1875 .collect();
1876
1877 if let Some(def_id) = self.tcx.get_diagnostic_item(sym::Send) {
1878 never_suggest_borrow.push(def_id);
1879 }
1880
1881 let mut try_borrowing = |old_pred: ty::PolyTraitClause<'tcx>,
1883 blacklist: &[DefId]|
1884 -> bool {
1885 if blacklist.contains(&old_pred.def_id()) {
1886 return false;
1887 }
1888 let trait_pred_and_imm_ref = old_pred.map_bound(|trait_pred| {
1890 (
1891 trait_pred,
1892 Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1893 )
1894 });
1895 let trait_pred_and_mut_ref = old_pred.map_bound(|trait_pred| {
1896 (
1897 trait_pred,
1898 Ty::new_mut_ref(self.tcx, self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1899 )
1900 });
1901
1902 let imm_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_imm_ref);
1903 let mut_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_mut_ref);
1904
1905 let (ref_inner_ty_satisfies_pred, ref_inner_ty_is_mut) =
1906 if let ObligationCauseCode::WhereClauseInExpr(..) = obligation.cause.code()
1907 && let ty::Ref(_, ty, mutability) = old_pred.self_ty().skip_binder().kind()
1908 {
1909 (
1910 mk_result(old_pred.map_bound(|trait_pred| (trait_pred, *ty))),
1911 mutability.is_mut(),
1912 )
1913 } else {
1914 (false, false)
1915 };
1916
1917 let is_immut = imm_ref_self_ty_satisfies_pred
1918 || (ref_inner_ty_satisfies_pred && !ref_inner_ty_is_mut);
1919 let is_mut = mut_ref_self_ty_satisfies_pred || ref_inner_ty_is_mut;
1920 if !is_immut && !is_mut {
1921 return false;
1922 }
1923 let Ok(_snippet) = self.tcx.sess.source_map().span_to_snippet(span) else {
1924 return false;
1925 };
1926 if !#[allow(non_exhaustive_omitted_patterns)] match span.ctxt().outer_expn_data().kind
{
ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop) => true,
_ => false,
}matches!(
1934 span.ctxt().outer_expn_data().kind,
1935 ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop)
1936 ) {
1937 return false;
1938 }
1939 let mut label = || {
1946 let is_sized = match obligation.predicate.kind().skip_binder() {
1949 ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred)) => {
1950 self.tcx.is_lang_item(trait_pred.def_id(), LangItem::Sized)
1951 }
1952 _ => false,
1953 };
1954
1955 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!(
1956 "the trait bound `{}` is not satisfied",
1957 self.tcx.short_string(old_pred, err.long_ty_path()),
1958 );
1959 let self_ty_str = self.tcx.short_string(old_pred.self_ty(), err.long_ty_path());
1960 let trait_path = self
1961 .tcx
1962 .short_string(old_pred.print_modifiers_and_trait_path(), err.long_ty_path());
1963
1964 if has_custom_message {
1965 let msg = if is_sized {
1966 "the trait bound `Sized` is not satisfied".into()
1967 } else {
1968 msg
1969 };
1970 err.note(msg);
1971 } else {
1972 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)];
1973 }
1974 if is_sized {
1975 err.span_label(
1976 span,
1977 ::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}`"),
1978 );
1979 } else {
1980 err.span_label(
1981 span,
1982 ::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}`"),
1983 );
1984 }
1985 };
1986
1987 let mut sugg_prefixes = ::alloc::vec::Vec::new()vec![];
1988 if is_immut {
1989 sugg_prefixes.push("&");
1990 }
1991 if is_mut {
1992 sugg_prefixes.push("&mut ");
1993 }
1994 let sugg_msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider{0} borrowing here",
if is_mut && !is_immut { " mutably" } else { "" }))
})format!(
1995 "consider{} borrowing here",
1996 if is_mut && !is_immut { " mutably" } else { "" },
1997 );
1998
1999 let Some(body) = self.tcx.hir_maybe_body_owned_by(obligation.cause.body_def_id) else {
2003 return false;
2004 };
2005 let mut expr_finder = FindExprBySpan::new(span, self.tcx);
2006 expr_finder.visit_expr(body.value);
2007
2008 if let Some(ty) = expr_finder.ty_result {
2009 if let hir::Node::Expr(expr) = self.tcx.parent_hir_node(ty.hir_id)
2010 && let hir::ExprKind::Path(hir::QPath::TypeRelative(_, _)) = expr.kind
2011 && ty.span == span
2012 {
2013 label();
2016 err.multipart_suggestions(
2017 sugg_msg,
2018 sugg_prefixes.into_iter().map(|sugg_prefix| {
2019 ::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![
2020 (span.shrink_to_lo(), format!("<{sugg_prefix}")),
2021 (span.shrink_to_hi(), ">".to_string()),
2022 ]
2023 }),
2024 Applicability::MaybeIncorrect,
2025 );
2026 return true;
2027 }
2028 return false;
2029 }
2030 let Some(expr) = expr_finder.result else {
2031 return false;
2032 };
2033 if let hir::ExprKind::AddrOf(_, _, _) = expr.kind {
2034 return false;
2035 }
2036 let old_self_ty = old_pred.skip_binder().self_ty();
2037 if !old_self_ty.has_escaping_bound_vars()
2038 && !self.where_clause_expr_matches_failed_self_ty(
2039 obligation,
2040 self.tcx.instantiate_bound_regions_with_erased(old_pred.self_ty()),
2041 )
2042 {
2043 return false;
2044 }
2045 let needs_parens_post = expr_needs_parens(expr);
2046 let needs_parens_pre = match self.tcx.parent_hir_node(expr.hir_id) {
2047 Node::Expr(e)
2048 if let hir::ExprKind::MethodCall(_, base, _, _) = e.kind
2049 && base.hir_id == expr.hir_id =>
2050 {
2051 true
2052 }
2053 _ => false,
2054 };
2055
2056 label();
2057 let suggestions = sugg_prefixes.into_iter().map(|sugg_prefix| {
2058 match (needs_parens_pre, needs_parens_post) {
2059 (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())],
2060 (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![
2063 (span.shrink_to_lo(), format!("{sugg_prefix}(")),
2064 (span.shrink_to_hi(), ")".to_string()),
2065 ],
2066 (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![
2069 (span.shrink_to_lo(), format!("({sugg_prefix}")),
2070 (span.shrink_to_hi(), ")".to_string()),
2071 ],
2072 (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![
2073 (span.shrink_to_lo(), format!("({sugg_prefix}(")),
2074 (span.shrink_to_hi(), "))".to_string()),
2075 ],
2076 }
2077 });
2078 err.multipart_suggestions(sugg_msg, suggestions, Applicability::MaybeIncorrect);
2079 return true;
2080 };
2081
2082 if let ObligationCauseCode::ImplDerived(cause) = &*code {
2083 try_borrowing(cause.derived.parent_trait_pred, &[])
2084 } else if let ObligationCauseCode::WhereClause(..)
2085 | ObligationCauseCode::WhereClauseInExpr(..) = code
2086 {
2087 try_borrowing(poly_trait_pred, &never_suggest_borrow)
2088 } else {
2089 false
2090 }
2091 }
2092
2093 pub(super) fn suggest_borrowing_for_object_cast(
2095 &self,
2096 err: &mut Diag<'_>,
2097 obligation: &PredicateObligation<'tcx>,
2098 self_ty: Ty<'tcx>,
2099 target_ty: Ty<'tcx>,
2100 ) {
2101 let ty::Ref(_, object_ty, hir::Mutability::Not) = target_ty.kind() else {
2102 return;
2103 };
2104 let ty::Dynamic(predicates, _) = object_ty.kind() else {
2105 return;
2106 };
2107 let self_ref_ty = Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_erased, self_ty);
2108
2109 for predicate in predicates.iter() {
2110 if !self.predicate_must_hold_modulo_regions(
2111 &obligation.with(self.tcx, predicate.with_self_ty(self.tcx, self_ref_ty)),
2112 ) {
2113 return;
2114 }
2115 }
2116
2117 err.span_suggestion_verbose(
2118 obligation.cause.span.shrink_to_lo(),
2119 ::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!(
2120 "consider borrowing the value, since `&{self_ty}` can be coerced into `{target_ty}`"
2121 ),
2122 "&",
2123 Applicability::MaybeIncorrect,
2124 );
2125 }
2126
2127 fn peel_expr_refs(
2132 &self,
2133 mut expr: &'tcx hir::Expr<'tcx>,
2134 mut ty: Ty<'tcx>,
2135 ) -> (Vec<PeeledRef<'tcx>>, Option<&'tcx hir::Param<'tcx>>) {
2136 let mut refs = Vec::new();
2137 'outer: loop {
2138 while let hir::ExprKind::AddrOf(_, _, borrowed) = expr.kind {
2139 let span =
2140 if let Some(borrowed_span) = borrowed.span.find_ancestor_inside(expr.span) {
2141 expr.span.until(borrowed_span)
2142 } else {
2143 break 'outer;
2144 };
2145
2146 let span = match self.tcx.sess.source_map().span_to_snippet(span) {
2152 Ok(ref snippet) if snippet.starts_with("&") => span,
2153 Ok(ref snippet) if let Some(amp) = snippet.find('&') => {
2154 span.with_lo(span.lo() + BytePos(amp as u32))
2155 }
2156 _ => break 'outer,
2157 };
2158
2159 let ty::Ref(_, inner_ty, _) = ty.kind() else {
2160 break 'outer;
2161 };
2162 ty = *inner_ty;
2163 refs.push(PeeledRef { span, peeled_ty: ty });
2164 expr = borrowed;
2165 }
2166 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
2167 && let Res::Local(hir_id) = path.res
2168 && let hir::Node::Pat(binding) = self.tcx.hir_node(hir_id)
2169 {
2170 match self.tcx.parent_hir_node(binding.hir_id) {
2171 hir::Node::LetStmt(local)
2173 if local.ty.is_none()
2174 && let Some(init) = local.init =>
2175 {
2176 expr = init;
2177 continue;
2178 }
2179 hir::Node::LetStmt(local)
2182 if #[allow(non_exhaustive_omitted_patterns)] match local.source {
hir::LocalSource::AsyncFn => true,
_ => false,
}matches!(local.source, hir::LocalSource::AsyncFn)
2183 && let Some(init) = local.init
2184 && let hir::ExprKind::Path(hir::QPath::Resolved(None, arg_path)) =
2185 init.kind
2186 && let Res::Local(arg_hir_id) = arg_path.res
2187 && let hir::Node::Pat(arg_binding) = self.tcx.hir_node(arg_hir_id)
2188 && let hir::Node::Param(param) =
2189 self.tcx.parent_hir_node(arg_binding.hir_id) =>
2190 {
2191 return (refs, Some(param));
2192 }
2193 hir::Node::Param(param) => {
2195 return (refs, Some(param));
2196 }
2197 _ => break 'outer,
2198 }
2199 } else {
2200 break 'outer;
2201 }
2202 }
2203 (refs, None)
2204 }
2205
2206 pub(super) fn suggest_remove_reference(
2209 &self,
2210 obligation: &PredicateObligation<'tcx>,
2211 err: &mut Diag<'_>,
2212 trait_pred: ty::PolyTraitClause<'tcx>,
2213 ) -> bool {
2214 let mut span = obligation.cause.span;
2215 let mut trait_pred = trait_pred;
2216 let mut code = obligation.cause.code();
2217 while let Some((c, Some(parent_trait_pred))) = code.parent_with_predicate() {
2218 code = c;
2221 trait_pred = parent_trait_pred;
2222 }
2223 while span.desugaring_kind().is_some() {
2224 span.remove_mark();
2226 }
2227 let mut expr_finder = super::FindExprBySpan::new(span, self.tcx);
2228 let Some(body) = self.tcx.hir_maybe_body_owned_by(obligation.cause.body_def_id) else {
2229 return false;
2230 };
2231 expr_finder.visit_expr(body.value);
2232 let mut maybe_suggest = |suggested_ty, count, suggestions| {
2233 let trait_pred_and_suggested_ty =
2235 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
2236
2237 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
2238 obligation.param_env,
2239 trait_pred_and_suggested_ty,
2240 );
2241
2242 if self.predicate_may_hold(&new_obligation) {
2243 let msg = if count == 1 {
2244 "consider removing the leading `&`-reference".to_string()
2245 } else {
2246 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider removing {0} leading `&`-references",
count))
})format!("consider removing {count} leading `&`-references")
2247 };
2248
2249 err.multipart_suggestion(msg, suggestions, Applicability::MachineApplicable);
2250 true
2251 } else {
2252 false
2253 }
2254 };
2255
2256 let mut count = 0;
2259 let mut suggestions = ::alloc::vec::Vec::new()vec![];
2260 let mut suggested_ty = trait_pred.self_ty().skip_binder();
2262 if let Some(mut hir_ty) = expr_finder.ty_result {
2263 while let hir::TyKind::Ref(_, mut_ty) = &hir_ty.kind {
2264 count += 1;
2265 let span = hir_ty.span.until(mut_ty.ty.span);
2266 suggestions.push((span, String::new()));
2267
2268 let ty::Ref(_, inner_ty, _) = suggested_ty.kind() else {
2269 break;
2270 };
2271 suggested_ty = *inner_ty;
2272
2273 hir_ty = mut_ty.ty;
2274
2275 if maybe_suggest(suggested_ty, count, suggestions.clone()) {
2276 return true;
2277 }
2278 }
2279 }
2280
2281 let Some(expr) = expr_finder.result else {
2283 return false;
2284 };
2285 let suggested_ty = trait_pred.self_ty().skip_binder();
2287 let (peeled_refs, _) = self.peel_expr_refs(expr, suggested_ty);
2288 for (i, peeled) in peeled_refs.iter().enumerate() {
2289 let suggestions: Vec<_> =
2290 peeled_refs[..=i].iter().map(|r| (r.span, String::new())).collect();
2291 if maybe_suggest(peeled.peeled_ty, i + 1, suggestions) {
2292 return true;
2293 }
2294 }
2295 false
2296 }
2297
2298 fn suggest_remove_ref_from_param(&self, param: &hir::Param<'_>, err: &mut Diag<'_>) -> bool {
2300 if let Some(decl) = self.tcx.parent_hir_node(param.hir_id).fn_decl()
2301 && let Some(input_ty) = decl.inputs.iter().find(|t| param.ty_span.contains(t.span))
2302 && let hir::TyKind::Ref(_, mut_ty) = input_ty.kind
2303 {
2304 let ref_span = input_ty.span.until(mut_ty.ty.span);
2305 match self.tcx.sess.source_map().span_to_snippet(ref_span) {
2306 Ok(snippet) if snippet.starts_with("&") => {
2307 err.span_suggestion_verbose(
2308 ref_span,
2309 "consider removing the `&` from the parameter type",
2310 "",
2311 Applicability::MaybeIncorrect,
2312 );
2313 return true;
2314 }
2315 _ => {}
2316 }
2317 }
2318 false
2319 }
2320
2321 pub(super) fn suggest_remove_await(
2322 &self,
2323 obligation: &PredicateObligation<'tcx>,
2324 err: &mut Diag<'_>,
2325 ) {
2326 if let ObligationCauseCode::AwaitableExpr(hir_id) = obligation.cause.code().peel_derives()
2327 && let hir::Node::Expr(expr) = self.tcx.hir_node(*hir_id)
2328 {
2329 if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
2337 obligation.predicate.kind().skip_binder()
2338 {
2339 let self_ty = pred.self_ty();
2340 let future_trait =
2341 self.tcx.require_lang_item(LangItem::Future, obligation.cause.span);
2342
2343 let has_future = {
2345 let mut ty = self_ty;
2346 loop {
2347 match *ty.kind() {
2348 ty::Ref(_, inner_ty, _)
2349 if !#[allow(non_exhaustive_omitted_patterns)] match inner_ty.kind() {
ty::Dynamic(..) => true,
_ => false,
}matches!(inner_ty.kind(), ty::Dynamic(..)) =>
2350 {
2351 if self
2352 .type_implements_trait(
2353 future_trait,
2354 [inner_ty],
2355 obligation.param_env,
2356 )
2357 .must_apply_modulo_regions()
2358 {
2359 break true;
2360 }
2361 ty = inner_ty;
2362 }
2363 _ => break false,
2364 }
2365 }
2366 };
2367
2368 if has_future {
2369 let (peeled_refs, terminal_param) = self.peel_expr_refs(expr, self_ty);
2370
2371 for (i, peeled) in peeled_refs.iter().enumerate() {
2373 if self
2374 .type_implements_trait(
2375 future_trait,
2376 [peeled.peeled_ty],
2377 obligation.param_env,
2378 )
2379 .must_apply_modulo_regions()
2380 {
2381 let count = i + 1;
2382 let msg = if count == 1 {
2383 "consider removing the leading `&`-reference".to_string()
2384 } else {
2385 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider removing {0} leading `&`-references",
count))
})format!("consider removing {count} leading `&`-references")
2386 };
2387 let suggestions: Vec<_> =
2388 peeled_refs[..=i].iter().map(|r| (r.span, String::new())).collect();
2389 err.multipart_suggestion(
2390 msg,
2391 suggestions,
2392 Applicability::MachineApplicable,
2393 );
2394 return;
2395 }
2396 }
2397
2398 if peeled_refs.is_empty()
2402 && let Some(param) = terminal_param
2403 && self.suggest_remove_ref_from_param(param, err)
2404 {
2405 return;
2406 }
2407
2408 err.help(
2410 "a reference to a future is not a future; \
2411 consider removing the leading `&`-reference",
2412 );
2413 return;
2414 }
2415 }
2416
2417 if let Some((_, hir::Node::Expr(await_expr))) = self.tcx.hir_parent_iter(*hir_id).nth(1)
2419 && let Some(expr_span) = expr.span.find_ancestor_inside_same_ctxt(await_expr.span)
2420 {
2421 let removal_span = self
2422 .tcx
2423 .sess
2424 .source_map()
2425 .span_extend_while_whitespace(expr_span)
2426 .shrink_to_hi()
2427 .to(await_expr.span.shrink_to_hi());
2428 err.span_suggestion_verbose(
2429 removal_span,
2430 "remove the `.await`",
2431 "",
2432 Applicability::MachineApplicable,
2433 );
2434 } else {
2435 err.span_label(obligation.cause.span, "remove the `.await`");
2436 }
2437 if let hir::Expr { span, kind: hir::ExprKind::Call(base, _), .. } = expr {
2439 if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
2440 obligation.predicate.kind().skip_binder()
2441 {
2442 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()));
2443 }
2444 if let Some(typeck_results) = &self.typeck_results
2445 && let ty = typeck_results.expr_ty_adjusted(base)
2446 && let ty::FnDef(def_id, _args) = ty.kind()
2447 && let Some(hir::Node::Item(item)) = self.tcx.hir_get_if_local(*def_id)
2448 {
2449 let (ident, _, _, _) = item.expect_fn();
2450 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");
2451 if item.vis_span.is_empty() {
2452 err.span_suggestion_verbose(
2453 item.span.shrink_to_lo(),
2454 msg,
2455 "async ",
2456 Applicability::MaybeIncorrect,
2457 );
2458 } else {
2459 err.span_suggestion_verbose(
2460 item.vis_span.shrink_to_hi(),
2461 msg,
2462 " async",
2463 Applicability::MaybeIncorrect,
2464 );
2465 }
2466 }
2467 }
2468 }
2469 }
2470
2471 pub(super) fn suggest_change_mut(
2474 &self,
2475 obligation: &PredicateObligation<'tcx>,
2476 err: &mut Diag<'_>,
2477 trait_pred: ty::PolyTraitClause<'tcx>,
2478 ) {
2479 let points_at_arg =
2480 #[allow(non_exhaustive_omitted_patterns)] match obligation.cause.code() {
ObligationCauseCode::FunctionArg { .. } => true,
_ => false,
}matches!(obligation.cause.code(), ObligationCauseCode::FunctionArg { .. },);
2481
2482 let span = obligation.cause.span;
2483 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
2484 let refs_number =
2485 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
2486 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
2487 return;
2489 }
2490 let trait_pred = self.resolve_vars_if_possible(trait_pred);
2491 if trait_pred.has_non_region_infer() {
2492 return;
2495 }
2496
2497 if let ty::Ref(region, t_type, mutability) = *trait_pred.skip_binder().self_ty().kind()
2499 {
2500 let suggested_ty = match mutability {
2501 hir::Mutability::Mut => Ty::new_imm_ref(self.tcx, region, t_type),
2502 hir::Mutability::Not => Ty::new_mut_ref(self.tcx, region, t_type),
2503 };
2504
2505 let trait_pred_and_suggested_ty =
2507 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
2508
2509 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
2510 obligation.param_env,
2511 trait_pred_and_suggested_ty,
2512 );
2513 let suggested_ty_would_satisfy_obligation = self
2514 .evaluate_obligation_no_overflow(&new_obligation)
2515 .must_apply_modulo_regions();
2516 if suggested_ty_would_satisfy_obligation {
2517 let sp = self
2518 .tcx
2519 .sess
2520 .source_map()
2521 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
2522 if points_at_arg && mutability.is_not() && refs_number > 0 {
2523 if snippet
2525 .trim_start_matches(|c: char| c.is_whitespace() || c == '&')
2526 .starts_with("mut")
2527 {
2528 return;
2529 }
2530 err.span_suggestion_verbose(
2531 sp,
2532 "consider changing this borrow's mutability",
2533 "&mut ",
2534 Applicability::MachineApplicable,
2535 );
2536 } else {
2537 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!(
2538 "`{}` is implemented for `{}`, but not for `{}`",
2539 trait_pred.print_modifiers_and_trait_path(),
2540 suggested_ty,
2541 trait_pred.skip_binder().self_ty(),
2542 ));
2543 }
2544 }
2545 }
2546 }
2547 }
2548
2549 pub(super) fn suggest_semicolon_removal(
2550 &self,
2551 obligation: &PredicateObligation<'tcx>,
2552 err: &mut Diag<'_>,
2553 span: Span,
2554 trait_pred: ty::PolyTraitClause<'tcx>,
2555 ) -> bool {
2556 if !trait_pred.self_ty().skip_binder().is_unit() {
2557 return false;
2558 }
2559 let node = self.tcx.hir_node_by_def_id(obligation.cause.body_def_id);
2560 if let hir::Node::Item(hir::Item {
2561 kind: hir::ItemKind::Fn { sig, body: body_id, .. }, ..
2562 }) = node
2563 && let hir::ExprKind::Block(blk, _) = &self.tcx.hir_body(*body_id).value.kind
2564 && sig.decl.output.span().overlaps(span)
2565 && let Some(candidate) = self.removable_trailing_semicolon(blk, obligation, trait_pred)
2566 {
2567 self.emit_semicolon_removal_suggestion(
2570 err,
2571 trait_pred,
2572 candidate,
2573 Applicability::MachineApplicable,
2574 );
2575 return true;
2576 }
2577 self.suggest_semicolon_removal_in_closure_arg(obligation, err, trait_pred)
2578 }
2579
2580 fn removable_trailing_semicolon(
2583 &self,
2584 block: &hir::Block<'tcx>,
2585 obligation: &PredicateObligation<'tcx>,
2586 trait_pred: ty::PolyTraitClause<'tcx>,
2587 ) -> Option<(&'tcx hir::Stmt<'tcx>, &'tcx hir::Expr<'tcx>, Ty<'tcx>)> {
2588 if block.expr.is_none()
2589 && let Some(stmt) = block.stmts.last()
2590 && let hir::StmtKind::Semi(expr) = stmt.kind
2591 && !stmt.span.from_expansion()
2592 && !#[allow(non_exhaustive_omitted_patterns)] match expr.kind {
hir::ExprKind::Err(_) => true,
_ => false,
}matches!(expr.kind, hir::ExprKind::Err(_))
2593 && let Some(typeck_results) = &self.typeck_results
2595 && let Some(ty) =
2596 typeck_results.expr_ty_opt(expr).map(|ty| self.resolve_vars_if_possible(ty))
2597 && self.predicate_may_hold(&self.mk_trait_obligation_with_new_self_ty(
2598 obligation.param_env, trait_pred.map_bound(|trait_pred| (trait_pred, ty))
2599 ))
2600 {
2601 Some((stmt, expr, ty))
2602 } else {
2603 None
2604 }
2605 }
2606
2607 fn emit_semicolon_removal_suggestion(
2608 &self,
2609 err: &mut Diag<'_>,
2610 trait_pred: ty::PolyTraitClause<'tcx>,
2611 (stmt, expr, ty): (&hir::Stmt<'_>, &hir::Expr<'_>, Ty<'tcx>),
2612 applicability: Applicability,
2613 ) {
2614 err.span_label(
2615 expr.span,
2616 ::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!(
2617 "this expression has type `{}`, which implements `{}`",
2618 ty,
2619 trait_pred.print_modifiers_and_trait_path()
2620 ),
2621 );
2622 err.span_suggestion(
2623 self.tcx.sess.source_map().end_point(stmt.span),
2624 "remove this semicolon",
2625 "",
2626 applicability,
2627 );
2628 }
2629
2630 fn suggest_semicolon_removal_in_closure_arg(
2639 &self,
2640 obligation: &PredicateObligation<'tcx>,
2641 err: &mut Diag<'_>,
2642 trait_pred: ty::PolyTraitClause<'tcx>,
2643 ) -> bool {
2644 let &ObligationCauseCode::WhereClauseInExpr(callee_def_id, _, hir_id, idx) =
2645 obligation.cause.code().peel_derives()
2646 else {
2647 return false;
2648 };
2649 if !#[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(callee_def_id)
{
DefKind::Fn | DefKind::AssocFn => true,
_ => false,
}matches!(self.tcx.def_kind(callee_def_id), DefKind::Fn | DefKind::AssocFn) {
2652 return false;
2653 }
2654 let hir::Node::Expr(expr) = self.tcx.hir_node(hir_id) else {
2655 return false;
2656 };
2657 let Some(typeck_results) = &self.typeck_results else {
2658 return false;
2659 };
2660 let args: Vec<&hir::Expr<'_>> =
2661 match expr.kind {
2662 hir::ExprKind::MethodCall(_, receiver, args, _) => {
2663 iter::once(receiver).chain(args).collect()
2664 }
2665 _ => match self.tcx.parent_hir_node(expr.hir_id) {
2668 hir::Node::Expr(hir::Expr {
2669 kind: hir::ExprKind::Call(callee, args), ..
2670 }) if callee.hir_id == expr.hir_id => args.iter().collect(),
2671 _ => return false,
2672 },
2673 };
2674 let clauses = self.tcx.clauses_of(callee_def_id).instantiate_identity(self.tcx);
2677 let Some(ty::ClauseKind::Trait(failed)) = clauses
2678 .clauses
2679 .get(idx)
2680 .map(|clause| clause.as_ref().skip_norm_wip().kind().skip_binder())
2681 else {
2682 return false;
2683 };
2684 let sig =
2685 self.tcx.fn_sig(callee_def_id).instantiate_identity().skip_norm_wip().skip_binder();
2686 let mut candidates = args.into_iter().enumerate().filter_map(|(i, arg)| {
2687 let declared = sig.inputs().get(i)?.peel_refs();
2690 if !clauses.clauses.iter().any(|clause| {
2691 #[allow(non_exhaustive_omitted_patterns)] match clause.as_ref().skip_norm_wip().kind().skip_binder()
{
ty::ClauseKind::Projection(proj) if
self.tcx.is_lang_item(proj.def_id(), LangItem::FnOnceOutput) &&
proj.projection_term.self_ty() == declared &&
proj.term.as_type() == Some(failed.self_ty()) => true,
_ => false,
}matches!(
2692 clause.as_ref().skip_norm_wip().kind().skip_binder(),
2693 ty::ClauseKind::Projection(proj)
2694 if self.tcx.is_lang_item(proj.def_id(), LangItem::FnOnceOutput)
2695 && proj.projection_term.self_ty() == declared
2696 && proj.term.as_type() == Some(failed.self_ty())
2697 )
2698 }) {
2699 return None;
2700 }
2701 let closure_def_id = match arg.kind {
2705 hir::ExprKind::Closure(closure) => closure.def_id,
2706 _ => match typeck_results
2707 .expr_ty_adjusted_opt(arg)
2708 .map(|ty| *self.resolve_vars_if_possible(ty).peel_refs().kind())
2709 {
2710 Some(ty::Closure(def_id, _)) => def_id.as_local()?,
2711 _ => return None,
2712 },
2713 };
2714 let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(closure), .. }) =
2715 self.tcx.hir_node_by_def_id(closure_def_id)
2716 else {
2717 return None;
2718 };
2719 let hir::ExprKind::Block(block, None) = self.tcx.hir_body(closure.body).value.kind
2720 else {
2721 return None;
2722 };
2723 self.removable_trailing_semicolon(block, obligation, trait_pred)
2724 });
2725 if let Some(candidate) = candidates.next()
2728 && candidates.next().is_none()
2729 {
2730 self.emit_semicolon_removal_suggestion(
2733 err,
2734 trait_pred,
2735 candidate,
2736 Applicability::MaybeIncorrect,
2737 );
2738 return true;
2739 }
2740 false
2741 }
2742
2743 pub(super) fn suggest_borrow_for_unsized_closure_return<G: EmissionGuarantee>(
2744 &self,
2745 body_def_id: LocalDefId,
2746 err: &mut Diag<'_, G>,
2747 predicate: ty::Predicate<'tcx>,
2748 ) {
2749 let Some(pred) = predicate.as_trait_clause() else {
2750 return;
2751 };
2752 if !self.tcx.is_lang_item(pred.def_id(), LangItem::Sized) {
2753 return;
2754 }
2755
2756 let Some(span) = err.span.primary_span() else {
2757 return;
2758 };
2759 let Some(body_id) = self.tcx.hir_node_by_def_id(body_def_id).body_id() else {
2760 return;
2761 };
2762 let body = self.tcx.hir_body(body_id);
2763 let mut expr_finder = FindExprBySpan::new(span, self.tcx);
2764 expr_finder.visit_expr(body.value);
2765 let Some(expr) = expr_finder.result else {
2766 return;
2767 };
2768
2769 let closure = match expr.kind {
2770 hir::ExprKind::Call(_, args) => args.iter().find_map(|arg| match arg.kind {
2771 hir::ExprKind::Closure(closure) => Some(closure),
2772 _ => None,
2773 }),
2774 hir::ExprKind::MethodCall(_, _, args, _) => {
2775 args.iter().find_map(|arg| match arg.kind {
2776 hir::ExprKind::Closure(closure) => Some(closure),
2777 _ => None,
2778 })
2779 }
2780 _ => None,
2781 };
2782 let Some(closure) = closure else {
2783 return;
2784 };
2785 if !#[allow(non_exhaustive_omitted_patterns)] match closure.fn_decl.output {
hir::FnRetTy::DefaultReturn(_) => true,
_ => false,
}matches!(closure.fn_decl.output, hir::FnRetTy::DefaultReturn(_)) {
2786 return;
2787 }
2788
2789 err.span_suggestion_verbose(
2790 self.tcx.hir_body(closure.body).value.span.shrink_to_lo(),
2791 "consider borrowing the value",
2792 "&",
2793 Applicability::MaybeIncorrect,
2794 );
2795 }
2796
2797 pub(super) fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span> {
2798 let hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn { sig, .. }, .. }) =
2799 self.tcx.hir_node_by_def_id(obligation.cause.body_def_id)
2800 else {
2801 return None;
2802 };
2803
2804 if let hir::FnRetTy::Return(ret_ty) = sig.decl.output { Some(ret_ty.span) } else { None }
2805 }
2806
2807 pub(super) fn suggest_impl_trait(
2811 &self,
2812 err: &mut Diag<'_>,
2813 obligation: &PredicateObligation<'tcx>,
2814 trait_pred: ty::PolyTraitClause<'tcx>,
2815 ) -> bool {
2816 let ObligationCauseCode::SizedReturnType = obligation.cause.code() else {
2817 return false;
2818 };
2819 let ty::Dynamic(_, _) = trait_pred.self_ty().skip_binder().kind() else {
2820 return false;
2821 };
2822 if let Node::Item(hir::Item { kind: hir::ItemKind::Fn { sig: fn_sig, .. }, .. })
2823 | Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(fn_sig, _), .. })
2824 | Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(fn_sig, _), .. }) =
2825 self.tcx.hir_node_by_def_id(obligation.cause.body_def_id)
2826 && let hir::FnRetTy::Return(ty) = fn_sig.decl.output
2827 && let hir::TyKind::Path(qpath) = ty.kind
2828 && let hir::QPath::Resolved(None, path) = qpath
2829 && let Res::Def(DefKind::TyAlias, def_id) = path.res
2830 {
2831 err.span_note(self.tcx.def_span(def_id), "this type alias is unsized");
2835 err.multipart_suggestion(
2836 ::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!(
2837 "consider boxing the return type, and wrapping all of the returned values in \
2838 `Box::new`",
2839 ),
2840 ::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![
2841 (ty.span.shrink_to_lo(), "Box<".to_string()),
2842 (ty.span.shrink_to_hi(), ">".to_string()),
2843 ],
2844 Applicability::MaybeIncorrect,
2845 );
2846 return false;
2847 }
2848
2849 err.code(E0746);
2850 err.primary_message("return type cannot be a trait object without pointer indirection");
2851 err.children.clear();
2852
2853 let mut span = obligation.cause.span;
2854 let mut is_async_fn_return = false;
2855 if let DefKind::Closure = self.tcx.def_kind(obligation.cause.body_def_id)
2856 && let parent = self.tcx.local_parent(obligation.cause.body_def_id)
2857 && let DefKind::Fn | DefKind::AssocFn = self.tcx.def_kind(parent)
2858 && self.tcx.asyncness(parent).is_async()
2859 && let Node::Item(hir::Item { kind: hir::ItemKind::Fn { sig: fn_sig, .. }, .. })
2860 | Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(fn_sig, _), .. })
2861 | Node::TraitItem(hir::TraitItem {
2862 kind: hir::TraitItemKind::Fn(fn_sig, _), ..
2863 }) = self.tcx.hir_node_by_def_id(parent)
2864 {
2865 span = fn_sig.decl.output.span();
2870 is_async_fn_return = true;
2871 err.span(span);
2872 }
2873 let body = self.tcx.hir_body_owned_by(obligation.cause.body_def_id);
2874
2875 if !is_async_fn_return
2876 && let Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(closure), .. }) =
2877 self.tcx.hir_node_by_def_id(obligation.cause.body_def_id)
2878 && #[allow(non_exhaustive_omitted_patterns)] match closure.fn_decl.output {
hir::FnRetTy::DefaultReturn(_) => true,
_ => false,
}matches!(closure.fn_decl.output, hir::FnRetTy::DefaultReturn(_))
2879 {
2880 return true;
2881 }
2882
2883 let mut visitor = ReturnsVisitor::default();
2884 visitor.visit_body(&body);
2885
2886 let (pre, impl_span) = if let Ok(snip) = self.tcx.sess.source_map().span_to_snippet(span)
2887 && snip.starts_with("dyn ")
2888 {
2889 ("", span.with_hi(span.lo() + BytePos(4)))
2890 } else {
2891 ("dyn ", span.shrink_to_lo())
2892 };
2893
2894 err.span_suggestion_verbose(
2895 impl_span,
2896 "consider returning an `impl Trait` instead of a `dyn Trait`",
2897 "impl ",
2898 Applicability::MaybeIncorrect,
2899 );
2900
2901 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![
2902 (span.shrink_to_lo(), format!("Box<{pre}")),
2903 (span.shrink_to_hi(), ">".to_string()),
2904 ];
2905 sugg.extend(visitor.returns.into_iter().flat_map(|expr| {
2906 let span =
2907 expr.span.find_ancestor_in_same_ctxt(obligation.cause.span).unwrap_or(expr.span);
2908 if !span.can_be_used_for_suggestions() {
2909 ::alloc::vec::Vec::new()vec![]
2910 } else if let hir::ExprKind::Call(path, ..) = expr.kind
2911 && let hir::ExprKind::Path(hir::QPath::TypeRelative(ty, method)) = path.kind
2912 && method.ident.name == sym::new
2913 && let hir::TyKind::Path(hir::QPath::Resolved(.., box_path)) = ty.kind
2914 && box_path
2915 .res
2916 .opt_def_id()
2917 .is_some_and(|def_id| self.tcx.is_lang_item(def_id, LangItem::OwnedBox))
2918 {
2919 ::alloc::vec::Vec::new()vec![]
2921 } else {
2922 ::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![
2923 (span.shrink_to_lo(), "Box::new(".to_string()),
2924 (span.shrink_to_hi(), ")".to_string()),
2925 ]
2926 }
2927 }));
2928
2929 err.multipart_suggestion(
2930 ::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!(
2931 "alternatively, box the return type, and wrap all of the returned values in \
2932 `Box::new`",
2933 ),
2934 sugg,
2935 Applicability::MaybeIncorrect,
2936 );
2937
2938 true
2939 }
2940
2941 pub(super) fn report_closure_arg_mismatch(
2942 &self,
2943 span: Span,
2944 found_span: Option<Span>,
2945 found: ty::TraitRef<'tcx>,
2946 expected: ty::TraitRef<'tcx>,
2947 cause: &ObligationCauseCode<'tcx>,
2948 found_node: Option<Node<'_>>,
2949 param_env: ty::ParamEnv<'tcx>,
2950 ) -> Diag<'a> {
2951 pub(crate) fn build_fn_sig_ty<'tcx>(
2952 infcx: &InferCtxt<'tcx>,
2953 trait_ref: ty::TraitRef<'tcx>,
2954 ) -> Ty<'tcx> {
2955 let inputs = trait_ref.args.type_at(1);
2956 let sig = match inputs.kind() {
2957 ty::Tuple(inputs) if infcx.tcx.is_callable_trait(trait_ref.def_id) => {
2958 infcx.tcx.mk_fn_sig_safe_rust_abi(*inputs, infcx.next_ty_var(DUMMY_SP))
2959 }
2960 _ => infcx.tcx.mk_fn_sig_safe_rust_abi([inputs], infcx.next_ty_var(DUMMY_SP)),
2961 };
2962
2963 Ty::new_fn_ptr(infcx.tcx, ty::Binder::dummy(sig))
2964 }
2965
2966 let argument_kind = match expected.self_ty().kind() {
2967 ty::Closure(..) => "closure",
2968 ty::Coroutine(..) => "coroutine",
2969 _ => "function",
2970 };
2971 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!(
2972 self.dcx(),
2973 span,
2974 E0631,
2975 "type mismatch in {argument_kind} arguments",
2976 );
2977
2978 err.span_label(span, "expected due to this");
2979
2980 let found_span = found_span.unwrap_or(span);
2981 err.span_label(found_span, "found signature defined here");
2982
2983 let expected = build_fn_sig_ty(self, expected);
2984 let found = build_fn_sig_ty(self, found);
2985
2986 let (expected_str, found_str) = self.cmp(expected, found);
2987
2988 let signature_kind = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} signature", argument_kind))
})format!("{argument_kind} signature");
2989 err.note_expected_found(&signature_kind, expected_str, &signature_kind, found_str);
2990
2991 self.note_conflicting_fn_args(&mut err, cause, expected, found, param_env);
2992 self.note_conflicting_closure_bounds(cause, &mut err);
2993
2994 if let Some(found_node) = found_node {
2995 hint_missing_borrow(self, param_env, span, found, expected, found_node, &mut err);
2996 }
2997
2998 err
2999 }
3000
3001 fn note_conflicting_fn_args(
3002 &self,
3003 err: &mut Diag<'_>,
3004 cause: &ObligationCauseCode<'tcx>,
3005 expected: Ty<'tcx>,
3006 found: Ty<'tcx>,
3007 param_env: ty::ParamEnv<'tcx>,
3008 ) {
3009 let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = cause else {
3010 return;
3011 };
3012 let ty::FnPtr(sig_tys, hdr) = expected.kind() else {
3013 return;
3014 };
3015 let expected = sig_tys.with(*hdr);
3016 let ty::FnPtr(sig_tys, hdr) = found.kind() else {
3017 return;
3018 };
3019 let found = sig_tys.with(*hdr);
3020 let Node::Expr(arg) = self.tcx.hir_node(*arg_hir_id) else {
3021 return;
3022 };
3023 let hir::ExprKind::Path(path) = arg.kind else {
3024 return;
3025 };
3026 let expected_inputs = self.tcx.instantiate_bound_regions_with_erased(expected).inputs();
3027 let found_inputs = self.tcx.instantiate_bound_regions_with_erased(found).inputs();
3028 let both_tys = expected_inputs.iter().copied().zip(found_inputs.iter().copied());
3029
3030 let arg_expr = |infcx: &InferCtxt<'tcx>, name, expected: Ty<'tcx>, found: Ty<'tcx>| {
3031 let (expected_ty, expected_refs) = get_deref_type_and_refs(expected);
3032 let (found_ty, found_refs) = get_deref_type_and_refs(found);
3033
3034 if infcx.can_eq(param_env, found_ty, expected_ty) {
3035 if found_refs.len() == expected_refs.len()
3036 && found_refs.iter().eq(expected_refs.iter())
3037 {
3038 name
3039 } else if found_refs.len() > expected_refs.len() {
3040 let refs = &found_refs[..found_refs.len() - expected_refs.len()];
3041 if found_refs[..expected_refs.len()].iter().eq(expected_refs.iter()) {
3042 ::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!(
3043 "{}{name}",
3044 refs.iter()
3045 .map(|mutbl| format!("&{}", mutbl.prefix_str()))
3046 .collect::<Vec<_>>()
3047 .join(""),
3048 )
3049 } else {
3050 ::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!(
3052 "{}*{name}",
3053 refs.iter()
3054 .map(|mutbl| format!("&{}", mutbl.prefix_str()))
3055 .collect::<Vec<_>>()
3056 .join(""),
3057 )
3058 }
3059 } else if expected_refs.len() > found_refs.len() {
3060 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}",
(0..(expected_refs.len() -
found_refs.len())).map(|_|
"*").collect::<Vec<_>>().join(""), name))
})format!(
3061 "{}{name}",
3062 (0..(expected_refs.len() - found_refs.len()))
3063 .map(|_| "*")
3064 .collect::<Vec<_>>()
3065 .join(""),
3066 )
3067 } else {
3068 ::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!(
3069 "{}{name}",
3070 found_refs
3071 .iter()
3072 .map(|mutbl| format!("&{}", mutbl.prefix_str()))
3073 .chain(found_refs.iter().map(|_| "*".to_string()))
3074 .collect::<Vec<_>>()
3075 .join(""),
3076 )
3077 }
3078 } else {
3079 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("/* {0} */", found))
})format!("/* {found} */")
3080 }
3081 };
3082 let args_have_same_underlying_type = both_tys.clone().all(|(expected, found)| {
3083 let (expected_ty, _) = get_deref_type_and_refs(expected);
3084 let (found_ty, _) = get_deref_type_and_refs(found);
3085 self.can_eq(param_env, found_ty, expected_ty)
3086 });
3087 let (closure_names, call_names): (Vec<_>, Vec<_>) = if args_have_same_underlying_type
3088 && !expected_inputs.is_empty()
3089 && expected_inputs.len() == found_inputs.len()
3090 && let Some(typeck) = &self.typeck_results
3091 && let Res::Def(res_kind, fn_def_id) = typeck.qpath_res(&path, *arg_hir_id)
3092 && res_kind.is_fn_like()
3093 {
3094 let closure: Vec<_> = self
3095 .tcx
3096 .fn_arg_idents(fn_def_id)
3097 .iter()
3098 .enumerate()
3099 .map(|(i, ident)| {
3100 if let Some(ident) = ident
3101 && !#[allow(non_exhaustive_omitted_patterns)] match ident {
Ident { name: kw::Underscore | kw::SelfLower, .. } => true,
_ => false,
}matches!(ident, Ident { name: kw::Underscore | kw::SelfLower, .. })
3102 {
3103 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", ident))
})format!("{ident}")
3104 } else {
3105 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("arg{0}", i))
})format!("arg{i}")
3106 }
3107 })
3108 .collect();
3109 let args = closure
3110 .iter()
3111 .zip(both_tys)
3112 .map(|(name, (expected, found))| {
3113 arg_expr(self.infcx, name.to_owned(), expected, found)
3114 })
3115 .collect();
3116 (closure, args)
3117 } else {
3118 let closure_args = expected_inputs
3119 .iter()
3120 .enumerate()
3121 .map(|(i, _)| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("arg{0}", i))
})format!("arg{i}"))
3122 .collect::<Vec<_>>();
3123 let call_args = both_tys
3124 .enumerate()
3125 .map(|(i, (expected, found))| {
3126 arg_expr(self.infcx, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("arg{0}", i))
})format!("arg{i}"), expected, found)
3127 })
3128 .collect::<Vec<_>>();
3129 (closure_args, call_args)
3130 };
3131 let closure_names: Vec<_> = closure_names
3132 .into_iter()
3133 .zip(expected_inputs.iter())
3134 .map(|(name, ty)| {
3135 ::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!(
3136 "{name}{}",
3137 if ty.has_infer_types() {
3138 String::new()
3139 } else if ty.references_error() {
3140 ": /* type */".to_string()
3141 } else {
3142 format!(": {ty}")
3143 }
3144 )
3145 })
3146 .collect();
3147 err.multipart_suggestion(
3148 "consider wrapping the function in a closure",
3149 ::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![
3150 (arg.span.shrink_to_lo(), format!("|{}| ", closure_names.join(", "))),
3151 (arg.span.shrink_to_hi(), format!("({})", call_names.join(", "))),
3152 ],
3153 Applicability::MaybeIncorrect,
3154 );
3155 }
3156
3157 fn note_conflicting_closure_bounds(
3160 &self,
3161 cause: &ObligationCauseCode<'tcx>,
3162 err: &mut Diag<'_>,
3163 ) {
3164 if let ObligationCauseCode::WhereClauseInExpr(def_id, _, _, idx) = *cause
3168 && let gen_clauses = self.tcx.clauses_of(def_id).instantiate_identity(self.tcx)
3169 && let Some(clause) = gen_clauses.clauses.get(idx).map(|c| c.as_ref().skip_norm_wip())
3170 && let ty::ClauseKind::Trait(trait_pred) = clause.kind().skip_binder()
3171 && self.tcx.is_fn_trait(trait_pred.def_id())
3172 {
3173 let expected_self =
3174 self.tcx.anonymize_bound_vars(clause.kind().rebind(trait_pred.self_ty()));
3175 let expected_args =
3176 self.tcx.anonymize_bound_vars(clause.kind().rebind(trait_pred.trait_ref.args));
3177
3178 let other_clause =
3181 gen_clauses.into_iter().enumerate().find(|&(other_idx, (clause, _))| {
3182 let clause = clause.skip_norm_wip();
3183 match clause.kind().skip_binder() {
3184 ty::ClauseKind::Trait(trait_pred)
3185 if self.tcx.is_fn_trait(trait_pred.def_id())
3186 && other_idx != idx
3187 && expected_self
3190 == self.tcx.anonymize_bound_vars(
3191 clause.kind().rebind(trait_pred.self_ty()),
3192 )
3193 && expected_args
3195 != self.tcx.anonymize_bound_vars(
3196 clause.kind().rebind(trait_pred.trait_ref.args),
3197 ) =>
3198 {
3199 true
3200 }
3201 _ => false,
3202 }
3203 });
3204 if let Some((_, (_, other_clause_span))) = other_clause {
3206 err.span_note(
3207 other_clause_span,
3208 "closure inferred to have a different signature due to this bound",
3209 );
3210 }
3211 }
3212 }
3213
3214 pub(super) fn suggest_fully_qualified_path(
3215 &self,
3216 err: &mut Diag<'_>,
3217 item_def_id: DefId,
3218 span: Span,
3219 trait_ref: DefId,
3220 ) {
3221 if let Some(assoc_item) = self.tcx.opt_associated_item(item_def_id)
3222 && let ty::AssocKind::Const { .. } | ty::AssocKind::Type { .. } = assoc_item.kind
3223 {
3224 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!(
3225 "{}s cannot be accessed directly on a `trait`, they can only be \
3226 accessed through a specific `impl`",
3227 self.tcx.def_kind_descr(assoc_item.as_def_kind(), item_def_id)
3228 ));
3229
3230 if !assoc_item.is_impl_trait_in_trait() {
3231 err.span_suggestion_verbose(
3232 span,
3233 "use the fully qualified path to an implementation",
3234 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<Type as {0}>::{1}",
self.tcx.def_path_str(trait_ref), assoc_item.name()))
})format!(
3235 "<Type as {}>::{}",
3236 self.tcx.def_path_str(trait_ref),
3237 assoc_item.name()
3238 ),
3239 Applicability::HasPlaceholders,
3240 );
3241 }
3242 }
3243 }
3244
3245 {}
#[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("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3287u32),
::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 /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3326",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3326u32),
::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 /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3333",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3333u32),
::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 /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3363",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3363u32),
::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 /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3394",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3394u32),
::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 /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3404",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3404u32),
::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 /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3417",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3417u32),
::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 /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3438",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3438u32),
::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 /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3462",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3462u32),
::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 /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3470",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3470u32),
::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 /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3474",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3474u32),
::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 /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3477",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3477u32),
::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 /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3498",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3498u32),
::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))]
3288 pub fn maybe_note_obligation_cause_for_async_await<G: EmissionGuarantee>(
3289 &self,
3290 err: &mut Diag<'_, G>,
3291 obligation: &PredicateObligation<'tcx>,
3292 ) -> bool {
3293 let (mut trait_ref, mut target_ty) = match obligation.predicate.kind().skip_binder() {
3316 ty::PredicateKind::Clause(ty::ClauseKind::Trait(p)) => (Some(p), Some(p.self_ty())),
3317 _ => (None, None),
3318 };
3319 let mut coroutine = None;
3320 let mut outer_coroutine = None;
3321 let mut next_code = Some(obligation.cause.code());
3322
3323 let mut seen_upvar_tys_infer_tuple = false;
3324
3325 while let Some(code) = next_code {
3326 debug!(?code);
3327 match code {
3328 ObligationCauseCode::FunctionArg { parent_code, .. } => {
3329 next_code = Some(parent_code);
3330 }
3331 ObligationCauseCode::ImplDerived(cause) => {
3332 let ty = cause.derived.parent_trait_pred.skip_binder().self_ty();
3333 debug!(
3334 parent_trait_ref = ?cause.derived.parent_trait_pred,
3335 self_ty.kind = ?ty.kind(),
3336 "ImplDerived",
3337 );
3338
3339 match *ty.kind() {
3340 ty::Coroutine(did, ..) | ty::CoroutineWitness(did, _) => {
3341 coroutine = coroutine.or(Some(did));
3342 outer_coroutine = Some(did);
3343 }
3344 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
3345 seen_upvar_tys_infer_tuple = true;
3350 }
3351 _ if coroutine.is_none() => {
3352 trait_ref = Some(cause.derived.parent_trait_pred.skip_binder());
3353 target_ty = Some(ty);
3354 }
3355 _ => {}
3356 }
3357
3358 next_code = Some(&cause.derived.parent_code);
3359 }
3360 ObligationCauseCode::WellFormedDerived(derived_obligation)
3361 | ObligationCauseCode::BuiltinDerived(derived_obligation) => {
3362 let ty = derived_obligation.parent_trait_pred.skip_binder().self_ty();
3363 debug!(
3364 parent_trait_ref = ?derived_obligation.parent_trait_pred,
3365 self_ty.kind = ?ty.kind(),
3366 );
3367
3368 match *ty.kind() {
3369 ty::Coroutine(did, ..) | ty::CoroutineWitness(did, ..) => {
3370 coroutine = coroutine.or(Some(did));
3371 outer_coroutine = Some(did);
3372 }
3373 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
3374 seen_upvar_tys_infer_tuple = true;
3379 }
3380 _ if coroutine.is_none() => {
3381 trait_ref = Some(derived_obligation.parent_trait_pred.skip_binder());
3382 target_ty = Some(ty);
3383 }
3384 _ => {}
3385 }
3386
3387 next_code = Some(&derived_obligation.parent_code);
3388 }
3389 _ => break,
3390 }
3391 }
3392
3393 debug!(?coroutine, ?trait_ref, ?target_ty);
3395 let (Some(coroutine_did), Some(trait_ref), Some(target_ty)) =
3396 (coroutine, trait_ref, target_ty)
3397 else {
3398 return false;
3399 };
3400
3401 let span = self.tcx.def_span(coroutine_did);
3402
3403 let coroutine_did_root = self.tcx.typeck_root_def_id(coroutine_did);
3404 debug!(
3405 ?coroutine_did,
3406 ?coroutine_did_root,
3407 typeck_results.hir_owner = ?self.typeck_results.as_ref().map(|t| t.hir_owner),
3408 ?span,
3409 );
3410
3411 let coroutine_body =
3412 coroutine_did.as_local().and_then(|def_id| self.tcx.hir_maybe_body_owned_by(def_id));
3413 let mut visitor = AwaitsVisitor::default();
3414 if let Some(body) = coroutine_body {
3415 visitor.visit_body(&body);
3416 }
3417 debug!(awaits = ?visitor.awaits);
3418
3419 let target_ty_erased = self.tcx.erase_and_anonymize_regions(target_ty);
3422 let ty_matches = |ty| -> bool {
3423 let ty_erased = self.tcx.instantiate_bound_regions_with_erased(ty);
3436 let ty_erased = self.tcx.erase_and_anonymize_regions(ty_erased);
3437 let eq = ty_erased == target_ty_erased;
3438 debug!(?ty_erased, ?target_ty_erased, ?eq);
3439 eq
3440 };
3441
3442 let coroutine_data = match &self.typeck_results {
3447 Some(t) if t.hir_owner.to_def_id() == coroutine_did_root => CoroutineData(t),
3448 _ if coroutine_did.is_local() => {
3449 CoroutineData(self.tcx.typeck(coroutine_did.expect_local()))
3450 }
3451 _ => return false,
3452 };
3453
3454 let coroutine_within_in_progress_typeck = match &self.typeck_results {
3455 Some(t) => t.hir_owner.to_def_id() == coroutine_did_root,
3456 _ => false,
3457 };
3458
3459 let mut interior_or_upvar_span = None;
3460
3461 let from_awaited_ty = coroutine_data.get_from_await_ty(visitor, self.tcx, ty_matches);
3462 debug!(?from_awaited_ty);
3463
3464 if coroutine_did.is_local()
3466 && !coroutine_within_in_progress_typeck
3468 && let Some(coroutine_info) = self.tcx.mir_coroutine_witnesses(coroutine_did)
3469 {
3470 debug!(?coroutine_info);
3471 'find_source: for (variant, source_info) in
3472 coroutine_info.variant_fields.iter().zip(&coroutine_info.variant_source_info)
3473 {
3474 debug!(?variant);
3475 for &local in variant {
3476 let decl = &coroutine_info.field_tys[local];
3477 debug!(?decl);
3478 if ty_matches(ty::Binder::dummy(decl.ty)) && !decl.ignore_for_traits {
3479 interior_or_upvar_span = Some(CoroutineInteriorOrUpvar::Interior(
3480 decl.source_info.span,
3481 Some((source_info.span, from_awaited_ty)),
3482 ));
3483 break 'find_source;
3484 }
3485 }
3486 }
3487 }
3488
3489 if interior_or_upvar_span.is_none() {
3490 interior_or_upvar_span =
3491 coroutine_data.try_get_upvar_span(self, coroutine_did, ty_matches);
3492 }
3493
3494 if interior_or_upvar_span.is_none() && !coroutine_did.is_local() {
3495 interior_or_upvar_span = Some(CoroutineInteriorOrUpvar::Interior(span, None));
3496 }
3497
3498 debug!(?interior_or_upvar_span);
3499 if let Some(interior_or_upvar_span) = interior_or_upvar_span {
3500 let is_async = self.tcx.coroutine_is_async(coroutine_did);
3501 self.note_obligation_cause_for_async_await(
3502 err,
3503 interior_or_upvar_span,
3504 is_async,
3505 outer_coroutine,
3506 trait_ref,
3507 target_ty,
3508 obligation,
3509 next_code,
3510 );
3511 true
3512 } else {
3513 false
3514 }
3515 }
3516
3517 {}
#[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("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3519u32),
::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 /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3742",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3742u32),
::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)]
3520 fn note_obligation_cause_for_async_await<G: EmissionGuarantee>(
3521 &self,
3522 err: &mut Diag<'_, G>,
3523 interior_or_upvar_span: CoroutineInteriorOrUpvar,
3524 is_async: bool,
3525 outer_coroutine: Option<DefId>,
3526 trait_pred: ty::TraitClause<'tcx>,
3527 target_ty: Ty<'tcx>,
3528 obligation: &PredicateObligation<'tcx>,
3529 next_code: Option<&ObligationCauseCode<'tcx>>,
3530 ) {
3531 let source_map = self.tcx.sess.source_map();
3532
3533 let (await_or_yield, an_await_or_yield) =
3534 if is_async { ("await", "an await") } else { ("yield", "a yield") };
3535 let future_or_coroutine = if is_async { "future" } else { "coroutine" };
3536
3537 let trait_explanation = if let Some(name @ (sym::Send | sym::Sync)) =
3540 self.tcx.get_diagnostic_name(trait_pred.def_id())
3541 {
3542 let (trait_name, trait_verb) =
3543 if name == sym::Send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
3544
3545 err.code = None;
3546 err.primary_message(format!(
3547 "{future_or_coroutine} cannot be {trait_verb} between threads safely"
3548 ));
3549
3550 let original_span = err.span.primary_span().unwrap();
3551 let mut span = MultiSpan::from_span(original_span);
3552
3553 let message = outer_coroutine
3554 .and_then(|coroutine_did| {
3555 Some(match self.tcx.coroutine_kind(coroutine_did).unwrap() {
3556 CoroutineKind::Coroutine(_) => format!("coroutine is not {trait_name}"),
3557 CoroutineKind::Desugared(
3558 CoroutineDesugaring::Async,
3559 CoroutineSource::Fn,
3560 ) => self
3561 .tcx
3562 .parent(coroutine_did)
3563 .as_local()
3564 .map(|parent_did| self.tcx.local_def_id_to_hir_id(parent_did))
3565 .and_then(|parent_hir_id| self.tcx.hir_opt_name(parent_hir_id))
3566 .map(|name| {
3567 format!("future returned by `{name}` is not {trait_name}")
3568 })?,
3569 CoroutineKind::Desugared(
3570 CoroutineDesugaring::Async,
3571 CoroutineSource::Block,
3572 ) => {
3573 format!("future created by async block is not {trait_name}")
3574 }
3575 CoroutineKind::Desugared(
3576 CoroutineDesugaring::Async,
3577 CoroutineSource::Closure,
3578 ) => {
3579 format!("future created by async closure is not {trait_name}")
3580 }
3581 CoroutineKind::Desugared(
3582 CoroutineDesugaring::AsyncGen,
3583 CoroutineSource::Fn,
3584 ) => self
3585 .tcx
3586 .parent(coroutine_did)
3587 .as_local()
3588 .map(|parent_did| self.tcx.local_def_id_to_hir_id(parent_did))
3589 .and_then(|parent_hir_id| self.tcx.hir_opt_name(parent_hir_id))
3590 .map(|name| {
3591 format!("async iterator returned by `{name}` is not {trait_name}")
3592 })?,
3593 CoroutineKind::Desugared(
3594 CoroutineDesugaring::AsyncGen,
3595 CoroutineSource::Block,
3596 ) => {
3597 format!("async iterator created by async gen block is not {trait_name}")
3598 }
3599 CoroutineKind::Desugared(
3600 CoroutineDesugaring::AsyncGen,
3601 CoroutineSource::Closure,
3602 ) => {
3603 format!(
3604 "async iterator created by async gen closure is not {trait_name}"
3605 )
3606 }
3607 CoroutineKind::Desugared(CoroutineDesugaring::Gen, CoroutineSource::Fn) => {
3608 self.tcx
3609 .parent(coroutine_did)
3610 .as_local()
3611 .map(|parent_did| self.tcx.local_def_id_to_hir_id(parent_did))
3612 .and_then(|parent_hir_id| self.tcx.hir_opt_name(parent_hir_id))
3613 .map(|name| {
3614 format!("iterator returned by `{name}` is not {trait_name}")
3615 })?
3616 }
3617 CoroutineKind::Desugared(
3618 CoroutineDesugaring::Gen,
3619 CoroutineSource::Block,
3620 ) => {
3621 format!("iterator created by gen block is not {trait_name}")
3622 }
3623 CoroutineKind::Desugared(
3624 CoroutineDesugaring::Gen,
3625 CoroutineSource::Closure,
3626 ) => {
3627 format!("iterator created by gen closure is not {trait_name}")
3628 }
3629 })
3630 })
3631 .unwrap_or_else(|| format!("{future_or_coroutine} is not {trait_name}"));
3632
3633 span.push_span_label(original_span, message);
3634 err.span(span);
3635
3636 format!("is not {trait_name}")
3637 } else {
3638 format!("does not implement `{}`", trait_pred.print_modifiers_and_trait_path())
3639 };
3640
3641 let mut explain_yield = |interior_span: Span, yield_span: Span| {
3642 let mut span = MultiSpan::from_span(yield_span);
3643 let snippet = match source_map.span_to_snippet(interior_span) {
3644 Ok(snippet) if !snippet.contains('\n') => format!("`{snippet}`"),
3647 _ => "the value".to_string(),
3648 };
3649 span.push_span_label(
3666 yield_span,
3667 format!("{await_or_yield} occurs here, with {snippet} maybe used later"),
3668 );
3669 span.push_span_label(
3670 interior_span,
3671 format!("has type `{target_ty}` which {trait_explanation}"),
3672 );
3673 err.span_note(
3674 span,
3675 format!("{future_or_coroutine} {trait_explanation} as this value is used across {an_await_or_yield}"),
3676 );
3677 };
3678 match interior_or_upvar_span {
3679 CoroutineInteriorOrUpvar::Interior(interior_span, interior_extra_info) => {
3680 if let Some((yield_span, from_awaited_ty)) = interior_extra_info {
3681 if let Some(await_span) = from_awaited_ty {
3682 let mut span = MultiSpan::from_span(await_span);
3684 span.push_span_label(
3685 await_span,
3686 format!(
3687 "await occurs here on type `{target_ty}`, which {trait_explanation}"
3688 ),
3689 );
3690 err.span_note(
3691 span,
3692 format!(
3693 "future {trait_explanation} as it awaits another future which {trait_explanation}"
3694 ),
3695 );
3696 } else {
3697 explain_yield(interior_span, yield_span);
3699 }
3700 }
3701 }
3702 CoroutineInteriorOrUpvar::Upvar(upvar_span) => {
3703 let non_send = match target_ty.kind() {
3705 ty::Ref(_, ref_ty, mutability) => match self.evaluate_obligation(obligation) {
3706 Ok(eval) if !eval.may_apply() => Some((ref_ty, mutability.is_mut())),
3707 _ => None,
3708 },
3709 _ => None,
3710 };
3711
3712 let (span_label, span_note) = match non_send {
3713 Some((ref_ty, is_mut)) => {
3717 let ref_ty_trait = if is_mut { "Send" } else { "Sync" };
3718 let ref_kind = if is_mut { "&mut" } else { "&" };
3719 (
3720 format!(
3721 "has type `{target_ty}` which {trait_explanation}, because `{ref_ty}` is not `{ref_ty_trait}`"
3722 ),
3723 format!(
3724 "captured value {trait_explanation} because `{ref_kind}` references cannot be sent unless their referent is `{ref_ty_trait}`"
3725 ),
3726 )
3727 }
3728 None => (
3729 format!("has type `{target_ty}` which {trait_explanation}"),
3730 format!("captured value {trait_explanation}"),
3731 ),
3732 };
3733
3734 let mut span = MultiSpan::from_span(upvar_span);
3735 span.push_span_label(upvar_span, span_label);
3736 err.span_note(span, span_note);
3737 }
3738 }
3739
3740 debug!(?next_code);
3743 self.note_obligation_cause_code(
3744 obligation.cause.body_def_id,
3745 err,
3746 obligation.predicate,
3747 obligation.param_env,
3748 next_code.unwrap(),
3749 &mut Vec::new(),
3750 &mut Default::default(),
3751 );
3752 }
3753
3754 fn note_closure_capture<G: EmissionGuarantee>(
3755 &self,
3756 err: &mut Diag<'_, G>,
3757 closure_def_id: DefId,
3758 upvar_args: ty::UpvarArgs<'tcx>,
3759 capture_ty: Option<Ty<'tcx>>,
3760 ) -> bool {
3761 let Some(closure_def_id) = closure_def_id.as_local() else {
3762 return false;
3763 };
3764 let Some(capture_ty) = capture_ty else {
3765 return false;
3766 };
3767
3768 let Some(typeck_results) = &self.typeck_results else {
3773 return false;
3774 };
3775 let typeck_root = self.tcx.typeck_root_def_id(closure_def_id.to_def_id());
3776 if typeck_results.hir_owner.to_def_id() != typeck_root {
3777 return false;
3778 }
3779 let captures: Vec<_> =
3780 typeck_results.closure_min_captures_flattened(closure_def_id).collect();
3781 let upvar_tys = upvar_args.upvar_tys();
3782 if captures.len() != upvar_tys.len() {
3783 return false;
3784 }
3785
3786 let capture_ty =
3787 self.tcx.erase_and_anonymize_regions(self.resolve_vars_if_possible(capture_ty));
3788 let Some(capture) = captures.iter().zip(upvar_tys).find_map(|(&capture, upvar_ty)| {
3789 let upvar_ty =
3790 self.tcx.erase_and_anonymize_regions(self.resolve_vars_if_possible(upvar_ty));
3791 (upvar_ty == capture_ty).then_some(capture)
3792 }) else {
3793 return false;
3794 };
3795
3796 err.span_note(
3797 capture.get_path_span(self.tcx),
3798 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("required because `{0}` is used within this closure",
capture.to_string(self.tcx)))
})format!(
3799 "required because `{}` is used within this closure",
3800 capture.to_string(self.tcx)
3801 ),
3802 );
3803 true
3804 }
3805
3806 pub(super) fn note_obligation_cause_code<G: EmissionGuarantee, T>(
3807 &self,
3808 body_def_id: LocalDefId,
3809 err: &mut Diag<'_, G>,
3810 predicate: T,
3811 param_env: ty::ParamEnv<'tcx>,
3812 cause_code: &ObligationCauseCode<'tcx>,
3813 obligated_types: &mut Vec<Ty<'tcx>>,
3814 seen_requirements: &mut FxHashSet<DefId>,
3815 ) where
3816 T: Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>>,
3817 {
3818 let predicate = predicate.upcast(self.tcx);
3819 let mut closure_capture_ty =
3822 predicate.as_trait_clause().map(|trait_pred| trait_pred.skip_binder().self_ty());
3823 self.note_obligation_cause_code_inner(
3824 body_def_id,
3825 err,
3826 predicate,
3827 param_env,
3828 cause_code,
3829 obligated_types,
3830 seen_requirements,
3831 &mut closure_capture_ty,
3832 );
3833 }
3834
3835 fn note_obligation_cause_code_inner<G: EmissionGuarantee, T>(
3836 &self,
3837 body_def_id: LocalDefId,
3838 err: &mut Diag<'_, G>,
3839 predicate: T,
3840 param_env: ty::ParamEnv<'tcx>,
3841 cause_code: &ObligationCauseCode<'tcx>,
3842 obligated_types: &mut Vec<Ty<'tcx>>,
3843 seen_requirements: &mut FxHashSet<DefId>,
3844 closure_capture_ty: &mut Option<Ty<'tcx>>,
3845 ) where
3846 T: Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>>,
3847 {
3848 let tcx = self.tcx;
3849 let predicate = predicate.upcast(tcx);
3850 let suggest_remove_deref = |err: &mut Diag<'_, G>, expr: &hir::Expr<'_>| {
3851 if let Some(pred) = predicate.as_trait_clause()
3852 && tcx.is_lang_item(pred.def_id(), LangItem::Sized)
3853 && let hir::ExprKind::Unary(hir::UnOp::Deref, inner) = expr.kind
3854 {
3855 err.span_suggestion_verbose(
3856 expr.span.until(inner.span),
3857 "references are always `Sized`, even if they point to unsized data; consider \
3858 not dereferencing the expression",
3859 String::new(),
3860 Applicability::MaybeIncorrect,
3861 );
3862 }
3863 };
3864 match *cause_code {
3865 ObligationCauseCode::ExprAssignable
3866 | ObligationCauseCode::MatchExpressionArm { .. }
3867 | ObligationCauseCode::Pattern { .. }
3868 | ObligationCauseCode::IfExpression { .. }
3869 | ObligationCauseCode::IfExpressionWithNoElse
3870 | ObligationCauseCode::MainFunctionType
3871 | ObligationCauseCode::LangFunctionType(_)
3872 | ObligationCauseCode::IntrinsicType
3873 | ObligationCauseCode::MethodReceiver
3874 | ObligationCauseCode::ReturnNoExpression
3875 | ObligationCauseCode::Misc
3876 | ObligationCauseCode::WellFormed(..)
3877 | ObligationCauseCode::MatchImpl(..)
3878 | ObligationCauseCode::ReturnValue(_)
3879 | ObligationCauseCode::BlockTailExpression(..)
3880 | ObligationCauseCode::AwaitableExpr(_)
3881 | ObligationCauseCode::ForLoopIterator(_)
3882 | ObligationCauseCode::QuestionMark
3883 | ObligationCauseCode::CheckAssociatedTypeBounds { .. }
3884 | ObligationCauseCode::LetElse
3885 | ObligationCauseCode::UnOp { .. }
3886 | ObligationCauseCode::AscribeUserTypeProvePredicate(..)
3887 | ObligationCauseCode::AlwaysApplicableImpl
3888 | ObligationCauseCode::ConstParam(_)
3889 | ObligationCauseCode::ReferenceOutlivesReferent(..)
3890 | ObligationCauseCode::ObjectTypeBound(..) => {}
3891 ObligationCauseCode::BinOp { lhs_hir_id, rhs_hir_id, .. } => {
3892 if let hir::Node::Expr(lhs) = tcx.hir_node(lhs_hir_id)
3893 && let hir::Node::Expr(rhs) = tcx.hir_node(rhs_hir_id)
3894 && tcx.sess.source_map().lookup_char_pos(lhs.span.lo()).line
3895 != tcx.sess.source_map().lookup_char_pos(rhs.span.hi()).line
3896 {
3897 err.span_label(lhs.span, "");
3898 err.span_label(rhs.span, "");
3899 }
3900 }
3901 ObligationCauseCode::RustCall => {
3902 if let Some(pred) = predicate.as_trait_clause()
3903 && tcx.is_lang_item(pred.def_id(), LangItem::Sized)
3904 {
3905 err.note("argument required to be sized due to `extern \"rust-call\"` ABI");
3906 }
3907 }
3908 ObligationCauseCode::SliceOrArrayElem => {
3909 err.note("slice and array elements must have `Sized` type");
3910 }
3911 ObligationCauseCode::ArrayLen(array_ty) => {
3912 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`"));
3913 }
3914 ObligationCauseCode::TupleElem => {
3915 err.note("only the last element of a tuple may have a dynamically sized type");
3916 }
3917 ObligationCauseCode::DynCompatible(span) => {
3918 err.multipart_suggestion(
3919 "you might have meant to use `Self` to refer to the implementing type",
3920 ::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())],
3921 Applicability::MachineApplicable,
3922 );
3923 }
3924 ObligationCauseCode::WhereClause(item_def_id, span)
3925 | ObligationCauseCode::WhereClauseInExpr(item_def_id, span, ..)
3926 | ObligationCauseCode::HostEffectInExpr(item_def_id, span, ..)
3927 if !span.is_dummy() =>
3928 {
3929 if let ObligationCauseCode::WhereClauseInExpr(_, _, hir_id, pos) = &cause_code {
3930 if let Node::Expr(expr) = tcx.parent_hir_node(*hir_id)
3931 && let hir::ExprKind::Call(_, args) = expr.kind
3932 && let Some(expr) = args.get(*pos)
3933 {
3934 suggest_remove_deref(err, &expr);
3935 } else if let Node::Expr(expr) = self.tcx.hir_node(*hir_id)
3936 && let hir::ExprKind::MethodCall(_, _, args, _) = expr.kind
3937 && let Some(expr) = args.get(*pos)
3938 {
3939 suggest_remove_deref(err, &expr);
3940 }
3941 }
3942 let item_name = tcx.def_path_str(item_def_id);
3943 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));
3944 let mut multispan = MultiSpan::from(span);
3945 let sm = tcx.sess.source_map();
3946 if let Some(ident) = tcx.opt_item_ident(item_def_id) {
3947 let same_line =
3948 match (sm.lookup_line(ident.span.hi()), sm.lookup_line(span.lo())) {
3949 (Ok(l), Ok(r)) => l.line == r.line,
3950 _ => true,
3951 };
3952 if ident.span.is_visible(sm) && !ident.span.overlaps(span) && !same_line {
3953 multispan.push_span_label(
3954 ident.span,
3955 ::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!(
3956 "required by a bound in this {}",
3957 tcx.def_kind(item_def_id).descr(item_def_id)
3958 ),
3959 );
3960 }
3961 }
3962 let mut a = "a";
3963 let mut this = "this bound";
3964 let mut note = None;
3965 let mut help = None;
3966 if let ty::PredicateKind::Clause(clause) = predicate.kind().skip_binder() {
3967 match clause {
3968 ty::ClauseKind::Trait(trait_pred) => {
3969 let def_id = trait_pred.def_id();
3970 let visible_item = if let Some(local) = def_id.as_local() {
3971 let ty = trait_pred.self_ty();
3972 if let ty::Adt(adt, _) = ty.kind() {
3976 let visibilities = &tcx.resolutions(()).effective_visibilities;
3977 visibilities.effective_vis(local).is_none_or(|v| {
3978 v.at_level(Level::Reexported)
3979 .is_accessible_from(adt.did(), tcx)
3980 })
3981 } else {
3982 true
3984 }
3985 } else {
3986 tcx.visible_parent_map(()).get(&def_id).is_some()
3988 };
3989 if tcx.is_lang_item(def_id, LangItem::Sized) {
3990 if tcx
3992 .generics_of(item_def_id)
3993 .own_params
3994 .iter()
3995 .any(|param| tcx.def_span(param.def_id) == span)
3996 {
3997 a = "an implicit `Sized`";
3998 this =
3999 "the implicit `Sized` requirement on this type parameter";
4000 }
4001 if let Some(hir::Node::TraitItem(hir::TraitItem {
4002 generics,
4003 kind: hir::TraitItemKind::Type(bounds, None),
4004 ..
4005 })) = tcx.hir_get_if_local(item_def_id)
4006 && !bounds.iter()
4008 .filter_map(|bound| bound.trait_ref())
4009 .any(|tr| tr.trait_def_id().is_some_and(|def_id| tcx.is_lang_item(def_id, LangItem::Sized)))
4010 {
4011 let (span, separator) = if let [.., last] = bounds {
4012 (last.span().shrink_to_hi(), " +")
4013 } else {
4014 (generics.span.shrink_to_hi(), ":")
4015 };
4016 err.span_suggestion_verbose(
4017 span,
4018 "consider relaxing the implicit `Sized` restriction",
4019 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} ?Sized", separator))
})format!("{separator} ?Sized"),
4020 Applicability::MachineApplicable,
4021 );
4022 }
4023 }
4024 if let DefKind::Trait = tcx.def_kind(item_def_id)
4025 && !visible_item
4026 {
4027 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!(
4028 "`{short_item_name}` is a \"sealed trait\", because to implement it \
4029 you also need to implement `{}`, which is not accessible; this is \
4030 usually done to force you to use one of the provided types that \
4031 already implement it",
4032 with_no_trimmed_paths!(tcx.def_path_str(def_id)),
4033 ));
4034 let mut types = tcx
4035 .all_impls(def_id)
4036 .map(|t| {
4037 {
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!(
4038 " {}",
4039 tcx.type_of(t).instantiate_identity().skip_norm_wip(),
4040 ))
4041 })
4042 .collect::<Vec<_>>();
4043 if !types.is_empty() {
4044 let len = types.len();
4045 let post = if len > 9 {
4046 types.truncate(8);
4047 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\nand {0} others", len - 8))
})format!("\nand {} others", len - 8)
4048 } else {
4049 String::new()
4050 };
4051 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!(
4052 "the following type{} implement{} the trait:\n{}{post}",
4053 pluralize!(len),
4054 if len == 1 { "s" } else { "" },
4055 types.join("\n"),
4056 ));
4057 }
4058 }
4059 }
4060 ty::ClauseKind::ConstArgHasType(..) => {
4061 let descr =
4062 ::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}`");
4063 if span.is_visible(sm) {
4064 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("required by this const generic parameter in `{0}`",
short_item_name))
})format!(
4065 "required by this const generic parameter in `{short_item_name}`"
4066 );
4067 multispan.push_span_label(span, msg);
4068 err.span_note(multispan, descr);
4069 } else {
4070 err.span_note(tcx.def_span(item_def_id), descr);
4071 }
4072 return;
4073 }
4074 _ => (),
4075 }
4076 }
4077
4078 let is_in_fmt_lit = if let Some(s) = err.span.primary_span() {
4081 #[allow(non_exhaustive_omitted_patterns)] match s.desugaring_kind() {
Some(DesugaringKind::FormatLiteral { .. }) => true,
_ => false,
}matches!(s.desugaring_kind(), Some(DesugaringKind::FormatLiteral { .. }))
4082 } else {
4083 false
4084 };
4085 if !is_in_fmt_lit {
4086 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}`");
4087 if span.is_visible(sm) {
4088 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}`");
4089 multispan.push_span_label(span, msg);
4090 err.span_note(multispan, descr);
4091 } else {
4092 err.span_note(tcx.def_span(item_def_id), descr);
4093 }
4094 }
4095 if let Some(note) = note {
4096 err.note(note);
4097 }
4098 if let Some(help) = help {
4099 err.help(help);
4100 }
4101 }
4102 ObligationCauseCode::WhereClause(..)
4103 | ObligationCauseCode::WhereClauseInExpr(..)
4104 | ObligationCauseCode::HostEffectInExpr(..) => {
4105 }
4108 ObligationCauseCode::OpaqueTypeBound(span, definition_def_id) => {
4109 err.span_note(span, "required by a bound in an opaque type");
4110 if let Some(definition_def_id) = definition_def_id
4111 && self.tcx.typeck(definition_def_id).coroutine_stalled_predicates.is_empty()
4115 {
4116 err.span_note(
4119 tcx.def_span(definition_def_id),
4120 "this definition site has more where clauses than the opaque type",
4121 );
4122 }
4123 }
4124 ObligationCauseCode::Coercion { source, target } => {
4125 let source =
4126 tcx.short_string(self.resolve_vars_if_possible(source), err.long_ty_path());
4127 let target =
4128 tcx.short_string(self.resolve_vars_if_possible(target), err.long_ty_path());
4129 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!(
4130 "required for the cast from `{source}` to `{target}`",
4131 )));
4132 }
4133 ObligationCauseCode::RepeatElementCopy { is_constable, elt_span } => {
4134 err.note(
4135 "the `Copy` trait is required because this value will be copied for each element of the array",
4136 );
4137 let sm = tcx.sess.source_map();
4138 if #[allow(non_exhaustive_omitted_patterns)] match is_constable {
IsConstable::Fn | IsConstable::Ctor => true,
_ => false,
}matches!(is_constable, IsConstable::Fn | IsConstable::Ctor)
4139 && let Ok(_) = sm.span_to_snippet(elt_span)
4140 {
4141 err.multipart_suggestion(
4142 "create an inline `const` block",
4143 ::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![
4144 (elt_span.shrink_to_lo(), "const { ".to_string()),
4145 (elt_span.shrink_to_hi(), " }".to_string()),
4146 ],
4147 Applicability::MachineApplicable,
4148 );
4149 } else {
4150 err.help("consider using `core::array::from_fn` to initialize the array");
4152 err.help("see https://doc.rust-lang.org/stable/std/array/fn.from_fn.html for more information");
4153 }
4154 }
4155 ObligationCauseCode::VariableType(hir_id) => {
4156 if let Some(typeck_results) = &self.typeck_results
4157 && let Some(ty) = typeck_results.node_type_opt(hir_id)
4158 && let ty::Error(_) = ty.kind()
4159 {
4160 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!(
4161 "`{predicate}` isn't satisfied, but the type of this pattern is \
4162 `{{type error}}`",
4163 ));
4164 err.downgrade_to_delayed_bug();
4165 }
4166 let mut local = true;
4167 match tcx.parent_hir_node(hir_id) {
4168 Node::LetStmt(hir::LetStmt { ty: Some(ty), .. }) => {
4169 err.span_suggestion_verbose(
4170 ty.span.shrink_to_lo(),
4171 "consider borrowing here",
4172 "&",
4173 Applicability::MachineApplicable,
4174 );
4175 }
4176 Node::LetStmt(hir::LetStmt {
4177 init: Some(hir::Expr { kind: hir::ExprKind::Index(..), span, .. }),
4178 ..
4179 }) => {
4180 err.span_suggestion_verbose(
4184 span.shrink_to_lo(),
4185 "consider borrowing here",
4186 "&",
4187 Applicability::MachineApplicable,
4188 );
4189 }
4190 Node::LetStmt(hir::LetStmt { init: Some(expr), .. }) => {
4191 suggest_remove_deref(err, &expr);
4194 }
4195 Node::Param(param) => {
4196 err.span_suggestion_verbose(
4197 param.ty_span.shrink_to_lo(),
4198 "function arguments must have a statically known size, borrowed types \
4199 always have a known size",
4200 "&",
4201 Applicability::MachineApplicable,
4202 );
4203 local = false;
4204 }
4205 _ => {}
4206 }
4207 if local {
4208 err.note("all local variables must have a statically known size");
4209 }
4210 }
4211 ObligationCauseCode::SizedArgumentType(hir_id) => {
4212 let mut ty = None;
4213 let borrowed_msg = "function arguments must have a statically known size, borrowed \
4214 types always have a known size";
4215 if let Some(hir_id) = hir_id
4216 && let hir::Node::Param(param) = self.tcx.hir_node(hir_id)
4217 && let Some(decl) = self.tcx.parent_hir_node(hir_id).fn_decl()
4218 && let Some(t) = decl.inputs.iter().find(|t| param.ty_span.contains(t.span))
4219 {
4220 ty = Some(t);
4228 } else if let Some(hir_id) = hir_id
4229 && let hir::Node::Ty(t) = self.tcx.hir_node(hir_id)
4230 {
4231 ty = Some(t);
4232 }
4233 if let Some(ty) = ty {
4234 match ty.kind {
4235 hir::TyKind::TraitObject(traits, _) => {
4236 let (span, kw) = match traits {
4237 [first, ..] if first.span.lo() == ty.span.lo() => {
4238 (ty.span.shrink_to_lo(), "dyn ")
4240 }
4241 [first, ..] => (ty.span.until(first.span), ""),
4242 [] => ::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:?}"),
4243 };
4244 let needs_parens = traits.len() != 1;
4245 if let Some(hir_id) = hir_id
4247 && #[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!(
4248 self.tcx.parent_hir_node(hir_id),
4249 hir::Node::Item(hir::Item {
4250 kind: hir::ItemKind::Fn { .. },
4251 ..
4252 })
4253 )
4254 {
4255 err.span_suggestion_verbose(
4256 span,
4257 "you can use `impl Trait` as the argument type",
4258 "impl ",
4259 Applicability::MaybeIncorrect,
4260 );
4261 }
4262 let sugg = if !needs_parens {
4263 ::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}"))]
4264 } else {
4265 ::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![
4266 (span.shrink_to_lo(), format!("&({kw}")),
4267 (ty.span.shrink_to_hi(), ")".to_string()),
4268 ]
4269 };
4270 err.multipart_suggestion(
4271 borrowed_msg,
4272 sugg,
4273 Applicability::MachineApplicable,
4274 );
4275 }
4276 hir::TyKind::Slice(_ty) => {
4277 err.span_suggestion_verbose(
4278 ty.span.shrink_to_lo(),
4279 "function arguments must have a statically known size, borrowed \
4280 slices always have a known size",
4281 "&",
4282 Applicability::MachineApplicable,
4283 );
4284 }
4285 hir::TyKind::Path(_) => {
4286 err.span_suggestion_verbose(
4287 ty.span.shrink_to_lo(),
4288 borrowed_msg,
4289 "&",
4290 Applicability::MachineApplicable,
4291 );
4292 }
4293 _ => {}
4294 }
4295 } else {
4296 err.note("all function arguments must have a statically known size");
4297 }
4298 if tcx.sess.opts.unstable_features.is_nightly_build()
4299 && !tcx.features().unsized_fn_params()
4300 {
4301 err.help("unsized fn params are gated as an unstable feature");
4302 }
4303 }
4304 ObligationCauseCode::SizedReturnType | ObligationCauseCode::SizedCallReturnType => {
4305 err.note("the return type of a function must have a statically known size");
4306 }
4307 ObligationCauseCode::SizedYieldType => {
4308 err.note("the yield type of a coroutine must have a statically known size");
4309 }
4310 ObligationCauseCode::AssignmentLhsSized => {
4311 err.note("the left-hand-side of an assignment must have a statically known size");
4312 }
4313 ObligationCauseCode::TupleInitializerSized => {
4314 err.note("tuples must have a statically known size to be initialized");
4315 }
4316 ObligationCauseCode::StructInitializerSized => {
4317 err.note("structs must have a statically known size to be initialized");
4318 }
4319 ObligationCauseCode::FieldSized { adt_kind: ref item, last, span } => {
4320 match *item {
4321 AdtKind::Struct => {
4322 if last {
4323 err.note(
4324 "the last field of a packed struct may only have a \
4325 dynamically sized type if it does not need drop to be run",
4326 );
4327 } else {
4328 err.note(
4329 "only the last field of a struct may have a dynamically sized type",
4330 );
4331 }
4332 }
4333 AdtKind::Union => {
4334 err.note("no field of a union may have a dynamically sized type");
4335 }
4336 AdtKind::Enum => {
4337 err.note("no field of an enum variant may have a dynamically sized type");
4338 }
4339 }
4340 err.help("change the field's type to have a statically known size");
4341 err.span_suggestion_verbose(
4342 span.shrink_to_lo(),
4343 "borrowed types always have a statically known size",
4344 "&",
4345 Applicability::MachineApplicable,
4346 );
4347 err.multipart_suggestion(
4348 "the `Box` type always has a statically known size and allocates its contents \
4349 in the heap",
4350 ::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![
4351 (span.shrink_to_lo(), "Box<".to_string()),
4352 (span.shrink_to_hi(), ">".to_string()),
4353 ],
4354 Applicability::MachineApplicable,
4355 );
4356 }
4357 ObligationCauseCode::SizedConstOrStatic => {
4358 err.note("statics and constants must have a statically known size");
4359 }
4360 ObligationCauseCode::InlineAsmSized => {
4361 err.note("all inline asm arguments must have a statically known size");
4362 }
4363 ObligationCauseCode::SizedClosureCapture(closure_def_id) => {
4364 err.note(
4365 "all values captured by value by a closure must have a statically known size",
4366 );
4367 let hir::ExprKind::Closure(closure) =
4368 tcx.hir_node_by_def_id(closure_def_id).expect_expr().kind
4369 else {
4370 ::rustc_middle::util::bug::bug_fmt(format_args!("expected closure in SizedClosureCapture obligation"));bug!("expected closure in SizedClosureCapture obligation");
4371 };
4372 if let hir::CaptureBy::Value { .. } = closure.capture_clause
4373 && let Some(span) = closure.fn_arg_span
4374 {
4375 err.span_label(span, "this closure captures all values by move");
4376 }
4377 }
4378 ObligationCauseCode::SizedCoroutineInterior(coroutine_def_id) => {
4379 let what = match tcx.coroutine_kind(coroutine_def_id) {
4380 None
4381 | Some(hir::CoroutineKind::Coroutine(_))
4382 | Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, _)) => {
4383 "yield"
4384 }
4385 Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)) => {
4386 "await"
4387 }
4388 Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, _)) => {
4389 "yield`/`await"
4390 }
4391 };
4392 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("all values live across `{0}` must have a statically known size",
what))
})format!(
4393 "all values live across `{what}` must have a statically known size"
4394 ));
4395 }
4396 ObligationCauseCode::SharedStatic => {
4397 err.note("shared static variables must have a type that implements `Sync`");
4398 }
4399 ObligationCauseCode::BuiltinDerived(ref data) => {
4400 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
4401 let ty = parent_trait_ref.skip_binder().self_ty();
4402 if parent_trait_ref.references_error() {
4403 err.downgrade_to_delayed_bug();
4406 return;
4407 }
4408
4409 let is_upvar_tys_infer_tuple = if !#[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
ty::Tuple(..) => true,
_ => false,
}matches!(ty.kind(), ty::Tuple(..)) {
4412 false
4413 } else if let ObligationCauseCode::BuiltinDerived(data) = &*data.parent_code {
4414 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
4415 let nested_ty = parent_trait_ref.skip_binder().self_ty();
4416 #[allow(non_exhaustive_omitted_patterns)] match nested_ty.kind() {
ty::Coroutine(..) => true,
_ => false,
}matches!(nested_ty.kind(), ty::Coroutine(..))
4417 || #[allow(non_exhaustive_omitted_patterns)] match nested_ty.kind() {
ty::Closure(..) => true,
_ => false,
}matches!(nested_ty.kind(), ty::Closure(..))
4418 || #[allow(non_exhaustive_omitted_patterns)] match nested_ty.kind() {
ty::CoroutineClosure(..) => true,
_ => false,
}matches!(nested_ty.kind(), ty::CoroutineClosure(..))
4419 } else {
4420 false
4421 };
4422
4423 let is_builtin_async_fn_trait =
4424 tcx.async_fn_trait_kind_from_def_id(data.parent_trait_pred.def_id()).is_some();
4425
4426 if !is_upvar_tys_infer_tuple && !is_builtin_async_fn_trait {
4427 let mut msg = || {
4428 let ty_str = tcx.short_string(ty, err.long_ty_path());
4429 ::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}`")
4430 };
4431 match *ty.kind() {
4432 ty::Adt(def, _) => {
4433 let msg = msg();
4434 match tcx.opt_item_ident(def.did()) {
4435 Some(ident) => {
4436 err.span_note(ident.span, msg);
4437 }
4438 None => {
4439 err.note(msg);
4440 }
4441 }
4442 }
4443 ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, .. }) => {
4444 let is_future = tcx.ty_is_opaque_future(ty);
4447 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:4447",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(4447u32),
::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!(
4448 ?obligated_types,
4449 ?is_future,
4450 "note_obligation_cause_code: check for async fn"
4451 );
4452 if is_future
4453 && obligated_types.last().is_some_and(|ty| match ty.kind() {
4454 ty::Coroutine(last_def_id, ..) => {
4455 tcx.coroutine_is_async(*last_def_id)
4456 }
4457 _ => false,
4458 })
4459 {
4460 } else {
4462 let msg = msg();
4463 err.span_note(tcx.def_span(def_id), msg);
4464 }
4465 }
4466 ty::Coroutine(def_id, _) => {
4467 let sp = tcx.def_span(def_id);
4468
4469 let kind = tcx.coroutine_kind(def_id).unwrap();
4471 err.span_note(
4472 sp,
4473 {
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!(
4474 "required because it's used within this {kind:#}",
4475 )),
4476 );
4477 }
4478 ty::CoroutineWitness(..) => {
4479 }
4482 ty::Closure(def_id, args) => {
4483 if !self.note_closure_capture(
4484 err,
4485 def_id,
4486 ty::UpvarArgs::Closure(args),
4487 *closure_capture_ty,
4488 ) {
4489 err.span_note(
4490 tcx.def_span(def_id),
4491 "required because it's used within this closure",
4492 );
4493 }
4494 }
4495 ty::CoroutineClosure(def_id, args) => {
4496 if !self.note_closure_capture(
4497 err,
4498 def_id,
4499 ty::UpvarArgs::CoroutineClosure(args),
4500 *closure_capture_ty,
4501 ) {
4502 err.span_note(
4503 tcx.def_span(def_id),
4504 "required because it's used within this closure",
4505 );
4506 }
4507 }
4508 ty::Str => {
4509 err.note("`str` is considered to contain a `[u8]` slice for auto trait purposes");
4510 }
4511 _ => {
4512 let msg = msg();
4513 err.note(msg);
4514 }
4515 };
4516 }
4517
4518 if !is_upvar_tys_infer_tuple {
4519 *closure_capture_ty = Some(ty);
4520 }
4521
4522 obligated_types.push(ty);
4523
4524 let parent_predicate = parent_trait_ref;
4525 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
4526 self.note_obligation_cause_code_inner(
4527 body_def_id,
4528 err,
4529 parent_predicate,
4530 param_env,
4531 &data.parent_code,
4532 obligated_types,
4533 seen_requirements,
4534 closure_capture_ty,
4535 );
4536 } else {
4537 self.note_obligation_cause_code_inner(
4538 body_def_id,
4539 err,
4540 parent_predicate,
4541 param_env,
4542 cause_code.peel_derives(),
4543 obligated_types,
4544 seen_requirements,
4545 closure_capture_ty,
4546 );
4547 }
4548 }
4549 ObligationCauseCode::ImplDerived(ref data) => {
4550 let mut parent_trait_pred =
4551 self.resolve_vars_if_possible(data.derived.parent_trait_pred);
4552 let parent_def_id = parent_trait_pred.def_id();
4553 if tcx.is_diagnostic_item(sym::FromResidual, parent_def_id)
4554 && !tcx.features().enabled(sym::try_trait_v2)
4555 {
4556 return;
4560 }
4561 if tcx.is_diagnostic_item(sym::PinDerefMutHelper, parent_def_id) {
4562 let parent_predicate =
4563 self.resolve_vars_if_possible(data.derived.parent_trait_pred);
4564
4565 *closure_capture_ty = Some(parent_trait_pred.skip_binder().self_ty());
4568 self.note_obligation_cause_code_inner(
4569 body_def_id,
4570 err,
4571 parent_predicate,
4572 param_env,
4573 &data.derived.parent_code,
4574 obligated_types,
4575 seen_requirements,
4576 closure_capture_ty,
4577 );
4578 return;
4579 }
4580 let self_ty_str =
4581 tcx.short_string(parent_trait_pred.skip_binder().self_ty(), err.long_ty_path());
4582 let trait_name = tcx.short_string(
4583 parent_trait_pred.print_modifiers_and_trait_path(),
4584 err.long_ty_path(),
4585 );
4586 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}`");
4587 let mut is_auto_trait = false;
4588 match tcx.hir_get_if_local(data.impl_or_alias_def_id) {
4589 Some(Node::Item(hir::Item {
4590 kind: hir::ItemKind::Trait { is_auto, ident, .. },
4591 ..
4592 })) => {
4593 is_auto_trait = #[allow(non_exhaustive_omitted_patterns)] match is_auto {
hir::IsAuto::Yes => true,
_ => false,
}matches!(is_auto, hir::IsAuto::Yes);
4596 err.span_note(ident.span, msg);
4597 }
4598 Some(Node::Item(hir::Item {
4599 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, generics, .. }),
4600 ..
4601 })) => {
4602 let mut spans = Vec::with_capacity(2);
4603 if let Some(of_trait) = of_trait
4604 && !of_trait.trait_ref.path.span.in_derive_expansion()
4605 {
4606 spans.push(of_trait.trait_ref.path.span);
4607 }
4608 spans.push(self_ty.span);
4609 let mut spans: MultiSpan = spans.into();
4610 let mut derived = false;
4611 if #[allow(non_exhaustive_omitted_patterns)] match self_ty.span.ctxt().outer_expn_data().kind
{
ExpnKind::Macro(MacroKind::Derive, _) => true,
_ => false,
}matches!(
4612 self_ty.span.ctxt().outer_expn_data().kind,
4613 ExpnKind::Macro(MacroKind::Derive, _)
4614 ) || #[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!(
4615 of_trait.map(|t| t.trait_ref.path.span.ctxt().outer_expn_data().kind),
4616 Some(ExpnKind::Macro(MacroKind::Derive, _))
4617 ) {
4618 derived = true;
4619 spans.push_span_label(
4620 data.span,
4621 if data.span.in_derive_expansion() {
4622 ::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}`")
4623 } else {
4624 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unsatisfied trait bound"))
})format!("unsatisfied trait bound")
4625 },
4626 );
4627 } else if !data.span.is_dummy() && !data.span.overlaps(self_ty.span) {
4628 if let Some(pred) = predicate.as_trait_clause()
4631 && self.tcx.is_lang_item(pred.def_id(), LangItem::Sized)
4632 && self
4633 .tcx
4634 .generics_of(data.impl_or_alias_def_id)
4635 .own_params
4636 .iter()
4637 .any(|param| self.tcx.def_span(param.def_id) == data.span)
4638 {
4639 spans.push_span_label(
4640 data.span,
4641 "unsatisfied trait bound implicitly introduced here",
4642 );
4643 } else {
4644 spans.push_span_label(
4645 data.span,
4646 "unsatisfied trait bound introduced here",
4647 );
4648 }
4649 }
4650 err.span_note(spans, msg);
4651 if derived
4652 && self.is_truly_imperfect_derive(
4653 parent_trait_pred,
4654 predicate,
4655 param_env,
4656 )
4657 {
4658 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!(
4659 "consider manually implementing `{trait_name}` to avoid undesired bounds caused by \"imperfect derives\"",
4660 ));
4661 err.note(
4662 "to learn more, visit <https://github.com/rust-lang/rust/issues/26925>",
4663 );
4664 }
4665 point_at_assoc_type_restriction(
4666 tcx,
4667 err,
4668 &self_ty_str,
4669 &trait_name,
4670 predicate,
4671 &generics,
4672 &data,
4673 );
4674 }
4675 _ => {
4676 err.note(msg);
4677 }
4678 };
4679
4680 let mut parent_predicate = parent_trait_pred;
4681 let mut data = &data.derived;
4682 let mut count = 0;
4683 seen_requirements.insert(parent_def_id);
4684 if is_auto_trait {
4685 while let ObligationCauseCode::BuiltinDerived(derived) = &*data.parent_code {
4688 let child_trait_ref =
4689 self.resolve_vars_if_possible(derived.parent_trait_pred);
4690 let child_def_id = child_trait_ref.def_id();
4691 if seen_requirements.insert(child_def_id) {
4692 break;
4693 }
4694 data = derived;
4695 parent_predicate = child_trait_ref.upcast(tcx);
4696 parent_trait_pred = child_trait_ref;
4697 }
4698 }
4699 while let ObligationCauseCode::ImplDerived(child) = &*data.parent_code {
4700 let child_trait_pred =
4702 self.resolve_vars_if_possible(child.derived.parent_trait_pred);
4703 let child_def_id = child_trait_pred.def_id();
4704 if seen_requirements.insert(child_def_id) {
4705 break;
4706 }
4707 count += 1;
4708 data = &child.derived;
4709 parent_predicate = child_trait_pred.upcast(tcx);
4710 parent_trait_pred = child_trait_pred;
4711 }
4712 if count > 0 {
4713 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} redundant requirement{1} hidden",
count, if count == 1 { "" } else { "s" }))
})format!(
4714 "{} redundant requirement{} hidden",
4715 count,
4716 pluralize!(count)
4717 ));
4718 let self_ty = tcx.short_string(
4719 parent_trait_pred.skip_binder().self_ty(),
4720 err.long_ty_path(),
4721 );
4722 let trait_path = tcx.short_string(
4723 parent_trait_pred.print_modifiers_and_trait_path(),
4724 err.long_ty_path(),
4725 );
4726 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}`"));
4727 }
4728 *closure_capture_ty = Some(parent_trait_pred.skip_binder().self_ty());
4729 self.note_obligation_cause_code_inner(
4730 body_def_id,
4731 err,
4732 parent_predicate,
4733 param_env,
4734 &data.parent_code,
4735 obligated_types,
4736 seen_requirements,
4737 closure_capture_ty,
4738 )
4739 }
4740 ObligationCauseCode::ImplDerivedHost(ref data) => {
4741 let self_ty = tcx.short_string(
4742 self.resolve_vars_if_possible(data.derived.parent_host_clause.self_ty()),
4743 err.long_ty_path(),
4744 );
4745 let trait_path = tcx.short_string(
4746 data.derived
4747 .parent_host_clause
4748 .map_bound(|clause| clause.trait_ref)
4749 .print_only_trait_path(),
4750 err.long_ty_path(),
4751 );
4752 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!(
4753 "required for `{self_ty}` to implement `{} {trait_path}`",
4754 data.derived.parent_host_clause.skip_binder().constness,
4755 );
4756 match tcx.hir_get_if_local(data.impl_def_id) {
4757 Some(Node::Item(hir::Item {
4758 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
4759 ..
4760 })) => {
4761 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];
4762 spans.extend(of_trait.map(|t| t.trait_ref.path.span));
4763 let mut spans: MultiSpan = spans.into();
4764 spans.push_span_label(data.span, "unsatisfied trait bound introduced here");
4765 err.span_note(spans, msg);
4766 }
4767 _ => {
4768 err.note(msg);
4769 }
4770 }
4771
4772 self.note_obligation_cause_code_inner(
4773 body_def_id,
4774 err,
4775 data.derived.parent_host_clause,
4776 param_env,
4777 &data.derived.parent_code,
4778 obligated_types,
4779 seen_requirements,
4780 closure_capture_ty,
4781 );
4782 }
4783 ObligationCauseCode::BuiltinDerivedHost(ref data) => {
4784 self.note_obligation_cause_code_inner(
4785 body_def_id,
4786 err,
4787 data.parent_host_clause,
4788 param_env,
4789 &data.parent_code,
4790 obligated_types,
4791 seen_requirements,
4792 closure_capture_ty,
4793 );
4794 }
4795 ObligationCauseCode::WellFormedDerived(ref data) => {
4796 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
4797 let parent_predicate = parent_trait_ref;
4798
4799 *closure_capture_ty = Some(parent_trait_ref.skip_binder().self_ty());
4800 self.note_obligation_cause_code_inner(
4801 body_def_id,
4802 err,
4803 parent_predicate,
4804 param_env,
4805 &data.parent_code,
4806 obligated_types,
4807 seen_requirements,
4808 closure_capture_ty,
4809 );
4810 }
4811 ObligationCauseCode::TypeAlias(ref nested, span, def_id) => {
4812 self.note_obligation_cause_code_inner(
4813 body_def_id,
4814 err,
4815 predicate,
4816 param_env,
4817 nested,
4818 obligated_types,
4819 seen_requirements,
4820 closure_capture_ty,
4821 );
4822 let mut multispan = MultiSpan::from(span);
4823 multispan.push_span_label(span, "required by this bound");
4824 err.span_note(
4825 multispan,
4826 ::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)),
4827 );
4828 }
4829 ObligationCauseCode::FunctionArg {
4830 arg_hir_id, call_hir_id, ref parent_code, ..
4831 } => {
4832 self.note_function_argument_obligation(
4833 body_def_id,
4834 err,
4835 arg_hir_id,
4836 parent_code,
4837 param_env,
4838 predicate,
4839 call_hir_id,
4840 );
4841
4842 self.note_obligation_cause_code_inner(
4843 body_def_id,
4844 err,
4845 predicate,
4846 param_env,
4847 parent_code,
4848 obligated_types,
4849 seen_requirements,
4850 closure_capture_ty,
4851 );
4852 }
4853 ObligationCauseCode::CompareImplItem { trait_item_def_id, .. }
4856 if tcx.is_impl_trait_in_trait(trait_item_def_id) => {}
4857 ObligationCauseCode::CompareImplItem { trait_item_def_id, kind, .. } => {
4858 let item_name = tcx.item_name(trait_item_def_id);
4859 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!(
4860 "the requirement `{predicate}` appears on the `impl`'s {kind} \
4861 `{item_name}` but not on the corresponding trait's {kind}",
4862 );
4863 let sp = tcx
4864 .opt_item_ident(trait_item_def_id)
4865 .map(|i| i.span)
4866 .unwrap_or_else(|| tcx.def_span(trait_item_def_id));
4867 let mut assoc_span: MultiSpan = sp.into();
4868 assoc_span.push_span_label(
4869 sp,
4870 ::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}`"),
4871 );
4872 if let Some(ident) = tcx
4873 .opt_associated_item(trait_item_def_id)
4874 .and_then(|i| tcx.opt_item_ident(i.container_id(tcx)))
4875 {
4876 assoc_span.push_span_label(ident.span, "in this trait");
4877 }
4878 err.span_note(assoc_span, msg);
4879 }
4880 ObligationCauseCode::TrivialBound => {
4881 tcx.disabled_nightly_features(err, [(String::new(), sym::trivial_bounds)]);
4882 }
4883 ObligationCauseCode::OpaqueReturnType(expr_info) => {
4884 if let Some(typeck_results) = self.typeck_results.as_deref() {
4888 let chain_expr = match expr_info {
4889 Some((_, hir_id)) => Some(tcx.hir_expect_expr(hir_id)),
4890 None => tcx.hir_node_by_def_id(body_def_id).body_id().and_then(|body_id| {
4891 match tcx.hir_body(body_id).value.kind {
4892 hir::ExprKind::Block(block, _) => block.expr,
4893 _ => None,
4894 }
4895 }),
4896 };
4897 if let Some(chain_expr) = chain_expr {
4898 self.point_at_chain_in_return_position(
4899 body_def_id,
4900 chain_expr,
4901 typeck_results,
4902 param_env,
4903 err,
4904 );
4905 }
4906 }
4907 let (expr_ty, expr) = if let Some((expr_ty, hir_id)) = expr_info {
4908 let expr = tcx.hir_expect_expr(hir_id);
4909 (expr_ty, expr)
4910 } else if let Some(body_id) = tcx.hir_node_by_def_id(body_def_id).body_id()
4911 && let body = tcx.hir_body(body_id)
4912 && let hir::ExprKind::Block(block, _) = body.value.kind
4913 && let Some(expr) = block.expr
4914 && let Some(expr_ty) = self
4915 .typeck_results
4916 .as_ref()
4917 .and_then(|typeck| typeck.node_type_opt(expr.hir_id))
4918 && let Some(pred) = predicate.as_clause()
4919 && let ty::ClauseKind::Trait(pred) = pred.kind().skip_binder()
4920 && self.can_eq(param_env, pred.self_ty(), expr_ty)
4921 {
4922 (expr_ty, expr)
4923 } else {
4924 return;
4925 };
4926 let expr_ty_string = tcx.short_string(expr_ty, err.long_ty_path());
4927 if expr_ty.is_never()
4928 && let span = expr.span.source_callsite()
4929 && let Ok(snippet) = tcx.sess.source_map().span_to_snippet(span)
4930 && span != expr.span
4931 {
4932 err.span_suggestion(
4933 span,
4934 "`!` can be coerced to any type; consider casting it to a concrete type that implements the trait",
4935 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} as /* Type */", snippet))
})format!("{snippet} as /* Type */"),
4936 Applicability::HasPlaceholders,
4937 );
4938 }
4939 err.span_label(
4940 expr.span,
4941 {
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!(
4942 "return type was inferred to be `{expr_ty_string}` here",
4943 )),
4944 );
4945 suggest_remove_deref(err, &expr);
4946 }
4947 ObligationCauseCode::UnsizedNonPlaceExpr(span) => {
4948 err.span_note(
4949 span,
4950 "unsized values must be place expressions and cannot be put in temporaries",
4951 );
4952 }
4953 ObligationCauseCode::CompareEii { .. } => {
4954 {
::core::panicking::panic_fmt(format_args!("trait bounds on EII not yet supported "));
}panic!("trait bounds on EII not yet supported ")
4955 }
4956 }
4957 }
4958
4959 {}
#[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("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(4959u32),
::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 /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:4996",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(4996u32),
::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 /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:5003",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(5003u32),
::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(
4960 level = "debug", skip(self, err), fields(trait_pred.self_ty = ?trait_pred.self_ty())
4961 )]
4962 pub(super) fn suggest_await_before_try(
4963 &self,
4964 err: &mut Diag<'_>,
4965 obligation: &PredicateObligation<'tcx>,
4966 trait_pred: ty::PolyTraitClause<'tcx>,
4967 span: Span,
4968 ) {
4969 let future_trait = self.tcx.require_lang_item(LangItem::Future, span);
4970
4971 let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
4972 let impls_future = self.type_implements_trait(
4973 future_trait,
4974 [self.tcx.instantiate_bound_regions_with_erased(self_ty)],
4975 obligation.param_env,
4976 );
4977 if !impls_future.must_apply_modulo_regions() {
4978 return;
4979 }
4980
4981 let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
4982 let projection_ty = trait_pred.map_bound(|trait_pred| {
4984 Ty::new_projection(
4985 self.tcx,
4986 ty::IsRigid::No,
4987 item_def_id,
4988 [trait_pred.self_ty()],
4990 )
4991 });
4992 let InferOk { value: projection_ty, .. } = self
4993 .at(&obligation.cause, obligation.param_env)
4994 .normalize(Unnormalized::new_wip(projection_ty));
4995
4996 debug!(
4997 normalized_projection_type = ?self.resolve_vars_if_possible(projection_ty)
4998 );
4999 let try_obligation = self.mk_trait_obligation_with_new_self_ty(
5000 obligation.param_env,
5001 trait_pred.map_bound(|trait_pred| (trait_pred, projection_ty.skip_binder())),
5002 );
5003 debug!(try_trait_obligation = ?try_obligation);
5004 if self.predicate_may_hold(&try_obligation)
5005 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
5006 && snippet.ends_with('?')
5007 {
5008 match self.tcx.coroutine_kind(obligation.cause.body_def_id) {
5009 Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)) => {
5010 err.span_suggestion_verbose(
5011 span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(),
5012 "consider `await`ing on the `Future`",
5013 ".await",
5014 Applicability::MaybeIncorrect,
5015 );
5016 }
5017 _ => {
5018 let mut span: MultiSpan = span.with_lo(span.hi() - BytePos(1)).into();
5019 span.push_span_label(
5020 self.tcx.def_span(obligation.cause.body_def_id),
5021 "this is not `async`",
5022 );
5023 err.span_note(
5024 span,
5025 "this implements `Future` and its output type supports \
5026 `?`, but the future cannot be awaited in a synchronous function",
5027 );
5028 }
5029 }
5030 }
5031 }
5032
5033 pub(super) fn suggest_floating_point_literal(
5034 &self,
5035 obligation: &PredicateObligation<'tcx>,
5036 err: &mut Diag<'_>,
5037 trait_pred: ty::PolyTraitClause<'tcx>,
5038 ) {
5039 let rhs_span = match obligation.cause.code() {
5040 ObligationCauseCode::BinOp { rhs_span, rhs_is_lit, .. } if *rhs_is_lit => rhs_span,
5041 _ => return,
5042 };
5043 if let ty::Float(_) = trait_pred.skip_binder().self_ty().kind()
5044 && let ty::Infer(InferTy::IntVar(_)) =
5045 trait_pred.skip_binder().trait_ref.args.type_at(1).kind()
5046 {
5047 err.span_suggestion_verbose(
5048 rhs_span.shrink_to_hi(),
5049 "consider using a floating-point literal by writing it with `.0`",
5050 ".0",
5051 Applicability::MaybeIncorrect,
5052 );
5053 }
5054 }
5055
5056 pub fn can_suggest_derive(
5057 &self,
5058 obligation: &PredicateObligation<'tcx>,
5059 trait_pred: ty::PolyTraitClause<'tcx>,
5060 ) -> bool {
5061 if trait_pred.polarity() == ty::ClausePolarity::Negative {
5062 return false;
5063 }
5064 let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else {
5065 return false;
5066 };
5067 let (adt, args) = match trait_pred.skip_binder().self_ty().kind() {
5068 ty::Adt(adt, args) if adt.did().is_local() => (adt, args),
5069 _ => return false,
5070 };
5071 let is_derivable_trait = match diagnostic_name {
5072 sym::Copy | sym::Clone => true,
5073 _ if adt.is_union() => false,
5074 sym::PartialEq | sym::PartialOrd => {
5075 let rhs_ty = trait_pred.skip_binder().trait_ref.args.type_at(1);
5076 trait_pred.skip_binder().self_ty() == rhs_ty
5077 }
5078 sym::Eq | sym::Ord | sym::Hash | sym::Debug | sym::Default => true,
5079 _ => false,
5080 };
5081 is_derivable_trait &&
5082 adt.all_fields().all(|field| {
5084 let field_ty = ty::GenericArg::from(field.ty(self.tcx, args).skip_norm_wip());
5085 let trait_args = match diagnostic_name {
5086 sym::PartialEq | sym::PartialOrd => {
5087 Some(field_ty)
5088 }
5089 _ => None,
5090 };
5091 let trait_pred = trait_pred.map_bound_ref(|tr| ty::TraitClause {
5092 trait_ref: ty::TraitRef::new(self.tcx,
5093 trait_pred.def_id(),
5094 [field_ty].into_iter().chain(trait_args),
5095 ),
5096 ..*tr
5097 });
5098 let field_obl = Obligation::new(
5099 self.tcx,
5100 obligation.cause.clone(),
5101 obligation.param_env,
5102 trait_pred,
5103 );
5104 self.predicate_must_hold_modulo_regions(&field_obl)
5105 })
5106 }
5107
5108 pub fn suggest_derive(
5109 &self,
5110 obligation: &PredicateObligation<'tcx>,
5111 err: &mut Diag<'_>,
5112 trait_pred: ty::PolyTraitClause<'tcx>,
5113 ) {
5114 let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else {
5115 return;
5116 };
5117 let adt = match trait_pred.skip_binder().self_ty().kind() {
5118 ty::Adt(adt, _) if adt.did().is_local() => adt,
5119 _ => return,
5120 };
5121 if self.can_suggest_derive(obligation, trait_pred) {
5122 err.span_suggestion_verbose(
5123 self.tcx.def_span(adt.did()).shrink_to_lo(),
5124 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider annotating `{0}` with `#[derive({1})]`",
trait_pred.skip_binder().self_ty(), diagnostic_name))
})format!(
5125 "consider annotating `{}` with `#[derive({})]`",
5126 trait_pred.skip_binder().self_ty(),
5127 diagnostic_name,
5128 ),
5129 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("#[derive({0})]\n",
diagnostic_name))
})format!("#[derive({diagnostic_name})]\n"),
5131 Applicability::MaybeIncorrect,
5132 );
5133 }
5134 }
5135
5136 pub(super) fn suggest_dereferencing_index(
5137 &self,
5138 obligation: &PredicateObligation<'tcx>,
5139 err: &mut Diag<'_>,
5140 trait_pred: ty::PolyTraitClause<'tcx>,
5141 ) {
5142 if let ObligationCauseCode::ImplDerived(_) = obligation.cause.code()
5143 && self
5144 .tcx
5145 .is_diagnostic_item(sym::SliceIndex, trait_pred.skip_binder().trait_ref.def_id)
5146 && let ty::Slice(_) = trait_pred.skip_binder().trait_ref.args.type_at(1).kind()
5147 && let ty::Ref(_, inner_ty, _) = trait_pred.skip_binder().self_ty().kind()
5148 && let ty::Uint(ty::UintTy::Usize) = inner_ty.kind()
5149 {
5150 err.span_suggestion_verbose(
5151 obligation.cause.span.shrink_to_lo(),
5152 "dereference this index",
5153 '*',
5154 Applicability::MachineApplicable,
5155 );
5156 }
5157 }
5158
5159 fn note_function_argument_obligation<G: EmissionGuarantee>(
5160 &self,
5161 body_def_id: LocalDefId,
5162 err: &mut Diag<'_, G>,
5163 arg_hir_id: HirId,
5164 parent_code: &ObligationCauseCode<'tcx>,
5165 param_env: ty::ParamEnv<'tcx>,
5166 failed_pred: ty::Predicate<'tcx>,
5167 call_hir_id: HirId,
5168 ) {
5169 let tcx = self.tcx;
5170 if let Node::Expr(expr) = tcx.hir_node(arg_hir_id)
5171 && let Some(typeck_results) = &self.typeck_results
5172 {
5173 if let hir::Expr { kind: hir::ExprKind::MethodCall(_, rcvr, _, _), .. } = expr
5174 && let Some(ty) = typeck_results.node_type_opt(rcvr.hir_id)
5175 && let Some(failed_pred) = failed_pred.as_trait_clause()
5176 && let pred = failed_pred.map_bound(|pred| pred.with_replaced_self_ty(tcx, ty))
5177 && self.predicate_must_hold_modulo_regions(&Obligation::misc(
5178 tcx,
5179 expr.span,
5180 body_def_id,
5181 param_env,
5182 pred,
5183 ))
5184 && expr.span.hi() != rcvr.span.hi()
5185 {
5186 let should_sugg = match tcx.hir_node(call_hir_id) {
5187 Node::Expr(hir::Expr {
5188 kind: hir::ExprKind::MethodCall(_, call_receiver, _, _),
5189 ..
5190 }) if let Some((DefKind::AssocFn, did)) =
5191 typeck_results.type_dependent_def(call_hir_id)
5192 && call_receiver.hir_id == arg_hir_id =>
5193 {
5194 if tcx.inherent_impl_of_assoc(did).is_some() {
5198 Some(ty) == typeck_results.node_type_opt(arg_hir_id)
5200 } else {
5201 let trait_id = tcx
5203 .trait_of_assoc(did)
5204 .unwrap_or_else(|| tcx.impl_trait_id(tcx.parent(did)));
5205 let args = typeck_results.node_args(call_hir_id);
5206 let tr = ty::TraitRef::from_assoc(tcx, trait_id, args)
5207 .with_replaced_self_ty(tcx, ty);
5208 self.type_implements_trait(tr.def_id, tr.args, param_env)
5209 .must_apply_modulo_regions()
5210 }
5211 }
5212 _ => true,
5213 };
5214
5215 if should_sugg {
5216 err.span_suggestion_verbose(
5217 expr.span.with_lo(rcvr.span.hi()),
5218 ::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!(
5219 "consider removing this method call, as the receiver has type `{ty}` and \
5220 `{pred}` trivially holds",
5221 ),
5222 "",
5223 Applicability::MaybeIncorrect,
5224 );
5225 }
5226 }
5227 if let hir::Expr { kind: hir::ExprKind::Block(block, _), .. } = expr {
5228 let inner_expr = expr.peel_blocks();
5229 let ty = typeck_results
5230 .expr_ty_adjusted_opt(inner_expr)
5231 .unwrap_or(Ty::new_misc_error(tcx));
5232 let span = inner_expr.span;
5233 if Some(span) != err.span.primary_span()
5234 && !span.in_external_macro(tcx.sess.source_map())
5235 {
5236 err.span_label(
5237 span,
5238 if ty.references_error() {
5239 String::new()
5240 } else {
5241 let ty = { let _guard = ForceTrimmedGuard::new(); self.ty_to_string(ty) }with_forced_trimmed_paths!(self.ty_to_string(ty));
5242 ::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}`")
5243 },
5244 );
5245 if let ty::PredicateKind::Clause(clause) = failed_pred.kind().skip_binder()
5246 && let ty::ClauseKind::Trait(pred) = clause
5247 && tcx.fn_trait_kind_from_def_id(pred.def_id()).is_some()
5248 {
5249 if let [stmt, ..] = block.stmts
5250 && let hir::StmtKind::Semi(value) = stmt.kind
5251 && let hir::ExprKind::Closure(hir::Closure {
5252 body, fn_decl_span, ..
5253 }) = value.kind
5254 && let body = tcx.hir_body(*body)
5255 && !#[allow(non_exhaustive_omitted_patterns)] match body.value.kind {
hir::ExprKind::Block(..) => true,
_ => false,
}matches!(body.value.kind, hir::ExprKind::Block(..))
5256 {
5257 err.multipart_suggestion(
5260 "you might have meant to open the closure body instead of placing \
5261 a closure within a block",
5262 ::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![
5263 (expr.span.with_hi(value.span.lo()), String::new()),
5264 (fn_decl_span.shrink_to_hi(), " {".to_string()),
5265 ],
5266 Applicability::MaybeIncorrect,
5267 );
5268 } else {
5269 err.span_suggestion_verbose(
5271 expr.span.shrink_to_lo(),
5272 "you might have meant to create the closure instead of a block",
5273 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("|{0}| ",
(0..pred.trait_ref.args.len() -
1).map(|_| "_").collect::<Vec<_>>().join(", ")))
})format!(
5274 "|{}| ",
5275 (0..pred.trait_ref.args.len() - 1)
5276 .map(|_| "_")
5277 .collect::<Vec<_>>()
5278 .join(", ")
5279 ),
5280 Applicability::MaybeIncorrect,
5281 );
5282 }
5283 }
5284 }
5285 }
5286
5287 let mut type_diffs = ::alloc::vec::Vec::new()vec![];
5292 if let ObligationCauseCode::WhereClauseInExpr(def_id, _, _, idx) = *parent_code
5293 && let Some(node_args) = typeck_results.node_args_opt(call_hir_id)
5294 && let where_clauses = self.tcx.clauses_of(def_id).instantiate(self.tcx, node_args)
5295 && let Some(where_pred) = where_clauses.clauses.get(idx)
5296 {
5297 let where_pred = where_pred.as_ref().skip_norm_wip();
5298 if let Some(where_pred) = where_pred.as_trait_clause()
5299 && let Some(failed_pred) = failed_pred.as_trait_clause()
5300 && where_pred.def_id() == failed_pred.def_id()
5301 {
5302 self.enter_forall(where_pred, |where_pred| {
5303 let failed_pred = self.instantiate_binder_with_fresh_vars(
5304 expr.span,
5305 BoundRegionConversionTime::FnCall,
5306 failed_pred,
5307 );
5308
5309 let zipped =
5310 iter::zip(where_pred.trait_ref.args, failed_pred.trait_ref.args);
5311 for (expected, actual) in zipped {
5312 self.probe(|_| {
5313 match self
5314 .at(&ObligationCause::misc(expr.span, body_def_id), param_env)
5315 .eq(DefineOpaqueTypes::Yes, expected, actual)
5318 {
5319 Ok(_) => (), Err(err) => type_diffs.push(err),
5321 }
5322 })
5323 }
5324 })
5325 } else if let Some(where_pred) = where_pred.as_projection_clause()
5326 && let Some(failed_pred) = failed_pred.as_projection_clause()
5327 && let Some(found) =
5328 failed_pred.map_bound(|pred| pred.term.as_type()).transpose().map(|term| {
5329 self.instantiate_binder_with_fresh_vars(
5330 expr.span,
5331 BoundRegionConversionTime::FnCall,
5332 term,
5333 )
5334 })
5335 {
5336 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 {
5337 expected: self
5338 .instantiate_binder_with_fresh_vars(
5339 expr.span,
5340 BoundRegionConversionTime::FnCall,
5341 where_pred.map_bound(|pred| pred.projection_term),
5342 )
5343 .expect_ty()
5344 .to_ty(self.tcx, ty::IsRigid::No),
5345 found,
5346 })];
5347 }
5348 }
5349 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
5350 && let hir::Path { res: Res::Local(hir_id), .. } = path
5351 && let hir::Node::Pat(binding) = self.tcx.hir_node(*hir_id)
5352 && let hir::Node::LetStmt(local) = self.tcx.parent_hir_node(binding.hir_id)
5353 && let Some(binding_expr) = local.init
5354 {
5355 self.point_at_chain(binding_expr, typeck_results, type_diffs, param_env, err);
5359 } else {
5360 self.point_at_chain(expr, typeck_results, type_diffs, param_env, err);
5361 }
5362 }
5363 let call_node = tcx.hir_node(call_hir_id);
5364 if let Node::Expr(hir::Expr { kind: hir::ExprKind::MethodCall(path, rcvr, ..), .. }) =
5365 call_node
5366 {
5367 if Some(rcvr.span) == err.span.primary_span() {
5368 err.replace_span_with(path.ident.span, true);
5369 }
5370 }
5371
5372 if let Node::Expr(expr) = call_node {
5373 if let hir::ExprKind::Call(hir::Expr { span, .. }, _)
5374 | hir::ExprKind::MethodCall(
5375 hir::PathSegment { ident: Ident { span, .. }, .. },
5376 ..,
5377 ) = expr.kind
5378 {
5379 if Some(*span) != err.span.primary_span() {
5380 let msg = if span.is_desugaring(DesugaringKind::FormatLiteral { source: true })
5381 {
5382 "required by this formatting parameter"
5383 } else if span.is_desugaring(DesugaringKind::FormatLiteral { source: false }) {
5384 "required by a formatting parameter in this expression"
5385 } else {
5386 "required by a bound introduced by this call"
5387 };
5388 err.span_label(*span, msg);
5389 }
5390 }
5391
5392 if let hir::ExprKind::MethodCall(_, expr, ..) = expr.kind {
5393 self.suggest_option_method_if_applicable(failed_pred, param_env, err, expr);
5394 }
5395 }
5396 }
5397
5398 fn suggest_option_method_if_applicable<G: EmissionGuarantee>(
5399 &self,
5400 failed_pred: ty::Predicate<'tcx>,
5401 param_env: ty::ParamEnv<'tcx>,
5402 err: &mut Diag<'_, G>,
5403 expr: &hir::Expr<'_>,
5404 ) {
5405 let tcx = self.tcx;
5406 let infcx = self.infcx;
5407 let Some(typeck_results) = self.typeck_results.as_ref() else { return };
5408
5409 let Some(option_ty_adt) = typeck_results.expr_ty_adjusted(expr).ty_adt_def() else {
5411 return;
5412 };
5413 if !tcx.is_diagnostic_item(sym::Option, option_ty_adt.did()) {
5414 return;
5415 }
5416
5417 if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(ty::TraitClause { trait_ref, .. }))
5420 = failed_pred.kind().skip_binder()
5421 && tcx.is_fn_trait(trait_ref.def_id)
5422 && let [self_ty, found_ty] = trait_ref.args.as_slice()
5423 && let Some(fn_ty) = self_ty.as_type().filter(|ty| ty.is_fn())
5424 && let fn_sig @ ty::FnSig {
5425 ..
5426 } = fn_ty.fn_sig(tcx).skip_binder()
5427 && fn_sig.abi() == ExternAbi::Rust
5429 && !fn_sig.c_variadic()
5430 && fn_sig.safety() == hir::Safety::Safe
5431
5432 && let Some(&ty::Ref(_, target_ty, needs_mut)) = fn_sig.inputs().first().map(|t| t.kind())
5434 && !target_ty.has_escaping_bound_vars()
5435
5436 && let Some(ty::Tuple(tys)) = found_ty.as_type().map(Ty::kind)
5438 && let &[found_ty] = tys.as_slice()
5439 && !found_ty.has_escaping_bound_vars()
5440
5441 && let Some(deref_target_did) = tcx.lang_items().deref_target()
5443 && let projection = Ty::new_projection_from_args(tcx,ty::IsRigid::No, deref_target_did, tcx.mk_args(&[ty::GenericArg::from(found_ty)]))
5444 && let InferOk { value: deref_target, obligations } = infcx.at(&ObligationCause::dummy(), param_env).normalize(Unnormalized::new_wip(projection))
5445 && obligations.iter().all(|obligation| infcx.predicate_must_hold_modulo_regions(obligation))
5446 && infcx.can_eq(param_env, deref_target, target_ty)
5447 {
5448 let help = if let hir::Mutability::Mut = needs_mut
5449 && let Some(deref_mut_did) = tcx.lang_items().deref_mut_trait()
5450 && infcx
5451 .type_implements_trait(deref_mut_did, iter::once(found_ty), param_env)
5452 .must_apply_modulo_regions()
5453 {
5454 Some(("call `Option::as_deref_mut()` first", ".as_deref_mut()"))
5455 } else if let hir::Mutability::Not = needs_mut {
5456 Some(("call `Option::as_deref()` first", ".as_deref()"))
5457 } else {
5458 None
5459 };
5460
5461 if let Some((msg, sugg)) = help {
5462 err.span_suggestion_with_style(
5463 expr.span.shrink_to_hi(),
5464 msg,
5465 sugg,
5466 Applicability::MaybeIncorrect,
5467 SuggestionStyle::ShowAlways,
5468 );
5469 }
5470 }
5471 }
5472
5473 fn look_for_iterator_item_mistakes<G: EmissionGuarantee>(
5474 &self,
5475 assocs_in_this_method: &[Option<(Span, (DefId, Ty<'tcx>))>],
5476 typeck_results: &TypeckResults<'tcx>,
5477 type_diffs: &[TypeError<'tcx>],
5478 param_env: ty::ParamEnv<'tcx>,
5479 path_segment: &hir::PathSegment<'_>,
5480 args: &[hir::Expr<'_>],
5481 prev_ty: Ty<'_>,
5482 err: &mut Diag<'_, G>,
5483 ) {
5484 let tcx = self.tcx;
5485 for entry in assocs_in_this_method {
5488 let Some((_span, (def_id, ty))) = entry else {
5489 continue;
5490 };
5491 for diff in type_diffs {
5492 let TypeError::Sorts(expected_found) = diff else {
5493 continue;
5494 };
5495 if tcx.is_diagnostic_item(sym::IntoIteratorItem, *def_id)
5496 && path_segment.ident.name == sym::iter
5497 && self.can_eq(
5498 param_env,
5499 Ty::new_ref(
5500 tcx,
5501 tcx.lifetimes.re_erased,
5502 expected_found.found,
5503 ty::Mutability::Not,
5504 ),
5505 *ty,
5506 )
5507 && let [] = args
5508 {
5509 err.span_suggestion_verbose(
5511 path_segment.ident.span,
5512 ::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`"),
5513 "into_iter".to_string(),
5514 Applicability::MachineApplicable,
5515 );
5516 }
5517 if tcx.is_diagnostic_item(sym::IntoIteratorItem, *def_id)
5518 && path_segment.ident.name == sym::into_iter
5519 && self.can_eq(
5520 param_env,
5521 expected_found.found,
5522 Ty::new_ref(tcx, tcx.lifetimes.re_erased, *ty, ty::Mutability::Not),
5523 )
5524 && let [] = args
5525 {
5526 err.span_suggestion_verbose(
5528 path_segment.ident.span,
5529 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider not consuming the `{0}` to construct the `Iterator`",
prev_ty))
})format!(
5530 "consider not consuming the `{prev_ty}` to construct the `Iterator`"
5531 ),
5532 "iter".to_string(),
5533 Applicability::MachineApplicable,
5534 );
5535 }
5536 if tcx.is_diagnostic_item(sym::IteratorItem, *def_id)
5537 && path_segment.ident.name == sym::map
5538 && self.can_eq(param_env, expected_found.found, *ty)
5539 && let [arg] = args
5540 && let hir::ExprKind::Closure(closure) = arg.kind
5541 {
5542 let body = tcx.hir_body(closure.body);
5543 if let hir::ExprKind::Block(block, None) = body.value.kind
5544 && let None = block.expr
5545 && let [.., stmt] = block.stmts
5546 && let hir::StmtKind::Semi(expr) = stmt.kind
5547 && expected_found.found.is_unit()
5551 && expr.span.hi() != stmt.span.hi()
5556 {
5557 err.span_suggestion_verbose(
5558 expr.span.shrink_to_hi().with_hi(stmt.span.hi()),
5559 "consider removing this semicolon",
5560 String::new(),
5561 Applicability::MachineApplicable,
5562 );
5563 }
5564 let expr = if let hir::ExprKind::Block(block, None) = body.value.kind
5565 && let Some(expr) = block.expr
5566 {
5567 expr
5568 } else {
5569 body.value
5570 };
5571 if let hir::ExprKind::MethodCall(path_segment, rcvr, [], span) = expr.kind
5572 && path_segment.ident.name == sym::clone
5573 && let Some(expr_ty) = typeck_results.expr_ty_opt(expr)
5574 && let Some(rcvr_ty) = typeck_results.expr_ty_opt(rcvr)
5575 && self.can_eq(param_env, expr_ty, rcvr_ty)
5576 && let ty::Ref(_, ty, _) = expr_ty.kind()
5577 {
5578 err.span_label(
5579 span,
5580 ::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!(
5581 "this method call is cloning the reference `{expr_ty}`, not \
5582 `{ty}` which doesn't implement `Clone`",
5583 ),
5584 );
5585 let ty::Param(..) = ty.kind() else {
5586 continue;
5587 };
5588 let node =
5589 tcx.hir_node_by_def_id(tcx.hir_get_parent_item(expr.hir_id).def_id);
5590
5591 let pred = ty::Binder::dummy(ty::TraitClause {
5592 trait_ref: ty::TraitRef::new(
5593 tcx,
5594 tcx.require_lang_item(LangItem::Clone, span),
5595 [*ty],
5596 ),
5597 polarity: ty::ClausePolarity::Positive,
5598 });
5599 let Some(generics) = node.generics() else {
5600 continue;
5601 };
5602 let Some(body_id) = node.body_id() else {
5603 continue;
5604 };
5605 suggest_restriction(
5606 tcx,
5607 tcx.hir_body_owner_def_id(body_id),
5608 generics,
5609 &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("type parameter `{0}`", ty))
})format!("type parameter `{ty}`"),
5610 err,
5611 node.fn_sig(),
5612 None,
5613 pred,
5614 None,
5615 );
5616 }
5617 }
5618 }
5619 }
5620 }
5621
5622 fn point_at_chain<G: EmissionGuarantee>(
5623 &self,
5624 expr: &hir::Expr<'_>,
5625 typeck_results: &TypeckResults<'tcx>,
5626 type_diffs: Vec<TypeError<'tcx>>,
5627 param_env: ty::ParamEnv<'tcx>,
5628 err: &mut Diag<'_, G>,
5629 ) {
5630 let mut primary_spans = ::alloc::vec::Vec::new()vec![];
5631 let mut span_labels = ::alloc::vec::Vec::new()vec![];
5632
5633 let tcx = self.tcx;
5634
5635 let mut print_root_expr = true;
5636 let mut assocs = ::alloc::vec::Vec::new()vec![];
5637 let mut expr = expr;
5638 let mut prev_ty = self.resolve_vars_if_possible(
5639 typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(tcx)),
5640 );
5641 while let hir::ExprKind::MethodCall(path_segment, rcvr_expr, args, span) = expr.kind {
5642 expr = rcvr_expr;
5646 let assocs_in_this_method =
5647 self.probe_assoc_types_at_expr(&type_diffs, span, prev_ty, expr.hir_id, param_env);
5648 prev_ty = self.resolve_vars_if_possible(
5649 typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(tcx)),
5650 );
5651 self.look_for_iterator_item_mistakes(
5652 &assocs_in_this_method,
5653 typeck_results,
5654 &type_diffs,
5655 param_env,
5656 path_segment,
5657 args,
5658 prev_ty,
5659 err,
5660 );
5661 assocs.push(assocs_in_this_method);
5662
5663 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
5664 && let hir::Path { res: Res::Local(hir_id), .. } = path
5665 && let hir::Node::Pat(binding) = self.tcx.hir_node(*hir_id)
5666 {
5667 let parent = self.tcx.parent_hir_node(binding.hir_id);
5668 if let hir::Node::LetStmt(local) = parent
5670 && let Some(binding_expr) = local.init
5671 {
5672 expr = binding_expr;
5674 }
5675 if let hir::Node::Param(param) = parent {
5676 let prev_ty = self.resolve_vars_if_possible(
5678 typeck_results
5679 .node_type_opt(param.hir_id)
5680 .unwrap_or(Ty::new_misc_error(tcx)),
5681 );
5682 let assocs_in_this_method = self.probe_assoc_types_at_expr(
5683 &type_diffs,
5684 param.ty_span,
5685 prev_ty,
5686 param.hir_id,
5687 param_env,
5688 );
5689 if assocs_in_this_method.iter().any(|a| a.is_some()) {
5690 assocs.push(assocs_in_this_method);
5691 print_root_expr = false;
5692 }
5693 break;
5694 }
5695 }
5696 }
5697 if let Some(ty) = typeck_results.expr_ty_opt(expr)
5700 && print_root_expr
5701 {
5702 let ty = { let _guard = ForceTrimmedGuard::new(); self.ty_to_string(ty) }with_forced_trimmed_paths!(self.ty_to_string(ty));
5703 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}`")));
5707 };
5708 let mut assocs = assocs.into_iter().peekable();
5711 while let Some(assocs_in_method) = assocs.next() {
5712 let Some(prev_assoc_in_method) = assocs.peek() else {
5713 for entry in assocs_in_method {
5714 let Some((span, (assoc, ty))) = entry else {
5715 continue;
5716 };
5717 if primary_spans.is_empty()
5718 || type_diffs.iter().any(|diff| {
5719 let TypeError::Sorts(expected_found) = diff else {
5720 return false;
5721 };
5722 self.can_eq(param_env, expected_found.found, ty)
5723 })
5724 {
5725 primary_spans.push(span);
5731 }
5732 span_labels.push((
5733 span,
5734 {
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!(
5735 "`{}` is `{ty}` here",
5736 self.tcx.def_path_str(assoc),
5737 )),
5738 ));
5739 }
5740 break;
5741 };
5742 for (entry, prev_entry) in
5743 assocs_in_method.into_iter().zip(prev_assoc_in_method.into_iter())
5744 {
5745 match (entry, prev_entry) {
5746 (Some((span, (assoc, ty))), Some((_, (_, prev_ty)))) => {
5747 let ty_str = { let _guard = ForceTrimmedGuard::new(); self.ty_to_string(ty) }with_forced_trimmed_paths!(self.ty_to_string(ty));
5748
5749 let assoc = { let _guard = ForceTrimmedGuard::new(); self.tcx.def_path_str(assoc) }with_forced_trimmed_paths!(self.tcx.def_path_str(assoc));
5750 if !self.can_eq(param_env, ty, *prev_ty) {
5751 if type_diffs.iter().any(|diff| {
5752 let TypeError::Sorts(expected_found) = diff else {
5753 return false;
5754 };
5755 self.can_eq(param_env, expected_found.found, ty)
5756 }) {
5757 primary_spans.push(span);
5758 }
5759 span_labels
5760 .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")));
5761 } else {
5762 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")));
5763 }
5764 }
5765 (Some((span, (assoc, ty))), None) => {
5766 span_labels.push((
5767 span,
5768 {
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!(
5769 "`{}` is `{}` here",
5770 self.tcx.def_path_str(assoc),
5771 self.ty_to_string(ty),
5772 )),
5773 ));
5774 }
5775 (None, Some(_)) | (None, None) => {}
5776 }
5777 }
5778 }
5779 if !primary_spans.is_empty() {
5780 let mut multi_span: MultiSpan = primary_spans.into();
5781 for (span, label) in span_labels {
5782 multi_span.push_span_label(span, label);
5783 }
5784 err.span_note(
5785 multi_span,
5786 "the method call chain might not have had the expected associated types",
5787 );
5788 }
5789 }
5790
5791 fn probe_assoc_types_at_expr(
5792 &self,
5793 type_diffs: &[TypeError<'tcx>],
5794 span: Span,
5795 prev_ty: Ty<'tcx>,
5796 body_id: HirId,
5797 param_env: ty::ParamEnv<'tcx>,
5798 ) -> Vec<Option<(Span, (DefId, Ty<'tcx>))>> {
5799 let ocx = ObligationCtxt::new(self.infcx);
5800 let mut assocs_in_this_method = Vec::with_capacity(type_diffs.len());
5801 for diff in type_diffs {
5802 let TypeError::Sorts(expected_found) = diff else {
5803 continue;
5804 };
5805 let &ty::Alias(_, ty::AliasTy { kind: kind @ ty::Projection { def_id }, .. }) =
5806 expected_found.expected.kind()
5807 else {
5808 continue;
5809 };
5810
5811 let args = GenericArgs::for_item(self.tcx, def_id, |param, _| {
5815 if param.index == 0 {
5816 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 { .. });
5817 return prev_ty.into();
5818 }
5819 self.var_for_def(span, param)
5820 });
5821 let ty = self.infcx.next_ty_var(span);
5825 let projection = ty::Binder::dummy(ty::PredicateKind::Clause(
5827 ty::ClauseKind::Projection(ty::ProjectionClause {
5828 projection_term: ty::AliasTerm::new_from_args(self.tcx, kind.into(), args),
5829 term: ty.into(),
5830 }),
5831 ));
5832 let body_def_id = self.tcx.hir_enclosing_body_owner(body_id);
5833 ocx.register_obligation(Obligation::misc(
5835 self.tcx,
5836 span,
5837 body_def_id,
5838 param_env,
5839 projection,
5840 ));
5841 if ocx.try_evaluate_obligations().no_errors()
5842 && let ty = self.resolve_vars_if_possible(ty)
5843 && !ty.is_ty_var()
5844 {
5845 assocs_in_this_method.push(Some((span, (def_id, ty))));
5846 } else {
5847 assocs_in_this_method.push(None);
5852 }
5853 }
5854 assocs_in_this_method
5855 }
5856
5857 fn point_at_chain_in_return_position<G: EmissionGuarantee>(
5872 &self,
5873 body_def_id: LocalDefId,
5874 expr: &hir::Expr<'_>,
5875 typeck_results: &TypeckResults<'tcx>,
5876 param_env: ty::ParamEnv<'tcx>,
5877 err: &mut Diag<'_, G>,
5878 ) {
5879 let tcx = self.tcx;
5880 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) {
5881 return;
5882 }
5883
5884 let binder = tcx.fn_sig(body_def_id).instantiate_identity().skip_norm_wip().output();
5885 self.enter_forall(binder, |output| {
5886 let &ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id: opaque_def_id }, args, .. }) =
5887 output.kind()
5888 else {
5889 return;
5890 };
5891
5892 let mut probe_diffs = ::alloc::vec::Vec::new()vec![];
5897 for clause in tcx.item_bounds(opaque_def_id).instantiate(tcx, args).skip_norm_wip() {
5898 let Some(proj) = clause.as_projection_clause() else { continue };
5899 let proj = self.instantiate_binder_with_fresh_vars(
5900 expr.span,
5901 BoundRegionConversionTime::FnCall,
5902 proj,
5903 );
5904 let Some(expected_term) = proj.term.as_type() else { continue };
5905 probe_diffs.push(TypeError::Sorts(ty::error::ExpectedFound {
5909 expected: proj.projection_term.expect_ty().to_ty(tcx, ty::IsRigid::No),
5910 found: expected_term,
5911 }));
5912 }
5913 if probe_diffs.is_empty() {
5914 return;
5915 }
5916
5917 let expr = if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
5919 && let hir::Path { res: Res::Local(hir_id), .. } = path
5920 && let hir::Node::Pat(binding) = tcx.hir_node(*hir_id)
5921 && let hir::Node::LetStmt(local) = tcx.parent_hir_node(binding.hir_id)
5922 && let Some(binding_expr) = local.init
5923 {
5924 binding_expr
5925 } else {
5926 expr
5927 };
5928
5929 let expr_ty = self.resolve_vars_if_possible(
5932 typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(tcx)),
5933 );
5934 let assocs = self.probe_assoc_types_at_expr(
5935 &probe_diffs,
5936 expr.span,
5937 expr_ty,
5938 expr.hir_id,
5939 param_env,
5940 );
5941 let mut type_diffs = ::alloc::vec::Vec::new()vec![];
5942 for (probe_diff, assoc) in iter::zip(probe_diffs, assocs) {
5943 let TypeError::Sorts(ty::error::ExpectedFound { expected, found: expected_term }) =
5944 probe_diff
5945 else {
5946 continue;
5947 };
5948 let Some((_, (_, actual_ty))) = assoc else { continue };
5949 if !self.can_eq(param_env, expected_term, actual_ty) {
5950 type_diffs.push(TypeError::Sorts(ty::error::ExpectedFound {
5951 expected,
5952 found: actual_ty,
5953 }));
5954 }
5955 }
5956 if !type_diffs.is_empty() {
5957 self.point_at_chain(expr, typeck_results, type_diffs, param_env, err);
5958 }
5959 });
5960 }
5961
5962 pub(super) fn suggest_convert_to_slice(
5966 &self,
5967 err: &mut Diag<'_>,
5968 obligation: &PredicateObligation<'tcx>,
5969 trait_pred: ty::PolyTraitClause<'tcx>,
5970 candidate_impls: &[ImplCandidate<'tcx>],
5971 span: Span,
5972 ) {
5973 if span.in_external_macro(self.tcx.sess.source_map()) {
5974 return;
5975 }
5976 let (ObligationCauseCode::BinOp { .. } | ObligationCauseCode::FunctionArg { .. }) =
5979 obligation.cause.code()
5980 else {
5981 return;
5982 };
5983
5984 let (element_ty, mut mutability) = match *trait_pred.skip_binder().self_ty().kind() {
5989 ty::Array(element_ty, _) => (element_ty, None),
5990
5991 ty::Ref(_, pointee_ty, mutability) => match *pointee_ty.kind() {
5992 ty::Array(element_ty, _) => (element_ty, Some(mutability)),
5993 _ => return,
5994 },
5995
5996 _ => return,
5997 };
5998
5999 let mut is_slice = |candidate: Ty<'tcx>| match *candidate.kind() {
6002 ty::RawPtr(t, m) | ty::Ref(_, t, m) => {
6003 if let ty::Slice(e) = *t.kind()
6004 && e == element_ty
6005 && m == mutability.unwrap_or(m)
6006 {
6007 mutability = Some(m);
6009 true
6010 } else {
6011 false
6012 }
6013 }
6014 _ => false,
6015 };
6016
6017 if let Some(slice_ty) = candidate_impls
6019 .iter()
6020 .map(|trait_ref| trait_ref.trait_ref.self_ty())
6021 .find(|t| is_slice(*t))
6022 {
6023 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");
6024
6025 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
6026 let mut suggestions = ::alloc::vec::Vec::new()vec![];
6027 if snippet.starts_with('&') {
6028 } else if let Some(hir::Mutability::Mut) = mutability {
6029 suggestions.push((span.shrink_to_lo(), "&mut ".into()));
6030 } else {
6031 suggestions.push((span.shrink_to_lo(), "&".into()));
6032 }
6033 suggestions.push((span.shrink_to_hi(), "[..]".into()));
6034 err.multipart_suggestion(msg, suggestions, Applicability::MaybeIncorrect);
6035 } else {
6036 err.span_help(span, msg);
6037 }
6038 }
6039 }
6040
6041 pub(super) fn suggest_tuple_wrapping(
6046 &self,
6047 err: &mut Diag<'_>,
6048 root_obligation: &PredicateObligation<'tcx>,
6049 obligation: &PredicateObligation<'tcx>,
6050 ) {
6051 let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code() else {
6052 return;
6053 };
6054
6055 let Some(root_pred) = root_obligation.predicate.as_trait_clause() else { return };
6056
6057 let trait_ref = root_pred.map_bound(|root_pred| {
6058 root_pred.trait_ref.with_replaced_self_ty(
6059 self.tcx,
6060 Ty::new_tup(self.tcx, &[root_pred.trait_ref.self_ty()]),
6061 )
6062 });
6063
6064 let obligation =
6065 Obligation::new(self.tcx, obligation.cause.clone(), obligation.param_env, trait_ref);
6066
6067 if self.predicate_must_hold_modulo_regions(&obligation) {
6068 let arg_span = self.tcx.hir_span(*arg_hir_id);
6069 err.multipart_suggestion(
6070 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use a unary tuple instead"))
})format!("use a unary tuple instead"),
6071 ::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())],
6072 Applicability::MaybeIncorrect,
6073 );
6074 }
6075 }
6076
6077 pub(super) fn suggest_shadowed_inherent_method(
6078 &self,
6079 err: &mut Diag<'_>,
6080 obligation: &PredicateObligation<'tcx>,
6081 trait_predicate: ty::PolyTraitClause<'tcx>,
6082 ) {
6083 let ObligationCauseCode::FunctionArg { call_hir_id, .. } = obligation.cause.code() else {
6084 return;
6085 };
6086 let Node::Expr(call) = self.tcx.hir_node(*call_hir_id) else { return };
6087 let hir::ExprKind::MethodCall(segment, rcvr, args, ..) = call.kind else { return };
6088 let Some(typeck) = &self.typeck_results else { return };
6089 let Some(rcvr_ty) = typeck.expr_ty_adjusted_opt(rcvr) else { return };
6090 let rcvr_ty = self.resolve_vars_if_possible(rcvr_ty);
6091 let autoderef = (self.autoderef_steps)(rcvr_ty);
6092 for (ty, def_id) in autoderef.iter().filter_map(|(ty, obligations)| {
6093 if let ty::Adt(def, _) = ty.kind()
6094 && *ty != rcvr_ty.peel_refs()
6095 && obligations.iter().all(|obligation| self.predicate_may_hold(obligation))
6096 {
6097 Some((ty, def.did()))
6098 } else {
6099 None
6100 }
6101 }) {
6102 for impl_def_id in self.tcx.inherent_impls(def_id) {
6103 if *impl_def_id == trait_predicate.def_id() {
6104 continue;
6105 }
6106 for m in self
6107 .tcx
6108 .provided_trait_methods(*impl_def_id)
6109 .filter(|m| m.name() == segment.ident.name)
6110 {
6111 let fn_sig = self.tcx.fn_sig(m.def_id);
6112 if fn_sig.skip_binder().inputs().skip_binder().len() != args.len() + 1 {
6113 continue;
6114 }
6115 let rcvr_ty = fn_sig.skip_binder().input(0).skip_binder();
6116 let (mutability, _ty) = match rcvr_ty.kind() {
6117 ty::Ref(_, ty, hir::Mutability::Mut) => ("&mut ", ty),
6118 ty::Ref(_, ty, _) => ("&", ty),
6119 _ => ("", &rcvr_ty),
6120 };
6121 let path = self.tcx.def_path_str(def_id);
6122 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!(
6123 "there's an inherent method on `{ty}` of the same name, which can be \
6124 auto-dereferenced from `{rcvr_ty}`"
6125 ));
6126 err.multipart_suggestion(
6127 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("to access the inherent method on `{0}`, use the fully-qualified path",
ty))
})format!(
6128 "to access the inherent method on `{ty}`, use the fully-qualified path",
6129 ),
6130 ::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![
6131 (
6132 call.span.until(rcvr.span),
6133 format!("{path}::{}({}", m.name(), mutability),
6134 ),
6135 match &args {
6136 [] => (
6137 rcvr.span.shrink_to_hi().with_hi(call.span.hi()),
6138 ")".to_string(),
6139 ),
6140 [first, ..] => (rcvr.span.between(first.span), ", ".to_string()),
6141 },
6142 ],
6143 Applicability::MaybeIncorrect,
6144 );
6145 }
6146 }
6147 }
6148 }
6149
6150 pub(super) fn explain_hrtb_projection(
6151 &self,
6152 diag: &mut Diag<'_>,
6153 pred: ty::PolyTraitClause<'tcx>,
6154 param_env: ty::ParamEnv<'tcx>,
6155 cause: &ObligationCause<'tcx>,
6156 ) {
6157 if pred.skip_binder().has_escaping_bound_vars() && pred.skip_binder().has_non_region_infer()
6158 {
6159 self.probe(|_| {
6160 let ocx = ObligationCtxt::new(self);
6161 ocx.register_obligation(Obligation::new(
6162 self.tcx,
6163 ObligationCause::dummy(),
6164 param_env,
6165 pred,
6166 ));
6167 if !ocx.try_evaluate_obligations().no_errors() {
6168 return;
6170 }
6171
6172 if let ObligationCauseCode::FunctionArg {
6173 call_hir_id,
6174 arg_hir_id,
6175 parent_code: _,
6176 } = cause.code()
6177 {
6178 let arg_span = self.tcx.hir_span(*arg_hir_id);
6179 let mut sp: MultiSpan = arg_span.into();
6180
6181 sp.push_span_label(
6182 arg_span,
6183 "the trait solver is unable to infer the \
6184 generic types that should be inferred from this argument",
6185 );
6186 sp.push_span_label(
6187 self.tcx.hir_span(*call_hir_id),
6188 "add turbofish arguments to this call to \
6189 specify the types manually, even if it's redundant",
6190 );
6191 diag.span_note(
6192 sp,
6193 "this is a known limitation of the trait solver that \
6194 will be lifted in the future",
6195 );
6196 } else {
6197 let mut sp: MultiSpan = cause.span.into();
6198 sp.push_span_label(
6199 cause.span,
6200 "try adding turbofish arguments to this expression to \
6201 specify the types manually, even if it's redundant",
6202 );
6203 diag.span_note(
6204 sp,
6205 "this is a known limitation of the trait solver that \
6206 will be lifted in the future",
6207 );
6208 }
6209 });
6210 }
6211 }
6212
6213 pub(super) fn suggest_desugaring_async_fn_in_trait(
6214 &self,
6215 err: &mut Diag<'_>,
6216 trait_pred: ty::PolyTraitClause<'tcx>,
6217 ) {
6218 if self.tcx.features().return_type_notation() {
6220 return;
6221 }
6222
6223 let trait_def_id = trait_pred.def_id();
6224
6225 if !self.tcx.trait_is_auto(trait_def_id) {
6227 return;
6228 }
6229
6230 let ty::Alias(_, alias_ty @ ty::AliasTy { kind: ty::Projection { def_id }, .. }) =
6232 trait_pred.self_ty().skip_binder().kind()
6233 else {
6234 return;
6235 };
6236 let Some(ty::ImplTraitInTraitData::Trait { fn_def_id, opaque_def_id }) =
6237 self.tcx.opt_rpitit_info(*def_id)
6238 else {
6239 return;
6240 };
6241
6242 let auto_trait = self.tcx.def_path_str(trait_def_id);
6243 let Some(fn_def_id) = fn_def_id.as_local() else {
6245 if self.tcx.asyncness(fn_def_id).is_async() {
6247 err.span_note(
6248 self.tcx.def_span(fn_def_id),
6249 ::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!(
6250 "`{}::{}` is an `async fn` in trait, which does not \
6251 automatically imply that its future is `{auto_trait}`",
6252 alias_ty.trait_ref(self.tcx),
6253 self.tcx.item_name(fn_def_id)
6254 ),
6255 );
6256 }
6257 return;
6258 };
6259 let hir::Node::TraitItem(item) = self.tcx.hir_node_by_def_id(fn_def_id) else {
6260 return;
6261 };
6262
6263 let (sig, body) = item.expect_fn();
6265 let hir::FnRetTy::Return(hir::Ty { kind: hir::TyKind::OpaqueDef(opaq_def, ..), .. }) =
6266 sig.decl.output
6267 else {
6268 return;
6270 };
6271
6272 if opaq_def.def_id.to_def_id() != opaque_def_id {
6275 return;
6276 }
6277
6278 let Some(sugg) = suggest_desugaring_async_fn_to_impl_future_in_trait(
6279 self.tcx,
6280 *sig,
6281 *body,
6282 opaque_def_id.expect_local(),
6283 &::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" + {0}", auto_trait))
})format!(" + {auto_trait}"),
6284 ) else {
6285 return;
6286 };
6287
6288 let function_name = self.tcx.def_path_str(fn_def_id);
6289 err.multipart_suggestion(
6290 ::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!(
6291 "`{auto_trait}` can be made part of the associated future's \
6292 guarantees for all implementations of `{function_name}`"
6293 ),
6294 sugg,
6295 Applicability::MachineApplicable,
6296 );
6297 }
6298
6299 pub fn ty_kind_suggestion(
6300 &self,
6301 param_env: ty::ParamEnv<'tcx>,
6302 ty: Ty<'tcx>,
6303 ) -> Option<String> {
6304 let tcx = self.infcx.tcx;
6305 let implements_default = |ty| {
6306 let Some(default_trait) = tcx.get_diagnostic_item(sym::Default) else {
6307 return false;
6308 };
6309 self.type_implements_trait(default_trait, [ty], param_env).must_apply_modulo_regions()
6310 };
6311
6312 Some(match *ty.kind() {
6313 ty::Never | ty::Error(_) => return None,
6314 ty::Bool => "false".to_string(),
6315 ty::Char => "\'x\'".to_string(),
6316 ty::Int(_) | ty::Uint(_) => "42".into(),
6317 ty::Float(_) => "3.14159".into(),
6318 ty::Slice(_) => "[]".to_string(),
6319 ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::Vec) => {
6320 "vec![]".to_string()
6321 }
6322 ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::String) => {
6323 "String::new()".to_string()
6324 }
6325 ty::Adt(def, args) if def.is_box() => {
6326 ::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())?)
6327 }
6328 ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::Option) => {
6329 "None".to_string()
6330 }
6331 ty::Adt(def, args) if Some(def.did()) == tcx.get_diagnostic_item(sym::Result) => {
6332 ::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())?)
6333 }
6334 ty::Adt(_, _) if implements_default(ty) => "Default::default()".to_string(),
6335 ty::Ref(_, ty, mutability) => {
6336 if let (ty::Str, hir::Mutability::Not) = (ty.kind(), mutability) {
6337 "\"\"".to_string()
6338 } else {
6339 let ty = self.ty_kind_suggestion(param_env, ty)?;
6340 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&{0}{1}", mutability.prefix_str(),
ty))
})format!("&{}{ty}", mutability.prefix_str())
6341 }
6342 }
6343 ty::Array(ty, len) if let Some(len) = len.try_to_target_usize(tcx) => {
6344 if len == 0 {
6345 "[]".to_string()
6346 } else if self.type_is_copy_modulo_regions(param_env, ty) || len == 1 {
6347 ::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)
6349 } else {
6350 "/* value */".to_string()
6351 }
6352 }
6353 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!(
6354 "({}{})",
6355 tys.iter()
6356 .map(|ty| self.ty_kind_suggestion(param_env, ty))
6357 .collect::<Option<Vec<String>>>()?
6358 .join(", "),
6359 if tys.len() == 1 { "," } else { "" }
6360 ),
6361 _ => "/* value */".to_string(),
6362 })
6363 }
6364
6365 pub(super) fn suggest_add_result_as_return_type(
6369 &self,
6370 obligation: &PredicateObligation<'tcx>,
6371 err: &mut Diag<'_>,
6372 trait_pred: ty::PolyTraitClause<'tcx>,
6373 ) {
6374 if ObligationCauseCode::QuestionMark != *obligation.cause.code().peel_derives() {
6375 return;
6376 }
6377
6378 fn choose_suggest_items<'tcx, 'hir>(
6385 tcx: TyCtxt<'tcx>,
6386 node: hir::Node<'hir>,
6387 ) -> Option<(&'hir hir::FnDecl<'hir>, hir::BodyId)> {
6388 match node {
6389 hir::Node::Item(item)
6390 if let hir::ItemKind::Fn { sig, body: body_id, .. } = item.kind =>
6391 {
6392 Some((sig.decl, body_id))
6393 }
6394 hir::Node::ImplItem(item)
6395 if let hir::ImplItemKind::Fn(sig, body_id) = item.kind =>
6396 {
6397 let parent = tcx.parent_hir_node(item.hir_id());
6398 if let hir::Node::Item(item) = parent
6399 && let hir::ItemKind::Impl(imp) = item.kind
6400 && imp.of_trait.is_none()
6401 {
6402 return Some((sig.decl, body_id));
6403 }
6404 None
6405 }
6406 _ => None,
6407 }
6408 }
6409
6410 let node = self.tcx.hir_node_by_def_id(obligation.cause.body_def_id);
6411 if let Some((fn_decl, body_id)) = choose_suggest_items(self.tcx, node)
6412 && let hir::FnRetTy::DefaultReturn(ret_span) = fn_decl.output
6413 && self.tcx.is_diagnostic_item(sym::FromResidual, trait_pred.def_id())
6414 && trait_pred.skip_binder().trait_ref.args.type_at(0).is_unit()
6415 && let ty::Adt(def, _) = trait_pred.skip_binder().trait_ref.args.type_at(1).kind()
6416 && self.tcx.is_diagnostic_item(sym::Result, def.did())
6417 {
6418 let mut sugg_spans =
6419 ::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())];
6420 let body = self.tcx.hir_body(body_id);
6421 if let hir::ExprKind::Block(b, _) = body.value.kind
6422 && b.expr.is_none()
6423 {
6424 let span = self.tcx.sess.source_map().end_point(b.span);
6426 sugg_spans.push((
6427 span.shrink_to_lo(),
6428 ::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!(
6429 "{}{}",
6430 " Ok(())\n",
6431 self.tcx.sess.source_map().indentation_before(span).unwrap_or_default(),
6432 ),
6433 ));
6434 }
6435 err.multipart_suggestion(
6436 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider adding return type"))
})format!("consider adding return type"),
6437 sugg_spans,
6438 Applicability::MaybeIncorrect,
6439 );
6440 }
6441 }
6442
6443 {}
#[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("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(6443u32),
::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 /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:6463",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(6463u32),
::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 /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:6476",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(6476u32),
::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 /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:6477",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(6477u32),
::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 /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:6490",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(6490u32),
::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)]
6444 pub(super) fn suggest_unsized_bound_if_applicable(
6445 &self,
6446 err: &mut Diag<'_>,
6447 obligation: &PredicateObligation<'tcx>,
6448 ) {
6449 let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
6450 obligation.predicate.kind().skip_binder()
6451 else {
6452 return;
6453 };
6454 let (ObligationCauseCode::WhereClause(item_def_id, span)
6455 | ObligationCauseCode::WhereClauseInExpr(item_def_id, span, ..)) =
6456 *obligation.cause.code().peel_derives()
6457 else {
6458 return;
6459 };
6460 if span.is_dummy() {
6461 return;
6462 }
6463 debug!(?pred, ?item_def_id, ?span);
6464
6465 let (Some(node), true) = (
6466 self.tcx.hir_get_if_local(item_def_id),
6467 self.tcx.is_lang_item(pred.def_id(), LangItem::Sized),
6468 ) else {
6469 return;
6470 };
6471
6472 let Some(generics) = node.generics() else {
6473 return;
6474 };
6475 let sized_trait = self.tcx.lang_items().sized_trait();
6476 debug!(?generics.params);
6477 debug!(?generics.predicates);
6478 let Some(param) = generics.params.iter().find(|param| param.span == span) else {
6479 return;
6480 };
6481 let explicitly_sized = generics
6484 .bounds_for_param(param.def_id)
6485 .flat_map(|bp| bp.bounds)
6486 .any(|bound| bound.trait_ref().and_then(|tr| tr.trait_def_id()) == sized_trait);
6487 if explicitly_sized {
6488 return;
6489 }
6490 debug!(?param);
6491 match node {
6492 hir::Node::Item(
6493 item @ hir::Item {
6494 kind:
6496 hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) | hir::ItemKind::Union(..),
6497 ..
6498 },
6499 ) => {
6500 if self.suggest_indirection_for_unsized(err, item, param) {
6501 return;
6502 }
6503 }
6504 _ => {}
6505 };
6506
6507 let (span, separator, open_paren_sp) =
6509 if let Some((s, open_paren_sp)) = generics.bounds_span_for_suggestions(param.def_id) {
6510 (s, " +", open_paren_sp)
6511 } else {
6512 (param.name.ident().span.shrink_to_hi(), ":", None)
6513 };
6514
6515 let mut suggs = vec![];
6516 let suggestion = format!("{separator} ?Sized");
6517
6518 if let Some(open_paren_sp) = open_paren_sp {
6519 suggs.push((open_paren_sp, "(".to_string()));
6520 suggs.push((span, format!("){suggestion}")));
6521 } else {
6522 suggs.push((span, suggestion));
6523 }
6524
6525 err.multipart_suggestion(
6526 "consider relaxing the implicit `Sized` restriction",
6527 suggs,
6528 Applicability::MachineApplicable,
6529 );
6530 }
6531
6532 fn suggest_indirection_for_unsized(
6533 &self,
6534 err: &mut Diag<'_>,
6535 item: &hir::Item<'tcx>,
6536 param: &hir::GenericParam<'tcx>,
6537 ) -> bool {
6538 let mut visitor = FindTypeParam { param: param.name.ident().name, .. };
6542 visitor.visit_item(item);
6543 if visitor.invalid_spans.is_empty() {
6544 return false;
6545 }
6546 let mut multispan: MultiSpan = param.span.into();
6547 multispan.push_span_label(
6548 param.span,
6549 ::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()),
6550 );
6551 for sp in visitor.invalid_spans {
6552 multispan.push_span_label(
6553 sp,
6554 ::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()),
6555 );
6556 }
6557 err.span_help(
6558 multispan,
6559 ::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!(
6560 "you could relax the implicit `Sized` bound on `{T}` if it were \
6561 used through indirection like `&{T}` or `Box<{T}>`",
6562 T = param.name.ident(),
6563 ),
6564 );
6565 true
6566 }
6567 pub(crate) fn suggest_swapping_lhs_and_rhs<T>(
6568 &self,
6569 err: &mut Diag<'_>,
6570 predicate: T,
6571 param_env: ty::ParamEnv<'tcx>,
6572 cause_code: &ObligationCauseCode<'tcx>,
6573 ) where
6574 T: Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>>,
6575 {
6576 let tcx = self.tcx;
6577 let predicate = predicate.upcast(tcx);
6578 match *cause_code {
6579 ObligationCauseCode::BinOp { lhs_hir_id, rhs_hir_id, rhs_span, .. }
6580 if let Some(typeck_results) = &self.typeck_results
6581 && let hir::Node::Expr(lhs) = tcx.hir_node(lhs_hir_id)
6582 && let hir::Node::Expr(rhs) = tcx.hir_node(rhs_hir_id)
6583 && let Some(lhs_ty) = typeck_results.expr_ty_opt(lhs)
6584 && let Some(rhs_ty) = typeck_results.expr_ty_opt(rhs) =>
6585 {
6586 if let Some(pred) = predicate.as_trait_clause()
6587 && tcx.is_lang_item(pred.def_id(), LangItem::PartialEq)
6588 && self
6589 .infcx
6590 .type_implements_trait(pred.def_id(), [rhs_ty, lhs_ty], param_env)
6591 .must_apply_modulo_regions()
6592 {
6593 let lhs_span = tcx.hir_span(lhs_hir_id);
6594 let sm = tcx.sess.source_map();
6595 if let Ok(rhs_snippet) = sm.span_to_snippet(rhs_span)
6596 && let Ok(lhs_snippet) = sm.span_to_snippet(lhs_span)
6597 {
6598 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}>`"));
6599 err.multipart_suggestion(
6600 "consider swapping the equality",
6601 ::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)],
6602 Applicability::MaybeIncorrect,
6603 );
6604 }
6605 }
6606 }
6607 _ => {}
6608 }
6609 }
6610
6611 fn is_truly_imperfect_derive(
6614 &self,
6615 parent_trait_pred: ty::PolyTraitClause<'tcx>,
6616 predicate: ty::Predicate<'tcx>,
6617 param_env: ty::ParamEnv<'tcx>,
6618 ) -> bool {
6619 let tcx = self.tcx;
6620 let ty::Adt(adt_def, parent_args) = parent_trait_pred.skip_binder().self_ty().kind() else {
6621 return false;
6622 };
6623 let Some(trait_clause) = predicate.as_trait_clause() else {
6624 return false;
6625 };
6626 let failing_ty = trait_clause.skip_binder().self_ty();
6627 let trait_def_id = parent_trait_pred.def_id();
6628
6629 let failing_adt_param_indices: FxHashSet<u32> = parent_args
6630 .iter()
6631 .enumerate()
6632 .filter_map(|(idx, arg)| {
6633 if let Some(t) = arg.as_type()
6634 && t == failing_ty
6635 {
6636 Some(idx as u32)
6637 } else {
6638 None
6639 }
6640 })
6641 .collect();
6642
6643 if failing_adt_param_indices.is_empty() {
6644 return false;
6645 }
6646
6647 adt_def.all_fields().all(|field| {
6648 let raw_field_ty = tcx.type_of(field.did).skip_binder();
6649 if let ty::Param(p) = raw_field_ty.kind()
6651 && failing_adt_param_indices.contains(&p.index)
6652 {
6653 return false;
6654 }
6655 if !raw_field_ty.walk().any(|arg| {
6657 #[allow(non_exhaustive_omitted_patterns)] match arg.as_type().map(|t|
t.kind()) {
Some(ty::Param(p)) if failing_adt_param_indices.contains(&p.index) =>
true,
_ => false,
}matches!(arg.as_type().map(|t| t.kind()), Some(ty::Param(p)) if failing_adt_param_indices.contains(&p.index))
6658 }) {
6659 return true;
6660 }
6661
6662 self.probe(|_| {
6663 let fresh_args = ty::GenericArgs::for_item(tcx, adt_def.did(), |param, _| {
6666 if failing_adt_param_indices.contains(¶m.index) {
6667 self.var_for_def(DUMMY_SP, param)
6668 } else {
6669 parent_args[param.index as usize]
6670 }
6671 });
6672
6673 let field_ty = field.ty(tcx, fresh_args).skip_norm_wip();
6674 let parent_trait_args = parent_trait_pred.skip_binder().trait_ref.args;
6677 let trait_args = parent_trait_args.iter().map(|arg| {
6678 if arg.as_type() == Some(parent_trait_pred.skip_binder().self_ty()) {
6679 field_ty.into()
6680 } else {
6681 arg
6682 }
6683 });
6684 let obligation = Obligation::new(
6685 tcx,
6686 ObligationCause::dummy(),
6687 param_env,
6688 ty::TraitRef::new(tcx, trait_def_id, trait_args),
6689 );
6690 self.predicate_may_hold(&obligation)
6691 })
6692 })
6693 }
6694}
6695
6696fn hint_missing_borrow<'tcx>(
6698 infcx: &InferCtxt<'tcx>,
6699 param_env: ty::ParamEnv<'tcx>,
6700 span: Span,
6701 found: Ty<'tcx>,
6702 expected: Ty<'tcx>,
6703 found_node: Node<'_>,
6704 err: &mut Diag<'_>,
6705) {
6706 if #[allow(non_exhaustive_omitted_patterns)] match found_node {
Node::TraitItem(..) => true,
_ => false,
}matches!(found_node, Node::TraitItem(..)) {
6707 return;
6708 }
6709
6710 let found_args = match found.kind() {
6711 ty::FnPtr(sig_tys, _) => infcx.enter_forall(*sig_tys, |sig_tys| sig_tys.inputs().iter()),
6712 kind => {
6713 ::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)
6714 }
6715 };
6716 let expected_args = match expected.kind() {
6717 ty::FnPtr(sig_tys, _) => infcx.enter_forall(*sig_tys, |sig_tys| sig_tys.inputs().iter()),
6718 kind => {
6719 ::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)
6720 }
6721 };
6722
6723 let Some(fn_decl) = found_node.fn_decl() else {
6725 return;
6726 };
6727
6728 let args = fn_decl.inputs.iter();
6729
6730 let mut to_borrow = Vec::new();
6731 let mut remove_borrow = Vec::new();
6732
6733 for ((found_arg, expected_arg), arg) in found_args.zip(expected_args).zip(args) {
6734 let (found_ty, found_refs) = get_deref_type_and_refs(*found_arg);
6735 let (expected_ty, expected_refs) = get_deref_type_and_refs(*expected_arg);
6736
6737 if infcx.can_eq(param_env, found_ty, expected_ty) {
6738 if found_refs.len() < expected_refs.len()
6740 && found_refs[..] == expected_refs[expected_refs.len() - found_refs.len()..]
6741 {
6742 to_borrow.push((
6743 arg.span.shrink_to_lo(),
6744 expected_refs[..expected_refs.len() - found_refs.len()]
6745 .iter()
6746 .map(|mutbl| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&{0}", mutbl.prefix_str()))
})format!("&{}", mutbl.prefix_str()))
6747 .collect::<Vec<_>>()
6748 .join(""),
6749 ));
6750 } else if found_refs.len() > expected_refs.len() {
6751 let mut span = arg.span.shrink_to_lo();
6752 let mut left = found_refs.len() - expected_refs.len();
6753 let mut ty = arg;
6754 while let hir::TyKind::Ref(_, mut_ty) = &ty.kind
6755 && left > 0
6756 {
6757 span = span.with_hi(mut_ty.ty.span.lo());
6758 ty = mut_ty.ty;
6759 left -= 1;
6760 }
6761 if left == 0 {
6762 remove_borrow.push((span, String::new()));
6763 }
6764 }
6765 }
6766 }
6767
6768 if !to_borrow.is_empty() {
6769 err.subdiagnostic(diagnostics::AdjustSignatureBorrow::Borrow { to_borrow });
6770 }
6771
6772 if !remove_borrow.is_empty() {
6773 err.subdiagnostic(diagnostics::AdjustSignatureBorrow::RemoveBorrow { remove_borrow });
6774 }
6775}
6776
6777#[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)]
6780pub struct SelfVisitor<'v> {
6781 pub paths: Vec<&'v hir::Ty<'v>> = Vec::new(),
6782 pub name: Option<Symbol>,
6783}
6784
6785impl<'v> Visitor<'v> for SelfVisitor<'v> {
6786 fn visit_ty(&mut self, ty: &'v hir::Ty<'v, AmbigArg>) {
6787 if let hir::TyKind::Path(path) = ty.kind
6788 && let hir::QPath::TypeRelative(inner_ty, segment) = path
6789 && (Some(segment.ident.name) == self.name || self.name.is_none())
6790 && let hir::TyKind::Path(inner_path) = inner_ty.kind
6791 && let hir::QPath::Resolved(None, inner_path) = inner_path
6792 && let Res::SelfTyAlias { .. } = inner_path.res
6793 {
6794 self.paths.push(ty.as_unambig_ty());
6795 }
6796 hir::intravisit::walk_ty(self, ty);
6797 }
6798}
6799
6800#[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)]
6803pub struct ReturnsVisitor<'v> {
6804 pub returns: Vec<&'v hir::Expr<'v>>,
6805 in_block_tail: bool,
6806}
6807
6808impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
6809 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
6810 match ex.kind {
6815 hir::ExprKind::Ret(Some(ex)) => {
6816 self.returns.push(ex);
6817 }
6818 hir::ExprKind::Block(block, _) if self.in_block_tail => {
6819 self.in_block_tail = false;
6820 for stmt in block.stmts {
6821 hir::intravisit::walk_stmt(self, stmt);
6822 }
6823 self.in_block_tail = true;
6824 if let Some(expr) = block.expr {
6825 self.visit_expr(expr);
6826 }
6827 }
6828 hir::ExprKind::If(_, then, else_opt) if self.in_block_tail => {
6829 self.visit_expr(then);
6830 if let Some(el) = else_opt {
6831 self.visit_expr(el);
6832 }
6833 }
6834 hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
6835 for arm in arms {
6836 self.visit_expr(arm.body);
6837 }
6838 }
6839 _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
6841 _ => self.returns.push(ex),
6842 }
6843 }
6844
6845 fn visit_body(&mut self, body: &hir::Body<'v>) {
6846 if !!self.in_block_tail {
::core::panicking::panic("assertion failed: !self.in_block_tail")
};assert!(!self.in_block_tail);
6847 self.in_block_tail = true;
6848 hir::intravisit::walk_body(self, body);
6849 }
6850}
6851
6852#[derive(#[automatically_derived]
impl ::core::default::Default for AwaitsVisitor {
#[inline]
fn default() -> AwaitsVisitor {
AwaitsVisitor { awaits: ::core::default::Default::default() }
}
}Default)]
6854struct AwaitsVisitor {
6855 awaits: Vec<HirId>,
6856}
6857
6858impl<'v> Visitor<'v> for AwaitsVisitor {
6859 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
6860 if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
6861 self.awaits.push(id)
6862 }
6863 hir::intravisit::walk_expr(self, ex)
6864 }
6865}
6866
6867pub trait NextTypeParamName {
6871 fn next_type_param_name(&self, name: Option<&str>) -> String;
6872}
6873
6874impl NextTypeParamName for &[hir::GenericParam<'_>] {
6875 fn next_type_param_name(&self, name: Option<&str>) -> String {
6876 let name = name.and_then(|n| n.chars().next()).map(|c| c.to_uppercase().to_string());
6878 let name = name.as_deref();
6879
6880 let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
6882
6883 let used_names: Vec<Symbol> = self
6885 .iter()
6886 .filter_map(|param| match param.name {
6887 hir::ParamName::Plain(ident) => Some(ident.name),
6888 _ => None,
6889 })
6890 .collect();
6891
6892 possible_names
6894 .iter()
6895 .find(|n| !used_names.contains(&Symbol::intern(n)))
6896 .unwrap_or(&"ParamName")
6897 .to_string()
6898 }
6899}
6900
6901struct ReplaceImplTraitVisitor<'a> {
6903 ty_spans: &'a mut Vec<Span>,
6904 param_did: DefId,
6905}
6906
6907impl<'a, 'hir> hir::intravisit::Visitor<'hir> for ReplaceImplTraitVisitor<'a> {
6908 fn visit_ty(&mut self, t: &'hir hir::Ty<'hir, AmbigArg>) {
6909 if let hir::TyKind::Path(hir::QPath::Resolved(
6910 None,
6911 hir::Path { res: Res::Def(_, segment_did), .. },
6912 )) = t.kind
6913 {
6914 if self.param_did == *segment_did {
6915 self.ty_spans.push(t.span);
6920 return;
6921 }
6922 }
6923
6924 hir::intravisit::walk_ty(self, t);
6925 }
6926}
6927
6928pub(super) fn get_explanation_based_on_obligation<'tcx>(
6929 tcx: TyCtxt<'tcx>,
6930 obligation: &PredicateObligation<'tcx>,
6931 trait_predicate: ty::PolyTraitClause<'tcx>,
6932 pre_message: String,
6933 long_ty_path: &mut Option<PathBuf>,
6934) -> String {
6935 if let ObligationCauseCode::MainFunctionType = obligation.cause.code() {
6936 "consider using `()`, or a `Result`".to_owned()
6937 } else {
6938 let ty_desc = match trait_predicate.self_ty().skip_binder().kind() {
6939 ty::FnDef(_, _) => Some("fn item"),
6940 ty::Closure(_, _) => Some("closure"),
6941 _ => None,
6942 };
6943
6944 let desc = match ty_desc {
6945 Some(desc) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" {0}", desc))
})format!(" {desc}"),
6946 None => String::new(),
6947 };
6948 if let ty::ClausePolarity::Positive = trait_predicate.polarity() {
6949 let mention_unstable = !tcx.sess.opts.unstable_opts.force_unstable_if_unmarked
6954 && try { tcx.lookup_stability(trait_predicate.def_id())?.level.is_stable() }
6955 == Some(false);
6956 let unstable = if mention_unstable { "nightly-only, unstable " } else { "" };
6957
6958 ::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!(
6959 "{pre_message}the {unstable}trait `{}` is not implemented for{desc} `{}`",
6960 trait_predicate.print_modifiers_and_trait_path(),
6961 tcx.short_string(trait_predicate.self_ty().skip_binder(), long_ty_path),
6962 )
6963 } else {
6964 ::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")
6968 }
6969 }
6970}
6971
6972struct ReplaceImplTraitFolder<'tcx> {
6974 tcx: TyCtxt<'tcx>,
6975 param: &'tcx ty::GenericParamDef,
6976 replace_ty: Ty<'tcx>,
6977}
6978
6979impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ReplaceImplTraitFolder<'tcx> {
6980 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
6981 if let ty::Param(ty::ParamTy { index, .. }) = t.kind() {
6982 if self.param.index == *index {
6983 return self.replace_ty;
6984 }
6985 }
6986 t.super_fold_with(self)
6987 }
6988
6989 fn cx(&self) -> TyCtxt<'tcx> {
6990 self.tcx
6991 }
6992}
6993
6994pub fn suggest_desugaring_async_fn_to_impl_future_in_trait<'tcx>(
6995 tcx: TyCtxt<'tcx>,
6996 sig: hir::FnSig<'tcx>,
6997 body: hir::TraitFn<'tcx>,
6998 opaque_def_id: LocalDefId,
6999 add_bounds: &str,
7000) -> Option<Vec<(Span, String)>> {
7001 let hir::IsAsync::Async(async_span) = sig.header.asyncness else {
7002 return None;
7003 };
7004 let async_span = tcx.sess.source_map().span_extend_while_whitespace(async_span);
7005
7006 let future = tcx.hir_node_by_def_id(opaque_def_id).expect_opaque_ty();
7007 let [hir::GenericBound::Trait(trait_ref)] = future.bounds else {
7008 return None;
7010 };
7011 let Some(hir::PathSegment { args: Some(args), .. }) = trait_ref.trait_ref.path.segments.last()
7012 else {
7013 return None;
7015 };
7016 let Some(future_output_ty) = args.constraints.first().and_then(|constraint| constraint.ty())
7017 else {
7018 return None;
7020 };
7021
7022 let mut sugg = if future_output_ty.span.is_empty() {
7023 ::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![
7024 (async_span, String::new()),
7025 (
7026 future_output_ty.span,
7027 format!(" -> impl std::future::Future<Output = ()>{add_bounds}"),
7028 ),
7029 ]
7030 } else {
7031 ::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![
7032 (future_output_ty.span.shrink_to_lo(), "impl std::future::Future<Output = ".to_owned()),
7033 (future_output_ty.span.shrink_to_hi(), format!(">{add_bounds}")),
7034 (async_span, String::new()),
7035 ]
7036 };
7037
7038 if let hir::TraitFn::Provided(body) = body {
7040 let body = tcx.hir_body(body);
7041 let body_span = body.value.span;
7042 let body_span_without_braces =
7043 body_span.with_lo(body_span.lo() + BytePos(1)).with_hi(body_span.hi() - BytePos(1));
7044 if body_span_without_braces.is_empty() {
7045 sugg.push((body_span_without_braces, " async {} ".to_owned()));
7046 } else {
7047 sugg.extend([
7048 (body_span_without_braces.shrink_to_lo(), "async {".to_owned()),
7049 (body_span_without_braces.shrink_to_hi(), "} ".to_owned()),
7050 ]);
7051 }
7052 }
7053
7054 Some(sugg)
7055}
7056
7057fn point_at_assoc_type_restriction<G: EmissionGuarantee>(
7060 tcx: TyCtxt<'_>,
7061 err: &mut Diag<'_, G>,
7062 self_ty_str: &str,
7063 trait_name: &str,
7064 predicate: ty::Predicate<'_>,
7065 generics: &hir::Generics<'_>,
7066 data: &ImplDerivedCause<'_>,
7067) {
7068 let ty::PredicateKind::Clause(clause) = predicate.kind().skip_binder() else {
7069 return;
7070 };
7071 let ty::ClauseKind::Projection(proj) = clause else {
7072 return;
7073 };
7074 let Some(name) = tcx
7075 .opt_rpitit_info(proj.def_id())
7076 .and_then(|data| match data {
7077 ty::ImplTraitInTraitData::Trait { fn_def_id, .. } => Some(tcx.item_name(fn_def_id)),
7078 ty::ImplTraitInTraitData::Impl { .. } => None,
7079 })
7080 .or_else(|| tcx.opt_item_name(proj.def_id()))
7081 else {
7082 return;
7083 };
7084 let mut predicates = generics.predicates.iter().peekable();
7085 let mut prev: Option<(&hir::WhereBoundPredicate<'_>, Span)> = None;
7086 while let Some(pred) = predicates.next() {
7087 let curr_span = pred.span;
7088 let hir::WherePredicateKind::BoundPredicate(pred) = pred.kind else {
7089 continue;
7090 };
7091 let mut bounds = pred.bounds.iter();
7092 while let Some(bound) = bounds.next() {
7093 let Some(trait_ref) = bound.trait_ref() else {
7094 continue;
7095 };
7096 if bound.span() != data.span {
7097 continue;
7098 }
7099 if let hir::TyKind::Path(path) = pred.bounded_ty.kind
7100 && let hir::QPath::TypeRelative(ty, segment) = path
7101 && segment.ident.name == name
7102 && let hir::TyKind::Path(inner_path) = ty.kind
7103 && let hir::QPath::Resolved(None, inner_path) = inner_path
7104 && let Res::SelfTyAlias { .. } = inner_path.res
7105 {
7106 let span = if pred.origin == hir::PredicateOrigin::WhereClause
7109 && generics
7110 .predicates
7111 .iter()
7112 .filter(|p| {
7113 #[allow(non_exhaustive_omitted_patterns)] match p.kind {
hir::WherePredicateKind::BoundPredicate(p) if
hir::PredicateOrigin::WhereClause == p.origin => true,
_ => false,
}matches!(
7114 p.kind,
7115 hir::WherePredicateKind::BoundPredicate(p)
7116 if hir::PredicateOrigin::WhereClause == p.origin
7117 )
7118 })
7119 .count()
7120 == 1
7121 {
7122 generics.where_clause_span
7125 } else if let Some(next_pred) = predicates.peek()
7126 && let hir::WherePredicateKind::BoundPredicate(next) = next_pred.kind
7127 && pred.origin == next.origin
7128 {
7129 curr_span.until(next_pred.span)
7131 } else if let Some((prev, prev_span)) = prev
7132 && pred.origin == prev.origin
7133 {
7134 prev_span.shrink_to_hi().to(curr_span)
7136 } else if pred.origin == hir::PredicateOrigin::WhereClause {
7137 curr_span.with_hi(generics.where_clause_span.hi())
7138 } else {
7139 curr_span
7140 };
7141
7142 err.span_suggestion_verbose(
7143 span,
7144 "associated type for the current `impl` cannot be restricted in `where` \
7145 clauses, remove this bound",
7146 "",
7147 Applicability::MaybeIncorrect,
7148 );
7149 }
7150 if let Some(new) =
7151 tcx.associated_items(data.impl_or_alias_def_id).find_by_ident_and_kind(
7152 tcx,
7153 Ident::with_dummy_span(name),
7154 ty::AssocTag::Type,
7155 data.impl_or_alias_def_id,
7156 )
7157 {
7158 let span = tcx.def_span(new.def_id);
7161 err.span_label(
7162 span,
7163 ::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!(
7164 "associated type `<{self_ty_str} as {trait_name}>::{name}` is specified \
7165 here",
7166 ),
7167 );
7168 let mut visitor = SelfVisitor { name: Some(name), .. };
7171 visitor.visit_trait_ref(trait_ref);
7172 for path in visitor.paths {
7173 err.span_suggestion_verbose(
7174 path.span,
7175 "replace the associated type with the type specified in this `impl`",
7176 tcx.type_of(new.def_id).skip_binder(),
7177 Applicability::MachineApplicable,
7178 );
7179 }
7180 } else {
7181 let mut visitor = SelfVisitor { name: None, .. };
7182 visitor.visit_trait_ref(trait_ref);
7183 let span: MultiSpan =
7184 visitor.paths.iter().map(|p| p.span).collect::<Vec<Span>>().into();
7185 err.span_note(
7186 span,
7187 "associated types for the current `impl` cannot be restricted in `where` \
7188 clauses",
7189 );
7190 }
7191 }
7192 prev = Some((pred, curr_span));
7193 }
7194}
7195
7196fn get_deref_type_and_refs(mut ty: Ty<'_>) -> (Ty<'_>, Vec<hir::Mutability>) {
7197 let mut refs = ::alloc::vec::Vec::new()vec![];
7198
7199 while let ty::Ref(_, new_ty, mutbl) = ty.kind() {
7200 ty = *new_ty;
7201 refs.push(*mutbl);
7202 }
7203
7204 (ty, refs)
7205}
7206
7207struct FindTypeParam {
7210 param: rustc_span::Symbol,
7211 invalid_spans: Vec<Span> = Vec::new(),
7212 nested: bool = false,
7213}
7214
7215impl<'v> Visitor<'v> for FindTypeParam {
7216 fn visit_where_predicate(&mut self, _: &'v hir::WherePredicate<'v>) {
7217 }
7219
7220 fn visit_ty(&mut self, ty: &hir::Ty<'_, AmbigArg>) {
7221 match ty.kind {
7228 hir::TyKind::Ptr(_) | hir::TyKind::Ref(..) | hir::TyKind::TraitObject(..) => {}
7229 hir::TyKind::Path(hir::QPath::Resolved(None, path))
7230 if let [segment] = path.segments
7231 && segment.ident.name == self.param =>
7232 {
7233 if !self.nested {
7234 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:7234",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(7234u32),
::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");
7235 self.invalid_spans.push(ty.span);
7236 }
7237 }
7238 hir::TyKind::Path(_) => {
7239 let prev = self.nested;
7240 self.nested = true;
7241 hir::intravisit::walk_ty(self, ty);
7242 self.nested = prev;
7243 }
7244 _ => {
7245 hir::intravisit::walk_ty(self, ty);
7246 }
7247 }
7248 }
7249}
7250
7251struct ParamFinder {
7254 params: Vec<Symbol> = Vec::new(),
7255}
7256
7257impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ParamFinder {
7258 fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
7259 match t.kind() {
7260 ty::Param(p) => self.params.push(p.name),
7261 _ => {}
7262 }
7263 t.super_visit_with(self)
7264 }
7265}
7266
7267impl ParamFinder {
7268 fn can_suggest_bound(&self, generics: &hir::Generics<'_>) -> bool {
7271 if self.params.is_empty() {
7272 return true;
7275 }
7276 generics.params.iter().any(|p| match p.name {
7277 hir::ParamName::Plain(p_name) => {
7278 self.params.iter().any(|p| *p == p_name.name || *p == kw::SelfUpper)
7280 }
7281 _ => true,
7282 })
7283 }
7284}