]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs
New upstream version 1.48.0~beta.8+dfsg1
[rustc.git] / compiler / rustc_trait_selection / src / traits / error_reporting / suggestions.rs
1 use super::{
2 EvaluationResult, Obligation, ObligationCause, ObligationCauseCode, PredicateObligation,
3 SelectionContext,
4 };
5
6 use crate::autoderef::Autoderef;
7 use crate::infer::InferCtxt;
8 use crate::traits::normalize_projection_type;
9
10 use rustc_data_structures::stack::ensure_sufficient_stack;
11 use rustc_errors::{error_code, struct_span_err, Applicability, DiagnosticBuilder, Style};
12 use rustc_hir as hir;
13 use rustc_hir::def::DefKind;
14 use rustc_hir::def_id::DefId;
15 use rustc_hir::intravisit::Visitor;
16 use rustc_hir::lang_items::LangItem;
17 use rustc_hir::{AsyncGeneratorKind, GeneratorKind, Node};
18 use rustc_middle::ty::{
19 self, suggest_constraining_type_param, AdtKind, DefIdTree, Infer, InferTy, ToPredicate, Ty,
20 TyCtxt, TypeFoldable, WithConstness,
21 };
22 use rustc_middle::ty::{TypeAndMut, TypeckResults};
23 use rustc_span::symbol::{kw, sym, Ident, Symbol};
24 use rustc_span::{MultiSpan, Span, DUMMY_SP};
25 use std::fmt;
26
27 use super::InferCtxtPrivExt;
28 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
29
30 #[derive(Debug)]
31 pub enum GeneratorInteriorOrUpvar {
32 // span of interior type
33 Interior(Span),
34 // span of upvar
35 Upvar(Span),
36 }
37
38 // This trait is public to expose the diagnostics methods to clippy.
39 pub trait InferCtxtExt<'tcx> {
40 fn suggest_restricting_param_bound(
41 &self,
42 err: &mut DiagnosticBuilder<'_>,
43 trait_ref: ty::PolyTraitRef<'tcx>,
44 body_id: hir::HirId,
45 );
46
47 fn suggest_dereferences(
48 &self,
49 obligation: &PredicateObligation<'tcx>,
50 err: &mut DiagnosticBuilder<'tcx>,
51 trait_ref: &ty::PolyTraitRef<'tcx>,
52 points_at_arg: bool,
53 );
54
55 fn get_closure_name(
56 &self,
57 def_id: DefId,
58 err: &mut DiagnosticBuilder<'_>,
59 msg: &str,
60 ) -> Option<String>;
61
62 fn suggest_fn_call(
63 &self,
64 obligation: &PredicateObligation<'tcx>,
65 err: &mut DiagnosticBuilder<'_>,
66 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
67 points_at_arg: bool,
68 );
69
70 fn suggest_add_reference_to_arg(
71 &self,
72 obligation: &PredicateObligation<'tcx>,
73 err: &mut DiagnosticBuilder<'_>,
74 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
75 points_at_arg: bool,
76 has_custom_message: bool,
77 ) -> bool;
78
79 fn suggest_remove_reference(
80 &self,
81 obligation: &PredicateObligation<'tcx>,
82 err: &mut DiagnosticBuilder<'_>,
83 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
84 );
85
86 fn suggest_change_mut(
87 &self,
88 obligation: &PredicateObligation<'tcx>,
89 err: &mut DiagnosticBuilder<'_>,
90 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
91 points_at_arg: bool,
92 );
93
94 fn suggest_semicolon_removal(
95 &self,
96 obligation: &PredicateObligation<'tcx>,
97 err: &mut DiagnosticBuilder<'_>,
98 span: Span,
99 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
100 );
101
102 fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span>;
103
104 fn suggest_impl_trait(
105 &self,
106 err: &mut DiagnosticBuilder<'_>,
107 span: Span,
108 obligation: &PredicateObligation<'tcx>,
109 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
110 ) -> bool;
111
112 fn point_at_returns_when_relevant(
113 &self,
114 err: &mut DiagnosticBuilder<'_>,
115 obligation: &PredicateObligation<'tcx>,
116 );
117
118 fn report_closure_arg_mismatch(
119 &self,
120 span: Span,
121 found_span: Option<Span>,
122 expected_ref: ty::PolyTraitRef<'tcx>,
123 found: ty::PolyTraitRef<'tcx>,
124 ) -> DiagnosticBuilder<'tcx>;
125
126 fn suggest_fully_qualified_path(
127 &self,
128 err: &mut DiagnosticBuilder<'_>,
129 def_id: DefId,
130 span: Span,
131 trait_ref: DefId,
132 );
133
134 fn maybe_note_obligation_cause_for_async_await(
135 &self,
136 err: &mut DiagnosticBuilder<'_>,
137 obligation: &PredicateObligation<'tcx>,
138 ) -> bool;
139
140 fn note_obligation_cause_for_async_await(
141 &self,
142 err: &mut DiagnosticBuilder<'_>,
143 interior_or_upvar_span: GeneratorInteriorOrUpvar,
144 interior_extra_info: Option<(Option<Span>, Span, Option<hir::HirId>, Option<Span>)>,
145 inner_generator_body: Option<&hir::Body<'tcx>>,
146 outer_generator: Option<DefId>,
147 trait_ref: ty::TraitRef<'tcx>,
148 target_ty: Ty<'tcx>,
149 typeck_results: &ty::TypeckResults<'tcx>,
150 obligation: &PredicateObligation<'tcx>,
151 next_code: Option<&ObligationCauseCode<'tcx>>,
152 );
153
154 fn note_obligation_cause_code<T>(
155 &self,
156 err: &mut DiagnosticBuilder<'_>,
157 predicate: &T,
158 cause_code: &ObligationCauseCode<'tcx>,
159 obligated_types: &mut Vec<&ty::TyS<'tcx>>,
160 ) where
161 T: fmt::Display;
162
163 fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder<'_>);
164
165 /// Suggest to await before try: future? => future.await?
166 fn suggest_await_before_try(
167 &self,
168 err: &mut DiagnosticBuilder<'_>,
169 obligation: &PredicateObligation<'tcx>,
170 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
171 span: Span,
172 );
173 }
174
175 fn predicate_constraint(generics: &hir::Generics<'_>, pred: String) -> (Span, String) {
176 (
177 generics.where_clause.tail_span_for_suggestion(),
178 format!(
179 "{} {}",
180 if !generics.where_clause.predicates.is_empty() { "," } else { " where" },
181 pred,
182 ),
183 )
184 }
185
186 /// Type parameter needs more bounds. The trivial case is `T` `where T: Bound`, but
187 /// it can also be an `impl Trait` param that needs to be decomposed to a type
188 /// param for cleaner code.
189 fn suggest_restriction(
190 tcx: TyCtxt<'tcx>,
191 generics: &hir::Generics<'tcx>,
192 msg: &str,
193 err: &mut DiagnosticBuilder<'_>,
194 fn_sig: Option<&hir::FnSig<'_>>,
195 projection: Option<&ty::ProjectionTy<'_>>,
196 trait_ref: ty::PolyTraitRef<'tcx>,
197 super_traits: Option<(&Ident, &hir::GenericBounds<'_>)>,
198 ) {
199 // When we are dealing with a trait, `super_traits` will be `Some`:
200 // Given `trait T: A + B + C {}`
201 // - ^^^^^^^^^ GenericBounds
202 // |
203 // &Ident
204 let span = generics.where_clause.span_for_predicates_or_empty_place();
205 if span.from_expansion() || span.desugaring_kind().is_some() {
206 return;
207 }
208 // Given `fn foo(t: impl Trait)` where `Trait` requires assoc type `A`...
209 if let Some((bound_str, fn_sig)) =
210 fn_sig.zip(projection).and_then(|(sig, p)| match p.self_ty().kind() {
211 // Shenanigans to get the `Trait` from the `impl Trait`.
212 ty::Param(param) => {
213 // `fn foo(t: impl Trait)`
214 // ^^^^^ get this string
215 param.name.as_str().strip_prefix("impl").map(|s| (s.trim_start().to_string(), sig))
216 }
217 _ => None,
218 })
219 {
220 // We know we have an `impl Trait` that doesn't satisfy a required projection.
221
222 // Find all of the ocurrences of `impl Trait` for `Trait` in the function arguments'
223 // types. There should be at least one, but there might be *more* than one. In that
224 // case we could just ignore it and try to identify which one needs the restriction,
225 // but instead we choose to suggest replacing all instances of `impl Trait` with `T`
226 // where `T: Trait`.
227 let mut ty_spans = vec![];
228 let impl_trait_str = format!("impl {}", bound_str);
229 for input in fn_sig.decl.inputs {
230 if let hir::TyKind::Path(hir::QPath::Resolved(
231 None,
232 hir::Path { segments: [segment], .. },
233 )) = input.kind
234 {
235 if segment.ident.as_str() == impl_trait_str.as_str() {
236 // `fn foo(t: impl Trait)`
237 // ^^^^^^^^^^ get this to suggest `T` instead
238
239 // There might be more than one `impl Trait`.
240 ty_spans.push(input.span);
241 }
242 }
243 }
244
245 let type_param_name = generics.params.next_type_param_name(Some(&bound_str));
246 // The type param `T: Trait` we will suggest to introduce.
247 let type_param = format!("{}: {}", type_param_name, bound_str);
248
249 // FIXME: modify the `trait_ref` instead of string shenanigans.
250 // Turn `<impl Trait as Foo>::Bar: Qux` into `<T as Foo>::Bar: Qux`.
251 let pred = trait_ref.without_const().to_predicate(tcx).to_string();
252 let pred = pred.replace(&impl_trait_str, &type_param_name);
253 let mut sugg = vec![
254 match generics
255 .params
256 .iter()
257 .filter(|p| match p.kind {
258 hir::GenericParamKind::Type {
259 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
260 ..
261 } => false,
262 _ => true,
263 })
264 .last()
265 {
266 // `fn foo(t: impl Trait)`
267 // ^ suggest `<T: Trait>` here
268 None => (generics.span, format!("<{}>", type_param)),
269 // `fn foo<A>(t: impl Trait)`
270 // ^^^ suggest `<A, T: Trait>` here
271 Some(param) => (
272 param.bounds_span().unwrap_or(param.span).shrink_to_hi(),
273 format!(", {}", type_param),
274 ),
275 },
276 // `fn foo(t: impl Trait)`
277 // ^ suggest `where <T as Trait>::A: Bound`
278 predicate_constraint(generics, pred),
279 ];
280 sugg.extend(ty_spans.into_iter().map(|s| (s, type_param_name.to_string())));
281
282 // Suggest `fn foo<T: Trait>(t: T) where <T as Trait>::A: Bound`.
283 // FIXME: once `#![feature(associated_type_bounds)]` is stabilized, we should suggest
284 // `fn foo(t: impl Trait<A: Bound>)` instead.
285 err.multipart_suggestion(
286 "introduce a type parameter with a trait bound instead of using `impl Trait`",
287 sugg,
288 Applicability::MaybeIncorrect,
289 );
290 } else {
291 // Trivial case: `T` needs an extra bound: `T: Bound`.
292 let (sp, suggestion) = match super_traits {
293 None => predicate_constraint(
294 generics,
295 trait_ref.without_const().to_predicate(tcx).to_string(),
296 ),
297 Some((ident, bounds)) => match bounds {
298 [.., bound] => (
299 bound.span().shrink_to_hi(),
300 format!(" + {}", trait_ref.print_only_trait_path().to_string()),
301 ),
302 [] => (
303 ident.span.shrink_to_hi(),
304 format!(": {}", trait_ref.print_only_trait_path().to_string()),
305 ),
306 },
307 };
308
309 err.span_suggestion_verbose(
310 sp,
311 &format!("consider further restricting {}", msg),
312 suggestion,
313 Applicability::MachineApplicable,
314 );
315 }
316 }
317
318 impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
319 fn suggest_restricting_param_bound(
320 &self,
321 mut err: &mut DiagnosticBuilder<'_>,
322 trait_ref: ty::PolyTraitRef<'tcx>,
323 body_id: hir::HirId,
324 ) {
325 let self_ty = trait_ref.skip_binder().self_ty();
326 let (param_ty, projection) = match self_ty.kind() {
327 ty::Param(_) => (true, None),
328 ty::Projection(projection) => (false, Some(projection)),
329 _ => return,
330 };
331
332 // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
333 // don't suggest `T: Sized + ?Sized`.
334 let mut hir_id = body_id;
335 while let Some(node) = self.tcx.hir().find(hir_id) {
336 match node {
337 hir::Node::Item(hir::Item {
338 ident,
339 kind: hir::ItemKind::Trait(_, _, generics, bounds, _),
340 ..
341 }) if self_ty == self.tcx.types.self_param => {
342 assert!(param_ty);
343 // Restricting `Self` for a single method.
344 suggest_restriction(
345 self.tcx,
346 &generics,
347 "`Self`",
348 err,
349 None,
350 projection,
351 trait_ref,
352 Some((ident, bounds)),
353 );
354 return;
355 }
356
357 hir::Node::TraitItem(hir::TraitItem {
358 generics,
359 kind: hir::TraitItemKind::Fn(..),
360 ..
361 }) if self_ty == self.tcx.types.self_param => {
362 assert!(param_ty);
363 // Restricting `Self` for a single method.
364 suggest_restriction(
365 self.tcx, &generics, "`Self`", err, None, projection, trait_ref, None,
366 );
367 return;
368 }
369
370 hir::Node::TraitItem(hir::TraitItem {
371 generics,
372 kind: hir::TraitItemKind::Fn(fn_sig, ..),
373 ..
374 })
375 | hir::Node::ImplItem(hir::ImplItem {
376 generics,
377 kind: hir::ImplItemKind::Fn(fn_sig, ..),
378 ..
379 })
380 | hir::Node::Item(hir::Item {
381 kind: hir::ItemKind::Fn(fn_sig, generics, _), ..
382 }) if projection.is_some() => {
383 // Missing restriction on associated type of type parameter (unmet projection).
384 suggest_restriction(
385 self.tcx,
386 &generics,
387 "the associated type",
388 err,
389 Some(fn_sig),
390 projection,
391 trait_ref,
392 None,
393 );
394 return;
395 }
396 hir::Node::Item(hir::Item {
397 kind:
398 hir::ItemKind::Trait(_, _, generics, _, _)
399 | hir::ItemKind::Impl { generics, .. },
400 ..
401 }) if projection.is_some() => {
402 // Missing restriction on associated type of type parameter (unmet projection).
403 suggest_restriction(
404 self.tcx,
405 &generics,
406 "the associated type",
407 err,
408 None,
409 projection,
410 trait_ref,
411 None,
412 );
413 return;
414 }
415
416 hir::Node::Item(hir::Item {
417 kind:
418 hir::ItemKind::Struct(_, generics)
419 | hir::ItemKind::Enum(_, generics)
420 | hir::ItemKind::Union(_, generics)
421 | hir::ItemKind::Trait(_, _, generics, ..)
422 | hir::ItemKind::Impl { generics, .. }
423 | hir::ItemKind::Fn(_, generics, _)
424 | hir::ItemKind::TyAlias(_, generics)
425 | hir::ItemKind::TraitAlias(generics, _)
426 | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
427 ..
428 })
429 | hir::Node::TraitItem(hir::TraitItem { generics, .. })
430 | hir::Node::ImplItem(hir::ImplItem { generics, .. })
431 if param_ty =>
432 {
433 // Missing generic type parameter bound.
434 let param_name = self_ty.to_string();
435 let constraint = trait_ref.print_only_trait_path().to_string();
436 if suggest_constraining_type_param(
437 self.tcx,
438 generics,
439 &mut err,
440 &param_name,
441 &constraint,
442 Some(trait_ref.def_id()),
443 ) {
444 return;
445 }
446 }
447
448 hir::Node::Crate(..) => return,
449
450 _ => {}
451 }
452
453 hir_id = self.tcx.hir().get_parent_item(hir_id);
454 }
455 }
456
457 /// When after several dereferencing, the reference satisfies the trait
458 /// binding. This function provides dereference suggestion for this
459 /// specific situation.
460 fn suggest_dereferences(
461 &self,
462 obligation: &PredicateObligation<'tcx>,
463 err: &mut DiagnosticBuilder<'tcx>,
464 trait_ref: &ty::PolyTraitRef<'tcx>,
465 points_at_arg: bool,
466 ) {
467 // It only make sense when suggesting dereferences for arguments
468 if !points_at_arg {
469 return;
470 }
471 let param_env = obligation.param_env;
472 let body_id = obligation.cause.body_id;
473 let span = obligation.cause.span;
474 let real_trait_ref = match &obligation.cause.code {
475 ObligationCauseCode::ImplDerivedObligation(cause)
476 | ObligationCauseCode::DerivedObligation(cause)
477 | ObligationCauseCode::BuiltinDerivedObligation(cause) => &cause.parent_trait_ref,
478 _ => trait_ref,
479 };
480 let real_ty = match real_trait_ref.self_ty().no_bound_vars() {
481 Some(ty) => ty,
482 None => return,
483 };
484
485 if let ty::Ref(region, base_ty, mutbl) = *real_ty.kind() {
486 let mut autoderef = Autoderef::new(self, param_env, body_id, span, base_ty, span);
487 if let Some(steps) = autoderef.find_map(|(ty, steps)| {
488 // Re-add the `&`
489 let ty = self.tcx.mk_ref(region, TypeAndMut { ty, mutbl });
490 let obligation =
491 self.mk_trait_obligation_with_new_self_ty(param_env, real_trait_ref, ty);
492 Some(steps).filter(|_| self.predicate_may_hold(&obligation))
493 }) {
494 if steps > 0 {
495 if let Ok(src) = self.tcx.sess.source_map().span_to_snippet(span) {
496 // Don't care about `&mut` because `DerefMut` is used less
497 // often and user will not expect autoderef happens.
498 if src.starts_with('&') && !src.starts_with("&mut ") {
499 let derefs = "*".repeat(steps);
500 err.span_suggestion(
501 span,
502 "consider adding dereference here",
503 format!("&{}{}", derefs, &src[1..]),
504 Applicability::MachineApplicable,
505 );
506 }
507 }
508 }
509 }
510 }
511 }
512
513 /// Given a closure's `DefId`, return the given name of the closure.
514 ///
515 /// This doesn't account for reassignments, but it's only used for suggestions.
516 fn get_closure_name(
517 &self,
518 def_id: DefId,
519 err: &mut DiagnosticBuilder<'_>,
520 msg: &str,
521 ) -> Option<String> {
522 let get_name =
523 |err: &mut DiagnosticBuilder<'_>, kind: &hir::PatKind<'_>| -> Option<String> {
524 // Get the local name of this closure. This can be inaccurate because
525 // of the possibility of reassignment, but this should be good enough.
526 match &kind {
527 hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, name, None) => {
528 Some(format!("{}", name))
529 }
530 _ => {
531 err.note(&msg);
532 None
533 }
534 }
535 };
536
537 let hir = self.tcx.hir();
538 let hir_id = hir.local_def_id_to_hir_id(def_id.as_local()?);
539 let parent_node = hir.get_parent_node(hir_id);
540 match hir.find(parent_node) {
541 Some(hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Local(local), .. })) => {
542 get_name(err, &local.pat.kind)
543 }
544 // Different to previous arm because one is `&hir::Local` and the other
545 // is `P<hir::Local>`.
546 Some(hir::Node::Local(local)) => get_name(err, &local.pat.kind),
547 _ => None,
548 }
549 }
550
551 /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
552 /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
553 /// it: `bar(foo)` → `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
554 fn suggest_fn_call(
555 &self,
556 obligation: &PredicateObligation<'tcx>,
557 err: &mut DiagnosticBuilder<'_>,
558 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
559 points_at_arg: bool,
560 ) {
561 let self_ty = match trait_ref.self_ty().no_bound_vars() {
562 None => return,
563 Some(ty) => ty,
564 };
565
566 let (def_id, output_ty, callable) = match *self_ty.kind() {
567 ty::Closure(def_id, substs) => (def_id, substs.as_closure().sig().output(), "closure"),
568 ty::FnDef(def_id, _) => (def_id, self_ty.fn_sig(self.tcx).output(), "function"),
569 _ => return,
570 };
571 let msg = format!("use parentheses to call the {}", callable);
572
573 // `mk_trait_obligation_with_new_self_ty` only works for types with no escaping bound
574 // variables, so bail out if we have any.
575 let output_ty = match output_ty.no_bound_vars() {
576 Some(ty) => ty,
577 None => return,
578 };
579
580 let new_obligation =
581 self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_ref, output_ty);
582
583 match self.evaluate_obligation(&new_obligation) {
584 Ok(
585 EvaluationResult::EvaluatedToOk
586 | EvaluationResult::EvaluatedToOkModuloRegions
587 | EvaluationResult::EvaluatedToAmbig,
588 ) => {}
589 _ => return,
590 }
591 let hir = self.tcx.hir();
592 // Get the name of the callable and the arguments to be used in the suggestion.
593 let (snippet, sugg) = match hir.get_if_local(def_id) {
594 Some(hir::Node::Expr(hir::Expr {
595 kind: hir::ExprKind::Closure(_, decl, _, span, ..),
596 ..
597 })) => {
598 err.span_label(*span, "consider calling this closure");
599 let name = match self.get_closure_name(def_id, err, &msg) {
600 Some(name) => name,
601 None => return,
602 };
603 let args = decl.inputs.iter().map(|_| "_").collect::<Vec<_>>().join(", ");
604 let sugg = format!("({})", args);
605 (format!("{}{}", name, sugg), sugg)
606 }
607 Some(hir::Node::Item(hir::Item {
608 ident,
609 kind: hir::ItemKind::Fn(.., body_id),
610 ..
611 })) => {
612 err.span_label(ident.span, "consider calling this function");
613 let body = hir.body(*body_id);
614 let args = body
615 .params
616 .iter()
617 .map(|arg| match &arg.pat.kind {
618 hir::PatKind::Binding(_, _, ident, None)
619 // FIXME: provide a better suggestion when encountering `SelfLower`, it
620 // should suggest a method call.
621 if ident.name != kw::SelfLower => ident.to_string(),
622 _ => "_".to_string(),
623 })
624 .collect::<Vec<_>>()
625 .join(", ");
626 let sugg = format!("({})", args);
627 (format!("{}{}", ident, sugg), sugg)
628 }
629 _ => return,
630 };
631 if points_at_arg {
632 // When the obligation error has been ensured to have been caused by
633 // an argument, the `obligation.cause.span` points at the expression
634 // of the argument, so we can provide a suggestion. This is signaled
635 // by `points_at_arg`. Otherwise, we give a more general note.
636 err.span_suggestion_verbose(
637 obligation.cause.span.shrink_to_hi(),
638 &msg,
639 sugg,
640 Applicability::HasPlaceholders,
641 );
642 } else {
643 err.help(&format!("{}: `{}`", msg, snippet));
644 }
645 }
646
647 fn suggest_add_reference_to_arg(
648 &self,
649 obligation: &PredicateObligation<'tcx>,
650 err: &mut DiagnosticBuilder<'_>,
651 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
652 points_at_arg: bool,
653 has_custom_message: bool,
654 ) -> bool {
655 if !points_at_arg {
656 return false;
657 }
658
659 let span = obligation.cause.span;
660 let param_env = obligation.param_env;
661 let trait_ref = trait_ref.skip_binder();
662
663 if let ObligationCauseCode::ImplDerivedObligation(obligation) = &obligation.cause.code {
664 // Try to apply the original trait binding obligation by borrowing.
665 let self_ty = trait_ref.self_ty();
666 let found = self_ty.to_string();
667 let new_self_ty = self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, self_ty);
668 let substs = self.tcx.mk_substs_trait(new_self_ty, &[]);
669 let new_trait_ref = ty::TraitRef::new(obligation.parent_trait_ref.def_id(), substs);
670 let new_obligation = Obligation::new(
671 ObligationCause::dummy(),
672 param_env,
673 new_trait_ref.without_const().to_predicate(self.tcx),
674 );
675
676 if self.predicate_must_hold_modulo_regions(&new_obligation) {
677 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
678 // We have a very specific type of error, where just borrowing this argument
679 // might solve the problem. In cases like this, the important part is the
680 // original type obligation, not the last one that failed, which is arbitrary.
681 // Because of this, we modify the error to refer to the original obligation and
682 // return early in the caller.
683
684 let msg = format!(
685 "the trait bound `{}: {}` is not satisfied",
686 found,
687 obligation.parent_trait_ref.skip_binder().print_only_trait_path(),
688 );
689 if has_custom_message {
690 err.note(&msg);
691 } else {
692 err.message = vec![(msg, Style::NoStyle)];
693 }
694 if snippet.starts_with('&') {
695 // This is already a literal borrow and the obligation is failing
696 // somewhere else in the obligation chain. Do not suggest non-sense.
697 return false;
698 }
699 err.span_label(
700 span,
701 &format!(
702 "expected an implementor of trait `{}`",
703 obligation.parent_trait_ref.skip_binder().print_only_trait_path(),
704 ),
705 );
706
707 // This if is to prevent a special edge-case
708 if !span.from_expansion() {
709 // We don't want a borrowing suggestion on the fields in structs,
710 // ```
711 // struct Foo {
712 // the_foos: Vec<Foo>
713 // }
714 // ```
715
716 err.span_suggestion(
717 span,
718 "consider borrowing here",
719 format!("&{}", snippet),
720 Applicability::MaybeIncorrect,
721 );
722 }
723 return true;
724 }
725 }
726 }
727 false
728 }
729
730 /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
731 /// suggest removing these references until we reach a type that implements the trait.
732 fn suggest_remove_reference(
733 &self,
734 obligation: &PredicateObligation<'tcx>,
735 err: &mut DiagnosticBuilder<'_>,
736 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
737 ) {
738 let span = obligation.cause.span;
739
740 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
741 let refs_number =
742 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
743 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
744 // Do not suggest removal of borrow from type arguments.
745 return;
746 }
747
748 let mut suggested_ty = match trait_ref.self_ty().no_bound_vars() {
749 Some(ty) => ty,
750 None => return,
751 };
752
753 for refs_remaining in 0..refs_number {
754 if let ty::Ref(_, inner_ty, _) = suggested_ty.kind() {
755 suggested_ty = inner_ty;
756
757 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
758 obligation.param_env,
759 trait_ref,
760 suggested_ty,
761 );
762
763 if self.predicate_may_hold(&new_obligation) {
764 let sp = self
765 .tcx
766 .sess
767 .source_map()
768 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
769
770 let remove_refs = refs_remaining + 1;
771
772 let msg = if remove_refs == 1 {
773 "consider removing the leading `&`-reference".to_string()
774 } else {
775 format!("consider removing {} leading `&`-references", remove_refs)
776 };
777
778 err.span_suggestion_short(
779 sp,
780 &msg,
781 String::new(),
782 Applicability::MachineApplicable,
783 );
784 break;
785 }
786 } else {
787 break;
788 }
789 }
790 }
791 }
792
793 /// Check if the trait bound is implemented for a different mutability and note it in the
794 /// final error.
795 fn suggest_change_mut(
796 &self,
797 obligation: &PredicateObligation<'tcx>,
798 err: &mut DiagnosticBuilder<'_>,
799 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
800 points_at_arg: bool,
801 ) {
802 let span = obligation.cause.span;
803 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
804 let refs_number =
805 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
806 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
807 // Do not suggest removal of borrow from type arguments.
808 return;
809 }
810 let trait_ref = self.resolve_vars_if_possible(trait_ref);
811 if trait_ref.has_infer_types_or_consts() {
812 // Do not ICE while trying to find if a reborrow would succeed on a trait with
813 // unresolved bindings.
814 return;
815 }
816
817 if let ty::Ref(region, t_type, mutability) = *trait_ref.skip_binder().self_ty().kind() {
818 if region.is_late_bound() || t_type.has_escaping_bound_vars() {
819 // Avoid debug assertion in `mk_obligation_for_def_id`.
820 //
821 // If the self type has escaping bound vars then it's not
822 // going to be the type of an expression, so the suggestion
823 // probably won't apply anyway.
824 return;
825 }
826
827 let suggested_ty = match mutability {
828 hir::Mutability::Mut => self.tcx.mk_imm_ref(region, t_type),
829 hir::Mutability::Not => self.tcx.mk_mut_ref(region, t_type),
830 };
831
832 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
833 obligation.param_env,
834 &trait_ref,
835 suggested_ty,
836 );
837 let suggested_ty_would_satisfy_obligation = self
838 .evaluate_obligation_no_overflow(&new_obligation)
839 .must_apply_modulo_regions();
840 if suggested_ty_would_satisfy_obligation {
841 let sp = self
842 .tcx
843 .sess
844 .source_map()
845 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
846 if points_at_arg && mutability == hir::Mutability::Not && refs_number > 0 {
847 err.span_suggestion_verbose(
848 sp,
849 "consider changing this borrow's mutability",
850 "&mut ".to_string(),
851 Applicability::MachineApplicable,
852 );
853 } else {
854 err.note(&format!(
855 "`{}` is implemented for `{:?}`, but not for `{:?}`",
856 trait_ref.print_only_trait_path(),
857 suggested_ty,
858 trait_ref.skip_binder().self_ty(),
859 ));
860 }
861 }
862 }
863 }
864 }
865
866 fn suggest_semicolon_removal(
867 &self,
868 obligation: &PredicateObligation<'tcx>,
869 err: &mut DiagnosticBuilder<'_>,
870 span: Span,
871 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
872 ) {
873 let is_empty_tuple =
874 |ty: ty::Binder<Ty<'_>>| *ty.skip_binder().kind() == ty::Tuple(ty::List::empty());
875
876 let hir = self.tcx.hir();
877 let parent_node = hir.get_parent_node(obligation.cause.body_id);
878 let node = hir.find(parent_node);
879 if let Some(hir::Node::Item(hir::Item {
880 kind: hir::ItemKind::Fn(sig, _, body_id), ..
881 })) = node
882 {
883 let body = hir.body(*body_id);
884 if let hir::ExprKind::Block(blk, _) = &body.value.kind {
885 if sig.decl.output.span().overlaps(span)
886 && blk.expr.is_none()
887 && is_empty_tuple(trait_ref.self_ty())
888 {
889 // FIXME(estebank): When encountering a method with a trait
890 // bound not satisfied in the return type with a body that has
891 // no return, suggest removal of semicolon on last statement.
892 // Once that is added, close #54771.
893 if let Some(ref stmt) = blk.stmts.last() {
894 let sp = self.tcx.sess.source_map().end_point(stmt.span);
895 err.span_label(sp, "consider removing this semicolon");
896 }
897 }
898 }
899 }
900 }
901
902 fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span> {
903 let hir = self.tcx.hir();
904 let parent_node = hir.get_parent_node(obligation.cause.body_id);
905 let sig = match hir.find(parent_node) {
906 Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, ..), .. })) => sig,
907 _ => return None,
908 };
909
910 if let hir::FnRetTy::Return(ret_ty) = sig.decl.output { Some(ret_ty.span) } else { None }
911 }
912
913 /// If all conditions are met to identify a returned `dyn Trait`, suggest using `impl Trait` if
914 /// applicable and signal that the error has been expanded appropriately and needs to be
915 /// emitted.
916 fn suggest_impl_trait(
917 &self,
918 err: &mut DiagnosticBuilder<'_>,
919 span: Span,
920 obligation: &PredicateObligation<'tcx>,
921 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
922 ) -> bool {
923 match obligation.cause.code.peel_derives() {
924 // Only suggest `impl Trait` if the return type is unsized because it is `dyn Trait`.
925 ObligationCauseCode::SizedReturnType => {}
926 _ => return false,
927 }
928
929 let hir = self.tcx.hir();
930 let parent_node = hir.get_parent_node(obligation.cause.body_id);
931 let node = hir.find(parent_node);
932 let (sig, body_id) = if let Some(hir::Node::Item(hir::Item {
933 kind: hir::ItemKind::Fn(sig, _, body_id),
934 ..
935 })) = node
936 {
937 (sig, body_id)
938 } else {
939 return false;
940 };
941 let body = hir.body(*body_id);
942 let trait_ref = self.resolve_vars_if_possible(trait_ref);
943 let ty = trait_ref.skip_binder().self_ty();
944 let is_object_safe = match ty.kind() {
945 ty::Dynamic(predicates, _) => {
946 // If the `dyn Trait` is not object safe, do not suggest `Box<dyn Trait>`.
947 predicates
948 .principal_def_id()
949 .map_or(true, |def_id| self.tcx.object_safety_violations(def_id).is_empty())
950 }
951 // We only want to suggest `impl Trait` to `dyn Trait`s.
952 // For example, `fn foo() -> str` needs to be filtered out.
953 _ => return false,
954 };
955
956 let ret_ty = if let hir::FnRetTy::Return(ret_ty) = sig.decl.output {
957 ret_ty
958 } else {
959 return false;
960 };
961
962 // Use `TypeVisitor` instead of the output type directly to find the span of `ty` for
963 // cases like `fn foo() -> (dyn Trait, i32) {}`.
964 // Recursively look for `TraitObject` types and if there's only one, use that span to
965 // suggest `impl Trait`.
966
967 // Visit to make sure there's a single `return` type to suggest `impl Trait`,
968 // otherwise suggest using `Box<dyn Trait>` or an enum.
969 let mut visitor = ReturnsVisitor::default();
970 visitor.visit_body(&body);
971
972 let typeck_results = self.in_progress_typeck_results.map(|t| t.borrow()).unwrap();
973
974 let mut ret_types = visitor
975 .returns
976 .iter()
977 .filter_map(|expr| typeck_results.node_type_opt(expr.hir_id))
978 .map(|ty| self.resolve_vars_if_possible(&ty));
979 let (last_ty, all_returns_have_same_type, only_never_return) = ret_types.clone().fold(
980 (None, true, true),
981 |(last_ty, mut same, only_never_return): (std::option::Option<Ty<'_>>, bool, bool),
982 ty| {
983 let ty = self.resolve_vars_if_possible(&ty);
984 same &=
985 !matches!(ty.kind(), ty::Error(_))
986 && last_ty.map_or(true, |last_ty| {
987 // FIXME: ideally we would use `can_coerce` here instead, but `typeck` comes
988 // *after* in the dependency graph.
989 match (ty.kind(), last_ty.kind()) {
990 (Infer(InferTy::IntVar(_)), Infer(InferTy::IntVar(_)))
991 | (Infer(InferTy::FloatVar(_)), Infer(InferTy::FloatVar(_)))
992 | (Infer(InferTy::FreshIntTy(_)), Infer(InferTy::FreshIntTy(_)))
993 | (
994 Infer(InferTy::FreshFloatTy(_)),
995 Infer(InferTy::FreshFloatTy(_)),
996 ) => true,
997 _ => ty == last_ty,
998 }
999 });
1000 (Some(ty), same, only_never_return && matches!(ty.kind(), ty::Never))
1001 },
1002 );
1003 let all_returns_conform_to_trait =
1004 if let Some(ty_ret_ty) = typeck_results.node_type_opt(ret_ty.hir_id) {
1005 match ty_ret_ty.kind() {
1006 ty::Dynamic(predicates, _) => {
1007 let cause = ObligationCause::misc(ret_ty.span, ret_ty.hir_id);
1008 let param_env = ty::ParamEnv::empty();
1009 only_never_return
1010 || ret_types.all(|returned_ty| {
1011 predicates.iter().all(|predicate| {
1012 let pred = predicate.with_self_ty(self.tcx, returned_ty);
1013 let obl = Obligation::new(cause.clone(), param_env, pred);
1014 self.predicate_may_hold(&obl)
1015 })
1016 })
1017 }
1018 _ => false,
1019 }
1020 } else {
1021 true
1022 };
1023
1024 let sm = self.tcx.sess.source_map();
1025 let snippet = if let (true, hir::TyKind::TraitObject(..), Ok(snippet), true) = (
1026 // Verify that we're dealing with a return `dyn Trait`
1027 ret_ty.span.overlaps(span),
1028 &ret_ty.kind,
1029 sm.span_to_snippet(ret_ty.span),
1030 // If any of the return types does not conform to the trait, then we can't
1031 // suggest `impl Trait` nor trait objects: it is a type mismatch error.
1032 all_returns_conform_to_trait,
1033 ) {
1034 snippet
1035 } else {
1036 return false;
1037 };
1038 err.code(error_code!(E0746));
1039 err.set_primary_message("return type cannot have an unboxed trait object");
1040 err.children.clear();
1041 let impl_trait_msg = "for information on `impl Trait`, see \
1042 <https://doc.rust-lang.org/book/ch10-02-traits.html\
1043 #returning-types-that-implement-traits>";
1044 let trait_obj_msg = "for information on trait objects, see \
1045 <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
1046 #using-trait-objects-that-allow-for-values-of-different-types>";
1047 let has_dyn = snippet.split_whitespace().next().map_or(false, |s| s == "dyn");
1048 let trait_obj = if has_dyn { &snippet[4..] } else { &snippet[..] };
1049 if only_never_return {
1050 // No return paths, probably using `panic!()` or similar.
1051 // Suggest `-> T`, `-> impl Trait`, and if `Trait` is object safe, `-> Box<dyn Trait>`.
1052 suggest_trait_object_return_type_alternatives(
1053 err,
1054 ret_ty.span,
1055 trait_obj,
1056 is_object_safe,
1057 );
1058 } else if let (Some(last_ty), true) = (last_ty, all_returns_have_same_type) {
1059 // Suggest `-> impl Trait`.
1060 err.span_suggestion(
1061 ret_ty.span,
1062 &format!(
1063 "use `impl {1}` as the return type, as all return paths are of type `{}`, \
1064 which implements `{1}`",
1065 last_ty, trait_obj,
1066 ),
1067 format!("impl {}", trait_obj),
1068 Applicability::MachineApplicable,
1069 );
1070 err.note(impl_trait_msg);
1071 } else {
1072 if is_object_safe {
1073 // Suggest `-> Box<dyn Trait>` and `Box::new(returned_value)`.
1074 // Get all the return values and collect their span and suggestion.
1075 if let Some(mut suggestions) = visitor
1076 .returns
1077 .iter()
1078 .map(|expr| {
1079 let snip = sm.span_to_snippet(expr.span).ok()?;
1080 Some((expr.span, format!("Box::new({})", snip)))
1081 })
1082 .collect::<Option<Vec<_>>>()
1083 {
1084 // Add the suggestion for the return type.
1085 suggestions.push((ret_ty.span, format!("Box<dyn {}>", trait_obj)));
1086 err.multipart_suggestion(
1087 "return a boxed trait object instead",
1088 suggestions,
1089 Applicability::MaybeIncorrect,
1090 );
1091 }
1092 } else {
1093 // This is currently not possible to trigger because E0038 takes precedence, but
1094 // leave it in for completeness in case anything changes in an earlier stage.
1095 err.note(&format!(
1096 "if trait `{}` was object safe, you could return a trait object",
1097 trait_obj,
1098 ));
1099 }
1100 err.note(trait_obj_msg);
1101 err.note(&format!(
1102 "if all the returned values were of the same type you could use `impl {}` as the \
1103 return type",
1104 trait_obj,
1105 ));
1106 err.note(impl_trait_msg);
1107 err.note("you can create a new `enum` with a variant for each returned type");
1108 }
1109 true
1110 }
1111
1112 fn point_at_returns_when_relevant(
1113 &self,
1114 err: &mut DiagnosticBuilder<'_>,
1115 obligation: &PredicateObligation<'tcx>,
1116 ) {
1117 match obligation.cause.code.peel_derives() {
1118 ObligationCauseCode::SizedReturnType => {}
1119 _ => return,
1120 }
1121
1122 let hir = self.tcx.hir();
1123 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1124 let node = hir.find(parent_node);
1125 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. })) =
1126 node
1127 {
1128 let body = hir.body(*body_id);
1129 // Point at all the `return`s in the function as they have failed trait bounds.
1130 let mut visitor = ReturnsVisitor::default();
1131 visitor.visit_body(&body);
1132 let typeck_results = self.in_progress_typeck_results.map(|t| t.borrow()).unwrap();
1133 for expr in &visitor.returns {
1134 if let Some(returned_ty) = typeck_results.node_type_opt(expr.hir_id) {
1135 let ty = self.resolve_vars_if_possible(&returned_ty);
1136 err.span_label(expr.span, &format!("this returned value is of type `{}`", ty));
1137 }
1138 }
1139 }
1140 }
1141
1142 fn report_closure_arg_mismatch(
1143 &self,
1144 span: Span,
1145 found_span: Option<Span>,
1146 expected_ref: ty::PolyTraitRef<'tcx>,
1147 found: ty::PolyTraitRef<'tcx>,
1148 ) -> DiagnosticBuilder<'tcx> {
1149 crate fn build_fn_sig_string<'tcx>(
1150 tcx: TyCtxt<'tcx>,
1151 trait_ref: ty::TraitRef<'tcx>,
1152 ) -> String {
1153 let inputs = trait_ref.substs.type_at(1);
1154 let sig = if let ty::Tuple(inputs) = inputs.kind() {
1155 tcx.mk_fn_sig(
1156 inputs.iter().map(|k| k.expect_ty()),
1157 tcx.mk_ty_infer(ty::TyVar(ty::TyVid { index: 0 })),
1158 false,
1159 hir::Unsafety::Normal,
1160 ::rustc_target::spec::abi::Abi::Rust,
1161 )
1162 } else {
1163 tcx.mk_fn_sig(
1164 ::std::iter::once(inputs),
1165 tcx.mk_ty_infer(ty::TyVar(ty::TyVid { index: 0 })),
1166 false,
1167 hir::Unsafety::Normal,
1168 ::rustc_target::spec::abi::Abi::Rust,
1169 )
1170 };
1171 ty::Binder::bind(sig).to_string()
1172 }
1173
1174 let argument_is_closure = expected_ref.skip_binder().substs.type_at(0).is_closure();
1175 let mut err = struct_span_err!(
1176 self.tcx.sess,
1177 span,
1178 E0631,
1179 "type mismatch in {} arguments",
1180 if argument_is_closure { "closure" } else { "function" }
1181 );
1182
1183 let found_str = format!(
1184 "expected signature of `{}`",
1185 build_fn_sig_string(self.tcx, found.skip_binder())
1186 );
1187 err.span_label(span, found_str);
1188
1189 let found_span = found_span.unwrap_or(span);
1190 let expected_str = format!(
1191 "found signature of `{}`",
1192 build_fn_sig_string(self.tcx, expected_ref.skip_binder())
1193 );
1194 err.span_label(found_span, expected_str);
1195
1196 err
1197 }
1198
1199 fn suggest_fully_qualified_path(
1200 &self,
1201 err: &mut DiagnosticBuilder<'_>,
1202 def_id: DefId,
1203 span: Span,
1204 trait_ref: DefId,
1205 ) {
1206 if let Some(assoc_item) = self.tcx.opt_associated_item(def_id) {
1207 if let ty::AssocKind::Const | ty::AssocKind::Type = assoc_item.kind {
1208 err.note(&format!(
1209 "{}s cannot be accessed directly on a `trait`, they can only be \
1210 accessed through a specific `impl`",
1211 assoc_item.kind.as_def_kind().descr(def_id)
1212 ));
1213 err.span_suggestion(
1214 span,
1215 "use the fully qualified path to an implementation",
1216 format!("<Type as {}>::{}", self.tcx.def_path_str(trait_ref), assoc_item.ident),
1217 Applicability::HasPlaceholders,
1218 );
1219 }
1220 }
1221 }
1222
1223 /// Adds an async-await specific note to the diagnostic when the future does not implement
1224 /// an auto trait because of a captured type.
1225 ///
1226 /// ```text
1227 /// note: future does not implement `Qux` as this value is used across an await
1228 /// --> $DIR/issue-64130-3-other.rs:17:5
1229 /// |
1230 /// LL | let x = Foo;
1231 /// | - has type `Foo`
1232 /// LL | baz().await;
1233 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1234 /// LL | }
1235 /// | - `x` is later dropped here
1236 /// ```
1237 ///
1238 /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
1239 /// is "replaced" with a different message and a more specific error.
1240 ///
1241 /// ```text
1242 /// error: future cannot be sent between threads safely
1243 /// --> $DIR/issue-64130-2-send.rs:21:5
1244 /// |
1245 /// LL | fn is_send<T: Send>(t: T) { }
1246 /// | ---- required by this bound in `is_send`
1247 /// ...
1248 /// LL | is_send(bar());
1249 /// | ^^^^^^^ future returned by `bar` is not send
1250 /// |
1251 /// = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
1252 /// implemented for `Foo`
1253 /// note: future is not send as this value is used across an await
1254 /// --> $DIR/issue-64130-2-send.rs:15:5
1255 /// |
1256 /// LL | let x = Foo;
1257 /// | - has type `Foo`
1258 /// LL | baz().await;
1259 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1260 /// LL | }
1261 /// | - `x` is later dropped here
1262 /// ```
1263 ///
1264 /// Returns `true` if an async-await specific note was added to the diagnostic.
1265 fn maybe_note_obligation_cause_for_async_await(
1266 &self,
1267 err: &mut DiagnosticBuilder<'_>,
1268 obligation: &PredicateObligation<'tcx>,
1269 ) -> bool {
1270 debug!(
1271 "maybe_note_obligation_cause_for_async_await: obligation.predicate={:?} \
1272 obligation.cause.span={:?}",
1273 obligation.predicate, obligation.cause.span
1274 );
1275 let hir = self.tcx.hir();
1276
1277 // Attempt to detect an async-await error by looking at the obligation causes, looking
1278 // for a generator to be present.
1279 //
1280 // When a future does not implement a trait because of a captured type in one of the
1281 // generators somewhere in the call stack, then the result is a chain of obligations.
1282 //
1283 // Given a `async fn` A that calls a `async fn` B which captures a non-send type and that
1284 // future is passed as an argument to a function C which requires a `Send` type, then the
1285 // chain looks something like this:
1286 //
1287 // - `BuiltinDerivedObligation` with a generator witness (B)
1288 // - `BuiltinDerivedObligation` with a generator (B)
1289 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (B)
1290 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1291 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1292 // - `BuiltinDerivedObligation` with a generator witness (A)
1293 // - `BuiltinDerivedObligation` with a generator (A)
1294 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (A)
1295 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1296 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1297 // - `BindingObligation` with `impl_send (Send requirement)
1298 //
1299 // The first obligation in the chain is the most useful and has the generator that captured
1300 // the type. The last generator (`outer_generator` below) has information about where the
1301 // bound was introduced. At least one generator should be present for this diagnostic to be
1302 // modified.
1303 let (mut trait_ref, mut target_ty) = match obligation.predicate.skip_binders() {
1304 ty::PredicateAtom::Trait(p, _) => (Some(p.trait_ref), Some(p.self_ty())),
1305 _ => (None, None),
1306 };
1307 let mut generator = None;
1308 let mut outer_generator = None;
1309 let mut next_code = Some(&obligation.cause.code);
1310 while let Some(code) = next_code {
1311 debug!("maybe_note_obligation_cause_for_async_await: code={:?}", code);
1312 match code {
1313 ObligationCauseCode::DerivedObligation(derived_obligation)
1314 | ObligationCauseCode::BuiltinDerivedObligation(derived_obligation)
1315 | ObligationCauseCode::ImplDerivedObligation(derived_obligation) => {
1316 let ty = derived_obligation.parent_trait_ref.skip_binder().self_ty();
1317 debug!(
1318 "maybe_note_obligation_cause_for_async_await: \
1319 parent_trait_ref={:?} self_ty.kind={:?}",
1320 derived_obligation.parent_trait_ref,
1321 ty.kind()
1322 );
1323
1324 match *ty.kind() {
1325 ty::Generator(did, ..) => {
1326 generator = generator.or(Some(did));
1327 outer_generator = Some(did);
1328 }
1329 ty::GeneratorWitness(..) => {}
1330 _ if generator.is_none() => {
1331 trait_ref = Some(derived_obligation.parent_trait_ref.skip_binder());
1332 target_ty = Some(ty);
1333 }
1334 _ => {}
1335 }
1336
1337 next_code = Some(derived_obligation.parent_code.as_ref());
1338 }
1339 _ => break,
1340 }
1341 }
1342
1343 // Only continue if a generator was found.
1344 debug!(
1345 "maybe_note_obligation_cause_for_async_await: generator={:?} trait_ref={:?} \
1346 target_ty={:?}",
1347 generator, trait_ref, target_ty
1348 );
1349 let (generator_did, trait_ref, target_ty) = match (generator, trait_ref, target_ty) {
1350 (Some(generator_did), Some(trait_ref), Some(target_ty)) => {
1351 (generator_did, trait_ref, target_ty)
1352 }
1353 _ => return false,
1354 };
1355
1356 let span = self.tcx.def_span(generator_did);
1357
1358 // Do not ICE on closure typeck (#66868).
1359 if !generator_did.is_local() {
1360 return false;
1361 }
1362
1363 // Get the typeck results from the infcx if the generator is the function we are
1364 // currently type-checking; otherwise, get them by performing a query.
1365 // This is needed to avoid cycles.
1366 let in_progress_typeck_results = self.in_progress_typeck_results.map(|t| t.borrow());
1367 let generator_did_root = self.tcx.closure_base_def_id(generator_did);
1368 debug!(
1369 "maybe_note_obligation_cause_for_async_await: generator_did={:?} \
1370 generator_did_root={:?} in_progress_typeck_results.hir_owner={:?} span={:?}",
1371 generator_did,
1372 generator_did_root,
1373 in_progress_typeck_results.as_ref().map(|t| t.hir_owner),
1374 span
1375 );
1376 let query_typeck_results;
1377 let typeck_results: &TypeckResults<'tcx> = match &in_progress_typeck_results {
1378 Some(t) if t.hir_owner.to_def_id() == generator_did_root => t,
1379 _ => {
1380 query_typeck_results = self.tcx.typeck(generator_did.expect_local());
1381 &query_typeck_results
1382 }
1383 };
1384
1385 let generator_body = generator_did
1386 .as_local()
1387 .map(|def_id| hir.local_def_id_to_hir_id(def_id))
1388 .and_then(|hir_id| hir.maybe_body_owned_by(hir_id))
1389 .map(|body_id| hir.body(body_id));
1390 let mut visitor = AwaitsVisitor::default();
1391 if let Some(body) = generator_body {
1392 visitor.visit_body(body);
1393 }
1394 debug!("maybe_note_obligation_cause_for_async_await: awaits = {:?}", visitor.awaits);
1395
1396 // Look for a type inside the generator interior that matches the target type to get
1397 // a span.
1398 let target_ty_erased = self.tcx.erase_regions(&target_ty);
1399 let ty_matches = |ty| -> bool {
1400 // Careful: the regions for types that appear in the
1401 // generator interior are not generally known, so we
1402 // want to erase them when comparing (and anyway,
1403 // `Send` and other bounds are generally unaffected by
1404 // the choice of region). When erasing regions, we
1405 // also have to erase late-bound regions. This is
1406 // because the types that appear in the generator
1407 // interior generally contain "bound regions" to
1408 // represent regions that are part of the suspended
1409 // generator frame. Bound regions are preserved by
1410 // `erase_regions` and so we must also call
1411 // `erase_late_bound_regions`.
1412 let ty_erased = self.tcx.erase_late_bound_regions(&ty::Binder::bind(ty));
1413 let ty_erased = self.tcx.erase_regions(&ty_erased);
1414 let eq = ty::TyS::same_type(ty_erased, target_ty_erased);
1415 debug!(
1416 "maybe_note_obligation_cause_for_async_await: ty_erased={:?} \
1417 target_ty_erased={:?} eq={:?}",
1418 ty_erased, target_ty_erased, eq
1419 );
1420 eq
1421 };
1422
1423 let mut interior_or_upvar_span = None;
1424 let mut interior_extra_info = None;
1425
1426 if let Some(upvars) = self.tcx.upvars_mentioned(generator_did) {
1427 interior_or_upvar_span = upvars.iter().find_map(|(upvar_id, upvar)| {
1428 let upvar_ty = typeck_results.node_type(*upvar_id);
1429 let upvar_ty = self.resolve_vars_if_possible(&upvar_ty);
1430 if ty_matches(&upvar_ty) {
1431 Some(GeneratorInteriorOrUpvar::Upvar(upvar.span))
1432 } else {
1433 None
1434 }
1435 });
1436 };
1437
1438 typeck_results
1439 .generator_interior_types
1440 .iter()
1441 .find(|ty::GeneratorInteriorTypeCause { ty, .. }| ty_matches(ty))
1442 .map(|cause| {
1443 // Check to see if any awaited expressions have the target type.
1444 let from_awaited_ty = visitor
1445 .awaits
1446 .into_iter()
1447 .map(|id| hir.expect_expr(id))
1448 .find(|await_expr| {
1449 let ty = typeck_results.expr_ty_adjusted(&await_expr);
1450 debug!(
1451 "maybe_note_obligation_cause_for_async_await: await_expr={:?}",
1452 await_expr
1453 );
1454 ty_matches(ty)
1455 })
1456 .map(|expr| expr.span);
1457 let ty::GeneratorInteriorTypeCause { span, scope_span, yield_span, expr, .. } =
1458 cause;
1459
1460 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(*span));
1461 interior_extra_info = Some((*scope_span, *yield_span, *expr, from_awaited_ty));
1462 });
1463
1464 debug!(
1465 "maybe_note_obligation_cause_for_async_await: interior_or_upvar={:?} \
1466 generator_interior_types={:?}",
1467 interior_or_upvar_span, typeck_results.generator_interior_types
1468 );
1469 if let Some(interior_or_upvar_span) = interior_or_upvar_span {
1470 self.note_obligation_cause_for_async_await(
1471 err,
1472 interior_or_upvar_span,
1473 interior_extra_info,
1474 generator_body,
1475 outer_generator,
1476 trait_ref,
1477 target_ty,
1478 typeck_results,
1479 obligation,
1480 next_code,
1481 );
1482 true
1483 } else {
1484 false
1485 }
1486 }
1487
1488 /// Unconditionally adds the diagnostic note described in
1489 /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
1490 fn note_obligation_cause_for_async_await(
1491 &self,
1492 err: &mut DiagnosticBuilder<'_>,
1493 interior_or_upvar_span: GeneratorInteriorOrUpvar,
1494 interior_extra_info: Option<(Option<Span>, Span, Option<hir::HirId>, Option<Span>)>,
1495 inner_generator_body: Option<&hir::Body<'tcx>>,
1496 outer_generator: Option<DefId>,
1497 trait_ref: ty::TraitRef<'tcx>,
1498 target_ty: Ty<'tcx>,
1499 typeck_results: &ty::TypeckResults<'tcx>,
1500 obligation: &PredicateObligation<'tcx>,
1501 next_code: Option<&ObligationCauseCode<'tcx>>,
1502 ) {
1503 let source_map = self.tcx.sess.source_map();
1504
1505 let is_async = inner_generator_body
1506 .and_then(|body| body.generator_kind())
1507 .map(|generator_kind| matches!(generator_kind, hir::GeneratorKind::Async(..)))
1508 .unwrap_or(false);
1509 let (await_or_yield, an_await_or_yield) =
1510 if is_async { ("await", "an await") } else { ("yield", "a yield") };
1511 let future_or_generator = if is_async { "future" } else { "generator" };
1512
1513 // Special case the primary error message when send or sync is the trait that was
1514 // not implemented.
1515 let is_send = self.tcx.is_diagnostic_item(sym::send_trait, trait_ref.def_id);
1516 let is_sync = self.tcx.is_diagnostic_item(sym::sync_trait, trait_ref.def_id);
1517 let hir = self.tcx.hir();
1518 let trait_explanation = if is_send || is_sync {
1519 let (trait_name, trait_verb) =
1520 if is_send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
1521
1522 err.clear_code();
1523 err.set_primary_message(format!(
1524 "{} cannot be {} between threads safely",
1525 future_or_generator, trait_verb
1526 ));
1527
1528 let original_span = err.span.primary_span().unwrap();
1529 let mut span = MultiSpan::from_span(original_span);
1530
1531 let message = outer_generator
1532 .and_then(|generator_did| {
1533 Some(match self.tcx.generator_kind(generator_did).unwrap() {
1534 GeneratorKind::Gen => format!("generator is not {}", trait_name),
1535 GeneratorKind::Async(AsyncGeneratorKind::Fn) => self
1536 .tcx
1537 .parent(generator_did)
1538 .and_then(|parent_did| parent_did.as_local())
1539 .map(|parent_did| hir.local_def_id_to_hir_id(parent_did))
1540 .and_then(|parent_hir_id| hir.opt_name(parent_hir_id))
1541 .map(|name| {
1542 format!("future returned by `{}` is not {}", name, trait_name)
1543 })?,
1544 GeneratorKind::Async(AsyncGeneratorKind::Block) => {
1545 format!("future created by async block is not {}", trait_name)
1546 }
1547 GeneratorKind::Async(AsyncGeneratorKind::Closure) => {
1548 format!("future created by async closure is not {}", trait_name)
1549 }
1550 })
1551 })
1552 .unwrap_or_else(|| format!("{} is not {}", future_or_generator, trait_name));
1553
1554 span.push_span_label(original_span, message);
1555 err.set_span(span);
1556
1557 format!("is not {}", trait_name)
1558 } else {
1559 format!("does not implement `{}`", trait_ref.print_only_trait_path())
1560 };
1561
1562 let mut explain_yield = |interior_span: Span,
1563 yield_span: Span,
1564 scope_span: Option<Span>| {
1565 let mut span = MultiSpan::from_span(yield_span);
1566 if let Ok(snippet) = source_map.span_to_snippet(interior_span) {
1567 span.push_span_label(
1568 yield_span,
1569 format!("{} occurs here, with `{}` maybe used later", await_or_yield, snippet),
1570 );
1571 // If available, use the scope span to annotate the drop location.
1572 if let Some(scope_span) = scope_span {
1573 span.push_span_label(
1574 source_map.end_point(scope_span),
1575 format!("`{}` is later dropped here", snippet),
1576 );
1577 }
1578 }
1579 span.push_span_label(
1580 interior_span,
1581 format!("has type `{}` which {}", target_ty, trait_explanation),
1582 );
1583
1584 err.span_note(
1585 span,
1586 &format!(
1587 "{} {} as this value is used across {}",
1588 future_or_generator, trait_explanation, an_await_or_yield
1589 ),
1590 );
1591 };
1592 match interior_or_upvar_span {
1593 GeneratorInteriorOrUpvar::Interior(interior_span) => {
1594 if let Some((scope_span, yield_span, expr, from_awaited_ty)) = interior_extra_info {
1595 if let Some(await_span) = from_awaited_ty {
1596 // The type causing this obligation is one being awaited at await_span.
1597 let mut span = MultiSpan::from_span(await_span);
1598 span.push_span_label(
1599 await_span,
1600 format!(
1601 "await occurs here on type `{}`, which {}",
1602 target_ty, trait_explanation
1603 ),
1604 );
1605 err.span_note(
1606 span,
1607 &format!(
1608 "future {not_trait} as it awaits another future which {not_trait}",
1609 not_trait = trait_explanation
1610 ),
1611 );
1612 } else {
1613 // Look at the last interior type to get a span for the `.await`.
1614 debug!(
1615 "note_obligation_cause_for_async_await generator_interior_types: {:#?}",
1616 typeck_results.generator_interior_types
1617 );
1618 explain_yield(interior_span, yield_span, scope_span);
1619 }
1620
1621 if let Some(expr_id) = expr {
1622 let expr = hir.expect_expr(expr_id);
1623 debug!("target_ty evaluated from {:?}", expr);
1624
1625 let parent = hir.get_parent_node(expr_id);
1626 if let Some(hir::Node::Expr(e)) = hir.find(parent) {
1627 let parent_span = hir.span(parent);
1628 let parent_did = parent.owner.to_def_id();
1629 // ```rust
1630 // impl T {
1631 // fn foo(&self) -> i32 {}
1632 // }
1633 // T.foo();
1634 // ^^^^^^^ a temporary `&T` created inside this method call due to `&self`
1635 // ```
1636 //
1637 let is_region_borrow = typeck_results
1638 .expr_adjustments(expr)
1639 .iter()
1640 .any(|adj| adj.is_region_borrow());
1641
1642 // ```rust
1643 // struct Foo(*const u8);
1644 // bar(Foo(std::ptr::null())).await;
1645 // ^^^^^^^^^^^^^^^^^^^^^ raw-ptr `*T` created inside this struct ctor.
1646 // ```
1647 debug!("parent_def_kind: {:?}", self.tcx.def_kind(parent_did));
1648 let is_raw_borrow_inside_fn_like_call =
1649 match self.tcx.def_kind(parent_did) {
1650 DefKind::Fn | DefKind::Ctor(..) => target_ty.is_unsafe_ptr(),
1651 _ => false,
1652 };
1653
1654 if (typeck_results.is_method_call(e) && is_region_borrow)
1655 || is_raw_borrow_inside_fn_like_call
1656 {
1657 err.span_help(
1658 parent_span,
1659 "consider moving this into a `let` \
1660 binding to create a shorter lived borrow",
1661 );
1662 }
1663 }
1664 }
1665 }
1666 }
1667 GeneratorInteriorOrUpvar::Upvar(upvar_span) => {
1668 let mut span = MultiSpan::from_span(upvar_span);
1669 span.push_span_label(
1670 upvar_span,
1671 format!("has type `{}` which {}", target_ty, trait_explanation),
1672 );
1673 err.span_note(span, &format!("captured value {}", trait_explanation));
1674 }
1675 }
1676
1677 // Add a note for the item obligation that remains - normally a note pointing to the
1678 // bound that introduced the obligation (e.g. `T: Send`).
1679 debug!("note_obligation_cause_for_async_await: next_code={:?}", next_code);
1680 self.note_obligation_cause_code(
1681 err,
1682 &obligation.predicate,
1683 next_code.unwrap(),
1684 &mut Vec::new(),
1685 );
1686 }
1687
1688 fn note_obligation_cause_code<T>(
1689 &self,
1690 err: &mut DiagnosticBuilder<'_>,
1691 predicate: &T,
1692 cause_code: &ObligationCauseCode<'tcx>,
1693 obligated_types: &mut Vec<&ty::TyS<'tcx>>,
1694 ) where
1695 T: fmt::Display,
1696 {
1697 let tcx = self.tcx;
1698 match *cause_code {
1699 ObligationCauseCode::ExprAssignable
1700 | ObligationCauseCode::MatchExpressionArm { .. }
1701 | ObligationCauseCode::Pattern { .. }
1702 | ObligationCauseCode::IfExpression { .. }
1703 | ObligationCauseCode::IfExpressionWithNoElse
1704 | ObligationCauseCode::MainFunctionType
1705 | ObligationCauseCode::StartFunctionType
1706 | ObligationCauseCode::IntrinsicType
1707 | ObligationCauseCode::MethodReceiver
1708 | ObligationCauseCode::ReturnNoExpression
1709 | ObligationCauseCode::UnifyReceiver(..)
1710 | ObligationCauseCode::MiscObligation => {}
1711 ObligationCauseCode::SliceOrArrayElem => {
1712 err.note("slice and array elements must have `Sized` type");
1713 }
1714 ObligationCauseCode::TupleElem => {
1715 err.note("only the last element of a tuple may have a dynamically sized type");
1716 }
1717 ObligationCauseCode::ProjectionWf(data) => {
1718 err.note(&format!("required so that the projection `{}` is well-formed", data,));
1719 }
1720 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
1721 err.note(&format!(
1722 "required so that reference `{}` does not outlive its referent",
1723 ref_ty,
1724 ));
1725 }
1726 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
1727 err.note(&format!(
1728 "required so that the lifetime bound of `{}` for `{}` is satisfied",
1729 region, object_ty,
1730 ));
1731 }
1732 ObligationCauseCode::ItemObligation(item_def_id) => {
1733 let item_name = tcx.def_path_str(item_def_id);
1734 let msg = format!("required by `{}`", item_name);
1735 if let Some(sp) = tcx.hir().span_if_local(item_def_id) {
1736 let sp = tcx.sess.source_map().guess_head_span(sp);
1737 err.span_label(sp, &msg);
1738 } else {
1739 err.note(&msg);
1740 }
1741 }
1742 ObligationCauseCode::BindingObligation(item_def_id, span) => {
1743 let item_name = tcx.def_path_str(item_def_id);
1744 let msg = format!("required by this bound in `{}`", item_name);
1745 if let Some(ident) = tcx.opt_item_name(item_def_id) {
1746 let sm = tcx.sess.source_map();
1747 let same_line =
1748 match (sm.lookup_line(ident.span.hi()), sm.lookup_line(span.lo())) {
1749 (Ok(l), Ok(r)) => l.line == r.line,
1750 _ => true,
1751 };
1752 if !ident.span.overlaps(span) && !same_line {
1753 err.span_label(ident.span, "required by a bound in this");
1754 }
1755 }
1756 if span != DUMMY_SP {
1757 err.span_label(span, &msg);
1758 } else {
1759 err.note(&msg);
1760 }
1761 }
1762 ObligationCauseCode::ObjectCastObligation(object_ty) => {
1763 err.note(&format!(
1764 "required for the cast to the object type `{}`",
1765 self.ty_to_string(object_ty)
1766 ));
1767 }
1768 ObligationCauseCode::Coercion { source: _, target } => {
1769 err.note(&format!("required by cast to type `{}`", self.ty_to_string(target)));
1770 }
1771 ObligationCauseCode::RepeatVec(suggest_const_in_array_repeat_expressions) => {
1772 err.note(
1773 "the `Copy` trait is required because the repeated element will be copied",
1774 );
1775 if suggest_const_in_array_repeat_expressions {
1776 err.note(
1777 "this array initializer can be evaluated at compile-time, see issue \
1778 #49147 <https://github.com/rust-lang/rust/issues/49147> \
1779 for more information",
1780 );
1781 if tcx.sess.opts.unstable_features.is_nightly_build() {
1782 err.help(
1783 "add `#![feature(const_in_array_repeat_expressions)]` to the \
1784 crate attributes to enable",
1785 );
1786 }
1787 }
1788 }
1789 ObligationCauseCode::VariableType(hir_id) => {
1790 let parent_node = self.tcx.hir().get_parent_node(hir_id);
1791 match self.tcx.hir().find(parent_node) {
1792 Some(Node::Local(hir::Local {
1793 init: Some(hir::Expr { kind: hir::ExprKind::Index(_, _), span, .. }),
1794 ..
1795 })) => {
1796 // When encountering an assignment of an unsized trait, like
1797 // `let x = ""[..];`, provide a suggestion to borrow the initializer in
1798 // order to use have a slice instead.
1799 err.span_suggestion_verbose(
1800 span.shrink_to_lo(),
1801 "consider borrowing here",
1802 "&".to_owned(),
1803 Applicability::MachineApplicable,
1804 );
1805 err.note("all local variables must have a statically known size");
1806 }
1807 Some(Node::Param(param)) => {
1808 err.span_suggestion_verbose(
1809 param.ty_span.shrink_to_lo(),
1810 "function arguments must have a statically known size, borrowed types \
1811 always have a known size",
1812 "&".to_owned(),
1813 Applicability::MachineApplicable,
1814 );
1815 }
1816 _ => {
1817 err.note("all local variables must have a statically known size");
1818 }
1819 }
1820 if !self.tcx.features().unsized_locals {
1821 err.help("unsized locals are gated as an unstable feature");
1822 }
1823 }
1824 ObligationCauseCode::SizedArgumentType(sp) => {
1825 if let Some(span) = sp {
1826 err.span_suggestion_verbose(
1827 span.shrink_to_lo(),
1828 "function arguments must have a statically known size, borrowed types \
1829 always have a known size",
1830 "&".to_string(),
1831 Applicability::MachineApplicable,
1832 );
1833 } else {
1834 err.note("all function arguments must have a statically known size");
1835 }
1836 if tcx.sess.opts.unstable_features.is_nightly_build()
1837 && !self.tcx.features().unsized_locals
1838 {
1839 err.help("unsized locals are gated as an unstable feature");
1840 }
1841 }
1842 ObligationCauseCode::SizedReturnType => {
1843 err.note("the return type of a function must have a statically known size");
1844 }
1845 ObligationCauseCode::SizedYieldType => {
1846 err.note("the yield type of a generator must have a statically known size");
1847 }
1848 ObligationCauseCode::AssignmentLhsSized => {
1849 err.note("the left-hand-side of an assignment must have a statically known size");
1850 }
1851 ObligationCauseCode::TupleInitializerSized => {
1852 err.note("tuples must have a statically known size to be initialized");
1853 }
1854 ObligationCauseCode::StructInitializerSized => {
1855 err.note("structs must have a statically known size to be initialized");
1856 }
1857 ObligationCauseCode::FieldSized { adt_kind: ref item, last, span } => {
1858 match *item {
1859 AdtKind::Struct => {
1860 if last {
1861 err.note(
1862 "the last field of a packed struct may only have a \
1863 dynamically sized type if it does not need drop to be run",
1864 );
1865 } else {
1866 err.note(
1867 "only the last field of a struct may have a dynamically sized type",
1868 );
1869 }
1870 }
1871 AdtKind::Union => {
1872 err.note("no field of a union may have a dynamically sized type");
1873 }
1874 AdtKind::Enum => {
1875 err.note("no field of an enum variant may have a dynamically sized type");
1876 }
1877 }
1878 err.help("change the field's type to have a statically known size");
1879 err.span_suggestion(
1880 span.shrink_to_lo(),
1881 "borrowed types always have a statically known size",
1882 "&".to_string(),
1883 Applicability::MachineApplicable,
1884 );
1885 err.multipart_suggestion(
1886 "the `Box` type always has a statically known size and allocates its contents \
1887 in the heap",
1888 vec![
1889 (span.shrink_to_lo(), "Box<".to_string()),
1890 (span.shrink_to_hi(), ">".to_string()),
1891 ],
1892 Applicability::MachineApplicable,
1893 );
1894 }
1895 ObligationCauseCode::ConstSized => {
1896 err.note("constant expressions must have a statically known size");
1897 }
1898 ObligationCauseCode::InlineAsmSized => {
1899 err.note("all inline asm arguments must have a statically known size");
1900 }
1901 ObligationCauseCode::ConstPatternStructural => {
1902 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
1903 }
1904 ObligationCauseCode::SharedStatic => {
1905 err.note("shared static variables must have a type that implements `Sync`");
1906 }
1907 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
1908 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
1909 let ty = parent_trait_ref.skip_binder().self_ty();
1910 err.note(&format!("required because it appears within the type `{}`", ty));
1911 obligated_types.push(ty);
1912
1913 let parent_predicate = parent_trait_ref.without_const().to_predicate(tcx);
1914 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
1915 // #74711: avoid a stack overflow
1916 ensure_sufficient_stack(|| {
1917 self.note_obligation_cause_code(
1918 err,
1919 &parent_predicate,
1920 &data.parent_code,
1921 obligated_types,
1922 )
1923 });
1924 }
1925 }
1926 ObligationCauseCode::ImplDerivedObligation(ref data) => {
1927 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
1928 err.note(&format!(
1929 "required because of the requirements on the impl of `{}` for `{}`",
1930 parent_trait_ref.print_only_trait_path(),
1931 parent_trait_ref.skip_binder().self_ty()
1932 ));
1933 let parent_predicate = parent_trait_ref.without_const().to_predicate(tcx);
1934 // #74711: avoid a stack overflow
1935 ensure_sufficient_stack(|| {
1936 self.note_obligation_cause_code(
1937 err,
1938 &parent_predicate,
1939 &data.parent_code,
1940 obligated_types,
1941 )
1942 });
1943 }
1944 ObligationCauseCode::DerivedObligation(ref data) => {
1945 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
1946 let parent_predicate = parent_trait_ref.without_const().to_predicate(tcx);
1947 // #74711: avoid a stack overflow
1948 ensure_sufficient_stack(|| {
1949 self.note_obligation_cause_code(
1950 err,
1951 &parent_predicate,
1952 &data.parent_code,
1953 obligated_types,
1954 )
1955 });
1956 }
1957 ObligationCauseCode::CompareImplMethodObligation { .. } => {
1958 err.note(&format!(
1959 "the requirement `{}` appears on the impl method \
1960 but not on the corresponding trait method",
1961 predicate
1962 ));
1963 }
1964 ObligationCauseCode::CompareImplTypeObligation { .. } => {
1965 err.note(&format!(
1966 "the requirement `{}` appears on the associated impl type \
1967 but not on the corresponding associated trait type",
1968 predicate
1969 ));
1970 }
1971 ObligationCauseCode::CompareImplConstObligation => {
1972 err.note(&format!(
1973 "the requirement `{}` appears on the associated impl constant \
1974 but not on the corresponding associated trait constant",
1975 predicate
1976 ));
1977 }
1978 ObligationCauseCode::ReturnType
1979 | ObligationCauseCode::ReturnValue(_)
1980 | ObligationCauseCode::BlockTailExpression(_) => (),
1981 ObligationCauseCode::TrivialBound => {
1982 err.help("see issue #48214");
1983 if tcx.sess.opts.unstable_features.is_nightly_build() {
1984 err.help("add `#![feature(trivial_bounds)]` to the crate attributes to enable");
1985 }
1986 }
1987 }
1988 }
1989
1990 fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder<'_>) {
1991 let current_limit = self.tcx.sess.recursion_limit();
1992 let suggested_limit = current_limit * 2;
1993 err.help(&format!(
1994 "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate (`{}`)",
1995 suggested_limit, self.tcx.crate_name,
1996 ));
1997 }
1998
1999 fn suggest_await_before_try(
2000 &self,
2001 err: &mut DiagnosticBuilder<'_>,
2002 obligation: &PredicateObligation<'tcx>,
2003 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
2004 span: Span,
2005 ) {
2006 debug!(
2007 "suggest_await_before_try: obligation={:?}, span={:?}, trait_ref={:?}, trait_ref_self_ty={:?}",
2008 obligation,
2009 span,
2010 trait_ref,
2011 trait_ref.self_ty()
2012 );
2013 let body_hir_id = obligation.cause.body_id;
2014 let item_id = self.tcx.hir().get_parent_node(body_hir_id);
2015
2016 if let Some(body_id) = self.tcx.hir().maybe_body_owned_by(item_id) {
2017 let body = self.tcx.hir().body(body_id);
2018 if let Some(hir::GeneratorKind::Async(_)) = body.generator_kind {
2019 let future_trait = self.tcx.require_lang_item(LangItem::Future, None);
2020
2021 let self_ty = self.resolve_vars_if_possible(&trait_ref.self_ty());
2022
2023 // Do not check on infer_types to avoid panic in evaluate_obligation.
2024 if self_ty.has_infer_types() {
2025 return;
2026 }
2027 let self_ty = self.tcx.erase_regions(&self_ty);
2028
2029 let impls_future = self.tcx.type_implements_trait((
2030 future_trait,
2031 self_ty.skip_binder(),
2032 ty::List::empty(),
2033 obligation.param_env,
2034 ));
2035
2036 let item_def_id = self
2037 .tcx
2038 .associated_items(future_trait)
2039 .in_definition_order()
2040 .next()
2041 .unwrap()
2042 .def_id;
2043 // `<T as Future>::Output`
2044 let projection_ty = ty::ProjectionTy {
2045 // `T`
2046 substs: self.tcx.mk_substs_trait(
2047 trait_ref.self_ty().skip_binder(),
2048 self.fresh_substs_for_item(span, item_def_id),
2049 ),
2050 // `Future::Output`
2051 item_def_id,
2052 };
2053
2054 let mut selcx = SelectionContext::new(self);
2055
2056 let mut obligations = vec![];
2057 let normalized_ty = normalize_projection_type(
2058 &mut selcx,
2059 obligation.param_env,
2060 projection_ty,
2061 obligation.cause.clone(),
2062 0,
2063 &mut obligations,
2064 );
2065
2066 debug!(
2067 "suggest_await_before_try: normalized_projection_type {:?}",
2068 self.resolve_vars_if_possible(&normalized_ty)
2069 );
2070 let try_obligation = self.mk_trait_obligation_with_new_self_ty(
2071 obligation.param_env,
2072 trait_ref,
2073 normalized_ty,
2074 );
2075 debug!("suggest_await_before_try: try_trait_obligation {:?}", try_obligation);
2076 if self.predicate_may_hold(&try_obligation) && impls_future {
2077 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
2078 if snippet.ends_with('?') {
2079 err.span_suggestion(
2080 span,
2081 "consider using `.await` here",
2082 format!("{}.await?", snippet.trim_end_matches('?')),
2083 Applicability::MaybeIncorrect,
2084 );
2085 }
2086 }
2087 }
2088 }
2089 }
2090 }
2091 }
2092
2093 /// Collect all the returned expressions within the input expression.
2094 /// Used to point at the return spans when we want to suggest some change to them.
2095 #[derive(Default)]
2096 pub struct ReturnsVisitor<'v> {
2097 pub returns: Vec<&'v hir::Expr<'v>>,
2098 in_block_tail: bool,
2099 }
2100
2101 impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
2102 type Map = hir::intravisit::ErasedMap<'v>;
2103
2104 fn nested_visit_map(&mut self) -> hir::intravisit::NestedVisitorMap<Self::Map> {
2105 hir::intravisit::NestedVisitorMap::None
2106 }
2107
2108 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
2109 // Visit every expression to detect `return` paths, either through the function's tail
2110 // expression or `return` statements. We walk all nodes to find `return` statements, but
2111 // we only care about tail expressions when `in_block_tail` is `true`, which means that
2112 // they're in the return path of the function body.
2113 match ex.kind {
2114 hir::ExprKind::Ret(Some(ex)) => {
2115 self.returns.push(ex);
2116 }
2117 hir::ExprKind::Block(block, _) if self.in_block_tail => {
2118 self.in_block_tail = false;
2119 for stmt in block.stmts {
2120 hir::intravisit::walk_stmt(self, stmt);
2121 }
2122 self.in_block_tail = true;
2123 if let Some(expr) = block.expr {
2124 self.visit_expr(expr);
2125 }
2126 }
2127 hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
2128 for arm in arms {
2129 self.visit_expr(arm.body);
2130 }
2131 }
2132 // We need to walk to find `return`s in the entire body.
2133 _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
2134 _ => self.returns.push(ex),
2135 }
2136 }
2137
2138 fn visit_body(&mut self, body: &'v hir::Body<'v>) {
2139 assert!(!self.in_block_tail);
2140 if body.generator_kind().is_none() {
2141 if let hir::ExprKind::Block(block, None) = body.value.kind {
2142 if block.expr.is_some() {
2143 self.in_block_tail = true;
2144 }
2145 }
2146 }
2147 hir::intravisit::walk_body(self, body);
2148 }
2149 }
2150
2151 /// Collect all the awaited expressions within the input expression.
2152 #[derive(Default)]
2153 struct AwaitsVisitor {
2154 awaits: Vec<hir::HirId>,
2155 }
2156
2157 impl<'v> Visitor<'v> for AwaitsVisitor {
2158 type Map = hir::intravisit::ErasedMap<'v>;
2159
2160 fn nested_visit_map(&mut self) -> hir::intravisit::NestedVisitorMap<Self::Map> {
2161 hir::intravisit::NestedVisitorMap::None
2162 }
2163
2164 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
2165 if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
2166 self.awaits.push(id)
2167 }
2168 hir::intravisit::walk_expr(self, ex)
2169 }
2170 }
2171
2172 pub trait NextTypeParamName {
2173 fn next_type_param_name(&self, name: Option<&str>) -> String;
2174 }
2175
2176 impl NextTypeParamName for &[hir::GenericParam<'_>] {
2177 fn next_type_param_name(&self, name: Option<&str>) -> String {
2178 // This is the list of possible parameter names that we might suggest.
2179 let name = name.and_then(|n| n.chars().next()).map(|c| c.to_string().to_uppercase());
2180 let name = name.as_deref();
2181 let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
2182 let used_names = self
2183 .iter()
2184 .filter_map(|p| match p.name {
2185 hir::ParamName::Plain(ident) => Some(ident.name),
2186 _ => None,
2187 })
2188 .collect::<Vec<_>>();
2189
2190 possible_names
2191 .iter()
2192 .find(|n| !used_names.contains(&Symbol::intern(n)))
2193 .unwrap_or(&"ParamName")
2194 .to_string()
2195 }
2196 }
2197
2198 fn suggest_trait_object_return_type_alternatives(
2199 err: &mut DiagnosticBuilder<'_>,
2200 ret_ty: Span,
2201 trait_obj: &str,
2202 is_object_safe: bool,
2203 ) {
2204 err.span_suggestion(
2205 ret_ty,
2206 "use some type `T` that is `T: Sized` as the return type if all return paths have the \
2207 same type",
2208 "T".to_string(),
2209 Applicability::MaybeIncorrect,
2210 );
2211 err.span_suggestion(
2212 ret_ty,
2213 &format!(
2214 "use `impl {}` as the return type if all return paths have the same type but you \
2215 want to expose only the trait in the signature",
2216 trait_obj,
2217 ),
2218 format!("impl {}", trait_obj),
2219 Applicability::MaybeIncorrect,
2220 );
2221 if is_object_safe {
2222 err.span_suggestion(
2223 ret_ty,
2224 &format!(
2225 "use a boxed trait object if all return paths implement trait `{}`",
2226 trait_obj,
2227 ),
2228 format!("Box<dyn {}>", trait_obj),
2229 Applicability::MaybeIncorrect,
2230 );
2231 }
2232 }