]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_infer/src/infer/error_reporting/note_and_explain.rs
Remove astconv usage in diagnostic
[rust.git] / compiler / rustc_infer / src / infer / error_reporting / note_and_explain.rs
1 use super::TypeErrCtxt;
2 use rustc_errors::Applicability::{MachineApplicable, MaybeIncorrect};
3 use rustc_errors::{pluralize, Diagnostic, MultiSpan};
4 use rustc_hir::{self as hir, def::DefKind};
5 use rustc_middle::traits::ObligationCauseCode;
6 use rustc_middle::ty::error::ExpectedFound;
7 use rustc_middle::ty::print::Printer;
8 use rustc_middle::{
9     traits::ObligationCause,
10     ty::{self, error::TypeError, print::FmtPrinter, suggest_constraining_type_param, Ty},
11 };
12 use rustc_span::{def_id::DefId, sym, BytePos, Span, Symbol};
13
14 impl<'tcx> TypeErrCtxt<'_, 'tcx> {
15     pub fn note_and_explain_type_err(
16         &self,
17         diag: &mut Diagnostic,
18         err: TypeError<'tcx>,
19         cause: &ObligationCause<'tcx>,
20         sp: Span,
21         body_owner_def_id: DefId,
22     ) {
23         use ty::error::TypeError::*;
24         debug!("note_and_explain_type_err err={:?} cause={:?}", err, cause);
25
26         let tcx = self.tcx;
27
28         match err {
29             ArgumentSorts(values, _) | Sorts(values) => {
30                 match (values.expected.kind(), values.found.kind()) {
31                     (ty::Closure(..), ty::Closure(..)) => {
32                         diag.note("no two closures, even if identical, have the same type");
33                         diag.help("consider boxing your closure and/or using it as a trait object");
34                     }
35                     (ty::Alias(ty::Opaque, ..), ty::Alias(ty::Opaque, ..)) => {
36                         // Issue #63167
37                         diag.note("distinct uses of `impl Trait` result in different opaque types");
38                     }
39                     (ty::Float(_), ty::Infer(ty::IntVar(_)))
40                         if let Ok(
41                             // Issue #53280
42                             snippet,
43                         ) = tcx.sess.source_map().span_to_snippet(sp) =>
44                     {
45                         if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
46                             diag.span_suggestion(
47                                 sp,
48                                 "use a float literal",
49                                 format!("{}.0", snippet),
50                                 MachineApplicable,
51                             );
52                         }
53                     }
54                     (ty::Param(expected), ty::Param(found)) => {
55                         let generics = tcx.generics_of(body_owner_def_id);
56                         let e_span = tcx.def_span(generics.type_param(expected, tcx).def_id);
57                         if !sp.contains(e_span) {
58                             diag.span_label(e_span, "expected type parameter");
59                         }
60                         let f_span = tcx.def_span(generics.type_param(found, tcx).def_id);
61                         if !sp.contains(f_span) {
62                             diag.span_label(f_span, "found type parameter");
63                         }
64                         diag.note(
65                             "a type parameter was expected, but a different one was found; \
66                              you might be missing a type parameter or trait bound",
67                         );
68                         diag.note(
69                             "for more information, visit \
70                              https://doc.rust-lang.org/book/ch10-02-traits.html\
71                              #traits-as-parameters",
72                         );
73                     }
74                     (ty::Alias(ty::Projection, _), ty::Alias(ty::Projection, _)) => {
75                         diag.note("an associated type was expected, but a different one was found");
76                     }
77                     (ty::Param(p), ty::Alias(ty::Projection, proj)) | (ty::Alias(ty::Projection, proj), ty::Param(p))
78                         if tcx.def_kind(proj.def_id) != DefKind::ImplTraitPlaceholder =>
79                     {
80                         let generics = tcx.generics_of(body_owner_def_id);
81                         let p_span = tcx.def_span(generics.type_param(p, tcx).def_id);
82                         if !sp.contains(p_span) {
83                             diag.span_label(p_span, "this type parameter");
84                         }
85                         let hir = tcx.hir();
86                         let mut note = true;
87                         if let Some(generics) = generics
88                             .type_param(p, tcx)
89                             .def_id
90                             .as_local()
91                             .map(|id| hir.local_def_id_to_hir_id(id))
92                             .and_then(|id| tcx.hir().find_parent(id))
93                             .as_ref()
94                             .and_then(|node| node.generics())
95                         {
96                             // Synthesize the associated type restriction `Add<Output = Expected>`.
97                             // FIXME: extract this logic for use in other diagnostics.
98                             let (trait_ref, assoc_substs) = proj.trait_ref_and_own_substs(tcx);
99                             let path =
100                                 tcx.def_path_str_with_substs(trait_ref.def_id, trait_ref.substs);
101                             let item_name = tcx.item_name(proj.def_id);
102                             let item_args = self.format_generic_args(assoc_substs);
103
104                             let path = if path.ends_with('>') {
105                                 format!(
106                                     "{}, {}{} = {}>",
107                                     &path[..path.len() - 1],
108                                     item_name,
109                                     item_args,
110                                     p
111                                 )
112                             } else {
113                                 format!("{}<{}{} = {}>", path, item_name, item_args, p)
114                             };
115                             note = !suggest_constraining_type_param(
116                                 tcx,
117                                 generics,
118                                 diag,
119                                 &format!("{}", proj.self_ty()),
120                                 &path,
121                                 None,
122                             );
123                         }
124                         if note {
125                             diag.note("you might be missing a type parameter or trait bound");
126                         }
127                     }
128                     (ty::Param(p), ty::Dynamic(..) | ty::Alias(ty::Opaque, ..))
129                     | (ty::Dynamic(..) | ty::Alias(ty::Opaque, ..), ty::Param(p)) => {
130                         let generics = tcx.generics_of(body_owner_def_id);
131                         let p_span = tcx.def_span(generics.type_param(p, tcx).def_id);
132                         if !sp.contains(p_span) {
133                             diag.span_label(p_span, "this type parameter");
134                         }
135                         diag.help("type parameters must be constrained to match other types");
136                         if tcx.sess.teach(&diag.get_code().unwrap()) {
137                             diag.help(
138                                 "given a type parameter `T` and a method `foo`:
139 ```
140 trait Trait<T> { fn foo(&self) -> T; }
141 ```
142 the only ways to implement method `foo` are:
143 - constrain `T` with an explicit type:
144 ```
145 impl Trait<String> for X {
146     fn foo(&self) -> String { String::new() }
147 }
148 ```
149 - add a trait bound to `T` and call a method on that trait that returns `Self`:
150 ```
151 impl<T: std::default::Default> Trait<T> for X {
152     fn foo(&self) -> T { <T as std::default::Default>::default() }
153 }
154 ```
155 - change `foo` to return an argument of type `T`:
156 ```
157 impl<T> Trait<T> for X {
158     fn foo(&self, x: T) -> T { x }
159 }
160 ```",
161                             );
162                         }
163                         diag.note(
164                             "for more information, visit \
165                              https://doc.rust-lang.org/book/ch10-02-traits.html\
166                              #traits-as-parameters",
167                         );
168                     }
169                     (ty::Param(p), ty::Closure(..) | ty::Generator(..)) => {
170                         let generics = tcx.generics_of(body_owner_def_id);
171                         let p_span = tcx.def_span(generics.type_param(p, tcx).def_id);
172                         if !sp.contains(p_span) {
173                             diag.span_label(p_span, "this type parameter");
174                         }
175                         diag.help(&format!(
176                             "every closure has a distinct type and so could not always match the \
177                              caller-chosen type of parameter `{}`",
178                             p
179                         ));
180                     }
181                     (ty::Param(p), _) | (_, ty::Param(p)) => {
182                         let generics = tcx.generics_of(body_owner_def_id);
183                         let p_span = tcx.def_span(generics.type_param(p, tcx).def_id);
184                         if !sp.contains(p_span) {
185                             diag.span_label(p_span, "this type parameter");
186                         }
187                     }
188                     (ty::Alias(ty::Projection, proj_ty), _) if tcx.def_kind(proj_ty.def_id) != DefKind::ImplTraitPlaceholder => {
189                         self.expected_projection(
190                             diag,
191                             proj_ty,
192                             values,
193                             body_owner_def_id,
194                             cause.code(),
195                         );
196                     }
197                     (_, ty::Alias(ty::Projection, proj_ty)) if tcx.def_kind(proj_ty.def_id) != DefKind::ImplTraitPlaceholder => {
198                         let msg = format!(
199                             "consider constraining the associated type `{}` to `{}`",
200                             values.found, values.expected,
201                         );
202                         if !(self.suggest_constraining_opaque_associated_type(
203                             diag,
204                             &msg,
205                             proj_ty,
206                             values.expected,
207                         ) || self.suggest_constraint(
208                             diag,
209                             &msg,
210                             body_owner_def_id,
211                             proj_ty,
212                             values.expected,
213                         )) {
214                             diag.help(&msg);
215                             diag.note(
216                                 "for more information, visit \
217                                 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
218                             );
219                         }
220                     }
221                     (ty::FnPtr(_), ty::FnDef(def, _))
222                     if let hir::def::DefKind::Fn = tcx.def_kind(def) => {
223                         diag.note(
224                             "when the arguments and return types match, functions can be coerced \
225                              to function pointers",
226                         );
227                     }
228                     _ => {}
229                 }
230                 debug!(
231                     "note_and_explain_type_err expected={:?} ({:?}) found={:?} ({:?})",
232                     values.expected,
233                     values.expected.kind(),
234                     values.found,
235                     values.found.kind(),
236                 );
237             }
238             CyclicTy(ty) => {
239                 // Watch out for various cases of cyclic types and try to explain.
240                 if ty.is_closure() || ty.is_generator() {
241                     diag.note(
242                         "closures cannot capture themselves or take themselves as argument;\n\
243                          this error may be the result of a recent compiler bug-fix,\n\
244                          see issue #46062 <https://github.com/rust-lang/rust/issues/46062>\n\
245                          for more information",
246                     );
247                 }
248             }
249             TargetFeatureCast(def_id) => {
250                 let target_spans = tcx.get_attrs(def_id, sym::target_feature).map(|attr| attr.span);
251                 diag.note(
252                     "functions with `#[target_feature]` can only be coerced to `unsafe` function pointers"
253                 );
254                 diag.span_labels(target_spans, "`#[target_feature]` added here");
255             }
256             _ => {}
257         }
258     }
259
260     fn suggest_constraint(
261         &self,
262         diag: &mut Diagnostic,
263         msg: &str,
264         body_owner_def_id: DefId,
265         proj_ty: &ty::AliasTy<'tcx>,
266         ty: Ty<'tcx>,
267     ) -> bool {
268         let tcx = self.tcx;
269         let assoc = tcx.associated_item(proj_ty.def_id);
270         let (trait_ref, assoc_substs) = proj_ty.trait_ref_and_own_substs(tcx);
271         if let Some(item) = tcx.hir().get_if_local(body_owner_def_id) {
272             if let Some(hir_generics) = item.generics() {
273                 // Get the `DefId` for the type parameter corresponding to `A` in `<A as T>::Foo`.
274                 // This will also work for `impl Trait`.
275                 let def_id = if let ty::Param(param_ty) = proj_ty.self_ty().kind() {
276                     let generics = tcx.generics_of(body_owner_def_id);
277                     generics.type_param(param_ty, tcx).def_id
278                 } else {
279                     return false;
280                 };
281                 let Some(def_id) = def_id.as_local() else {
282                     return false;
283                 };
284
285                 // First look in the `where` clause, as this might be
286                 // `fn foo<T>(x: T) where T: Trait`.
287                 for pred in hir_generics.bounds_for_param(def_id) {
288                     if self.constrain_generic_bound_associated_type_structured_suggestion(
289                         diag,
290                         &trait_ref,
291                         pred.bounds,
292                         &assoc,
293                         assoc_substs,
294                         ty,
295                         msg,
296                         false,
297                     ) {
298                         return true;
299                     }
300                 }
301             }
302         }
303         false
304     }
305
306     /// An associated type was expected and a different type was found.
307     ///
308     /// We perform a few different checks to see what we can suggest:
309     ///
310     ///  - In the current item, look for associated functions that return the expected type and
311     ///    suggest calling them. (Not a structured suggestion.)
312     ///  - If any of the item's generic bounds can be constrained, we suggest constraining the
313     ///    associated type to the found type.
314     ///  - If the associated type has a default type and was expected inside of a `trait`, we
315     ///    mention that this is disallowed.
316     ///  - If all other things fail, and the error is not because of a mismatch between the `trait`
317     ///    and the `impl`, we provide a generic `help` to constrain the assoc type or call an assoc
318     ///    fn that returns the type.
319     fn expected_projection(
320         &self,
321         diag: &mut Diagnostic,
322         proj_ty: &ty::AliasTy<'tcx>,
323         values: ExpectedFound<Ty<'tcx>>,
324         body_owner_def_id: DefId,
325         cause_code: &ObligationCauseCode<'_>,
326     ) {
327         let tcx = self.tcx;
328
329         let msg = format!(
330             "consider constraining the associated type `{}` to `{}`",
331             values.expected, values.found
332         );
333         let body_owner = tcx.hir().get_if_local(body_owner_def_id);
334         let current_method_ident = body_owner.and_then(|n| n.ident()).map(|i| i.name);
335
336         // We don't want to suggest calling an assoc fn in a scope where that isn't feasible.
337         let callable_scope = matches!(
338             body_owner,
339             Some(
340                 hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(..), .. })
341                     | hir::Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(..), .. })
342                     | hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }),
343             )
344         );
345         let impl_comparison =
346             matches!(cause_code, ObligationCauseCode::CompareImplItemObligation { .. });
347         let assoc = tcx.associated_item(proj_ty.def_id);
348         if !callable_scope || impl_comparison {
349             // We do not want to suggest calling functions when the reason of the
350             // type error is a comparison of an `impl` with its `trait` or when the
351             // scope is outside of a `Body`.
352         } else {
353             // If we find a suitable associated function that returns the expected type, we don't
354             // want the more general suggestion later in this method about "consider constraining
355             // the associated type or calling a method that returns the associated type".
356             let point_at_assoc_fn = self.point_at_methods_that_satisfy_associated_type(
357                 diag,
358                 assoc.container_id(tcx),
359                 current_method_ident,
360                 proj_ty.def_id,
361                 values.expected,
362             );
363             // Possibly suggest constraining the associated type to conform to the
364             // found type.
365             if self.suggest_constraint(diag, &msg, body_owner_def_id, proj_ty, values.found)
366                 || point_at_assoc_fn
367             {
368                 return;
369             }
370         }
371
372         self.suggest_constraining_opaque_associated_type(diag, &msg, proj_ty, values.found);
373
374         if self.point_at_associated_type(diag, body_owner_def_id, values.found) {
375             return;
376         }
377
378         if !impl_comparison {
379             // Generic suggestion when we can't be more specific.
380             if callable_scope {
381                 diag.help(&format!(
382                     "{} or calling a method that returns `{}`",
383                     msg, values.expected
384                 ));
385             } else {
386                 diag.help(&msg);
387             }
388             diag.note(
389                 "for more information, visit \
390                  https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
391             );
392         }
393         if tcx.sess.teach(&diag.get_code().unwrap()) {
394             diag.help(
395                 "given an associated type `T` and a method `foo`:
396 ```
397 trait Trait {
398 type T;
399 fn foo(&self) -> Self::T;
400 }
401 ```
402 the only way of implementing method `foo` is to constrain `T` with an explicit associated type:
403 ```
404 impl Trait for X {
405 type T = String;
406 fn foo(&self) -> Self::T { String::new() }
407 }
408 ```",
409             );
410         }
411     }
412
413     /// When the expected `impl Trait` is not defined in the current item, it will come from
414     /// a return type. This can occur when dealing with `TryStream` (#71035).
415     fn suggest_constraining_opaque_associated_type(
416         &self,
417         diag: &mut Diagnostic,
418         msg: &str,
419         proj_ty: &ty::AliasTy<'tcx>,
420         ty: Ty<'tcx>,
421     ) -> bool {
422         let tcx = self.tcx;
423
424         let assoc = tcx.associated_item(proj_ty.def_id);
425         if let ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) = *proj_ty.self_ty().kind() {
426             let opaque_local_def_id = def_id.as_local();
427             let opaque_hir_ty = if let Some(opaque_local_def_id) = opaque_local_def_id {
428                 match &tcx.hir().expect_item(opaque_local_def_id).kind {
429                     hir::ItemKind::OpaqueTy(opaque_hir_ty) => opaque_hir_ty,
430                     _ => bug!("The HirId comes from a `ty::Opaque`"),
431                 }
432             } else {
433                 return false;
434             };
435
436             let (trait_ref, assoc_substs) = proj_ty.trait_ref_and_own_substs(tcx);
437
438             self.constrain_generic_bound_associated_type_structured_suggestion(
439                 diag,
440                 &trait_ref,
441                 opaque_hir_ty.bounds,
442                 assoc,
443                 assoc_substs,
444                 ty,
445                 msg,
446                 true,
447             )
448         } else {
449             false
450         }
451     }
452
453     fn point_at_methods_that_satisfy_associated_type(
454         &self,
455         diag: &mut Diagnostic,
456         assoc_container_id: DefId,
457         current_method_ident: Option<Symbol>,
458         proj_ty_item_def_id: DefId,
459         expected: Ty<'tcx>,
460     ) -> bool {
461         let tcx = self.tcx;
462
463         let items = tcx.associated_items(assoc_container_id);
464         // Find all the methods in the trait that could be called to construct the
465         // expected associated type.
466         // FIXME: consider suggesting the use of associated `const`s.
467         let methods: Vec<(Span, String)> = items
468             .in_definition_order()
469             .filter(|item| {
470                 ty::AssocKind::Fn == item.kind && Some(item.name) != current_method_ident
471             })
472             .filter_map(|item| {
473                 let method = tcx.fn_sig(item.def_id).subst_identity();
474                 match *method.output().skip_binder().kind() {
475                     ty::Alias(ty::Projection, ty::AliasTy { def_id: item_def_id, .. })
476                         if item_def_id == proj_ty_item_def_id =>
477                     {
478                         Some((
479                             tcx.def_span(item.def_id),
480                             format!("consider calling `{}`", tcx.def_path_str(item.def_id)),
481                         ))
482                     }
483                     _ => None,
484                 }
485             })
486             .collect();
487         if !methods.is_empty() {
488             // Use a single `help:` to show all the methods in the trait that can
489             // be used to construct the expected associated type.
490             let mut span: MultiSpan =
491                 methods.iter().map(|(sp, _)| *sp).collect::<Vec<Span>>().into();
492             let msg = format!(
493                 "{some} method{s} {are} available that return{r} `{ty}`",
494                 some = if methods.len() == 1 { "a" } else { "some" },
495                 s = pluralize!(methods.len()),
496                 are = pluralize!("is", methods.len()),
497                 r = if methods.len() == 1 { "s" } else { "" },
498                 ty = expected
499             );
500             for (sp, label) in methods.into_iter() {
501                 span.push_span_label(sp, label);
502             }
503             diag.span_help(span, &msg);
504             return true;
505         }
506         false
507     }
508
509     fn point_at_associated_type(
510         &self,
511         diag: &mut Diagnostic,
512         body_owner_def_id: DefId,
513         found: Ty<'tcx>,
514     ) -> bool {
515         let tcx = self.tcx;
516
517         let Some(hir_id) = body_owner_def_id.as_local() else {
518             return false;
519         };
520         let hir_id = tcx.hir().local_def_id_to_hir_id(hir_id);
521         // When `body_owner` is an `impl` or `trait` item, look in its associated types for
522         // `expected` and point at it.
523         let parent_id = tcx.hir().get_parent_item(hir_id);
524         let item = tcx.hir().find_by_def_id(parent_id.def_id);
525
526         debug!("expected_projection parent item {:?}", item);
527
528         let param_env = tcx.param_env(body_owner_def_id);
529
530         match item {
531             Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Trait(.., items), .. })) => {
532                 // FIXME: account for `#![feature(specialization)]`
533                 for item in &items[..] {
534                     match item.kind {
535                         hir::AssocItemKind::Type => {
536                             // FIXME: account for returning some type in a trait fn impl that has
537                             // an assoc type as a return type (#72076).
538                             if let hir::Defaultness::Default { has_value: true } =
539                                 tcx.impl_defaultness(item.id.owner_id)
540                             {
541                                 let assoc_ty = tcx.bound_type_of(item.id.owner_id).subst_identity();
542                                 if self.infcx.can_eq(param_env, assoc_ty, found).is_ok() {
543                                     diag.span_label(
544                                         item.span,
545                                         "associated type defaults can't be assumed inside the \
546                                             trait defining them",
547                                     );
548                                     return true;
549                                 }
550                             }
551                         }
552                         _ => {}
553                     }
554                 }
555             }
556             Some(hir::Node::Item(hir::Item {
557                 kind: hir::ItemKind::Impl(hir::Impl { items, .. }),
558                 ..
559             })) => {
560                 for item in &items[..] {
561                     if let hir::AssocItemKind::Type = item.kind {
562                         let assoc_ty = tcx.bound_type_of(item.id.owner_id).subst_identity();
563
564                         if self.infcx.can_eq(param_env, assoc_ty, found).is_ok() {
565                             diag.span_label(item.span, "expected this associated type");
566                             return true;
567                         }
568                     }
569                 }
570             }
571             _ => {}
572         }
573         false
574     }
575
576     /// Given a slice of `hir::GenericBound`s, if any of them corresponds to the `trait_ref`
577     /// requirement, provide a structured suggestion to constrain it to a given type `ty`.
578     ///
579     /// `is_bound_surely_present` indicates whether we know the bound we're looking for is
580     /// inside `bounds`. If that's the case then we can consider `bounds` containing only one
581     /// trait bound as the one we're looking for. This can help in cases where the associated
582     /// type is defined on a supertrait of the one present in the bounds.
583     fn constrain_generic_bound_associated_type_structured_suggestion(
584         &self,
585         diag: &mut Diagnostic,
586         trait_ref: &ty::TraitRef<'tcx>,
587         bounds: hir::GenericBounds<'_>,
588         assoc: &ty::AssocItem,
589         assoc_substs: &[ty::GenericArg<'tcx>],
590         ty: Ty<'tcx>,
591         msg: &str,
592         is_bound_surely_present: bool,
593     ) -> bool {
594         // FIXME: we would want to call `resolve_vars_if_possible` on `ty` before suggesting.
595
596         let trait_bounds = bounds.iter().filter_map(|bound| match bound {
597             hir::GenericBound::Trait(ptr, hir::TraitBoundModifier::None) => Some(ptr),
598             _ => None,
599         });
600
601         let matching_trait_bounds = trait_bounds
602             .clone()
603             .filter(|ptr| ptr.trait_ref.trait_def_id() == Some(trait_ref.def_id))
604             .collect::<Vec<_>>();
605
606         let span = match &matching_trait_bounds[..] {
607             &[ptr] => ptr.span,
608             &[] if is_bound_surely_present => match &trait_bounds.collect::<Vec<_>>()[..] {
609                 &[ptr] => ptr.span,
610                 _ => return false,
611             },
612             _ => return false,
613         };
614
615         self.constrain_associated_type_structured_suggestion(
616             diag,
617             span,
618             assoc,
619             assoc_substs,
620             ty,
621             msg,
622         )
623     }
624
625     /// Given a span corresponding to a bound, provide a structured suggestion to set an
626     /// associated type to a given type `ty`.
627     fn constrain_associated_type_structured_suggestion(
628         &self,
629         diag: &mut Diagnostic,
630         span: Span,
631         assoc: &ty::AssocItem,
632         assoc_substs: &[ty::GenericArg<'tcx>],
633         ty: Ty<'tcx>,
634         msg: &str,
635     ) -> bool {
636         let tcx = self.tcx;
637
638         if let Ok(has_params) =
639             tcx.sess.source_map().span_to_snippet(span).map(|snippet| snippet.ends_with('>'))
640         {
641             let (span, sugg) = if has_params {
642                 let pos = span.hi() - BytePos(1);
643                 let span = Span::new(pos, pos, span.ctxt(), span.parent());
644                 (span, format!(", {} = {}", assoc.ident(tcx), ty))
645             } else {
646                 let item_args = self.format_generic_args(assoc_substs);
647                 (span.shrink_to_hi(), format!("<{}{} = {}>", assoc.ident(tcx), item_args, ty))
648             };
649             diag.span_suggestion_verbose(span, msg, sugg, MaybeIncorrect);
650             return true;
651         }
652         false
653     }
654
655     pub fn format_generic_args(&self, args: &[ty::GenericArg<'tcx>]) -> String {
656         FmtPrinter::new(self.tcx, hir::def::Namespace::TypeNS)
657             .path_generic_args(Ok, args)
658             .expect("could not write to `String`.")
659             .into_buffer()
660     }
661 }