]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_infer/src/infer/error_reporting/note_and_explain.rs
Rollup merge of #107321 - lcnr:comment, r=compiler-errors
[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(&tcx) -> 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(&tcx) -> 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(&tcx) -> 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(&tcx, 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                     _ => {}
222                 }
223                 debug!(
224                     "note_and_explain_type_err expected={:?} ({:?}) found={:?} ({:?})",
225                     values.expected,
226                     values.expected.kind(),
227                     values.found,
228                     values.found.kind(),
229                 );
230             }
231             CyclicTy(ty) => {
232                 // Watch out for various cases of cyclic types and try to explain.
233                 if ty.is_closure() || ty.is_generator() {
234                     diag.note(
235                         "closures cannot capture themselves or take themselves as argument;\n\
236                          this error may be the result of a recent compiler bug-fix,\n\
237                          see issue #46062 <https://github.com/rust-lang/rust/issues/46062>\n\
238                          for more information",
239                     );
240                 }
241             }
242             TargetFeatureCast(def_id) => {
243                 let target_spans = tcx.get_attrs(def_id, sym::target_feature).map(|attr| attr.span);
244                 diag.note(
245                     "functions with `#[target_feature]` can only be coerced to `unsafe` function pointers"
246                 );
247                 diag.span_labels(target_spans, "`#[target_feature]` added here");
248             }
249             _ => {}
250         }
251     }
252
253     fn suggest_constraint(
254         &self,
255         diag: &mut Diagnostic,
256         msg: &str,
257         body_owner_def_id: DefId,
258         proj_ty: &ty::AliasTy<'tcx>,
259         ty: Ty<'tcx>,
260     ) -> bool {
261         let tcx = self.tcx;
262         let assoc = tcx.associated_item(proj_ty.def_id);
263         let (trait_ref, assoc_substs) = proj_ty.trait_ref_and_own_substs(tcx);
264         if let Some(item) = tcx.hir().get_if_local(body_owner_def_id) {
265             if let Some(hir_generics) = item.generics() {
266                 // Get the `DefId` for the type parameter corresponding to `A` in `<A as T>::Foo`.
267                 // This will also work for `impl Trait`.
268                 let def_id = if let ty::Param(param_ty) = proj_ty.self_ty().kind() {
269                     let generics = tcx.generics_of(body_owner_def_id);
270                     generics.type_param(param_ty, tcx).def_id
271                 } else {
272                     return false;
273                 };
274                 let Some(def_id) = def_id.as_local() else {
275                     return false;
276                 };
277
278                 // First look in the `where` clause, as this might be
279                 // `fn foo<T>(x: T) where T: Trait`.
280                 for pred in hir_generics.bounds_for_param(def_id) {
281                     if self.constrain_generic_bound_associated_type_structured_suggestion(
282                         diag,
283                         &trait_ref,
284                         pred.bounds,
285                         &assoc,
286                         assoc_substs,
287                         ty,
288                         msg,
289                         false,
290                     ) {
291                         return true;
292                     }
293                 }
294             }
295         }
296         false
297     }
298
299     /// An associated type was expected and a different type was found.
300     ///
301     /// We perform a few different checks to see what we can suggest:
302     ///
303     ///  - In the current item, look for associated functions that return the expected type and
304     ///    suggest calling them. (Not a structured suggestion.)
305     ///  - If any of the item's generic bounds can be constrained, we suggest constraining the
306     ///    associated type to the found type.
307     ///  - If the associated type has a default type and was expected inside of a `trait`, we
308     ///    mention that this is disallowed.
309     ///  - If all other things fail, and the error is not because of a mismatch between the `trait`
310     ///    and the `impl`, we provide a generic `help` to constrain the assoc type or call an assoc
311     ///    fn that returns the type.
312     fn expected_projection(
313         &self,
314         diag: &mut Diagnostic,
315         proj_ty: &ty::AliasTy<'tcx>,
316         values: ExpectedFound<Ty<'tcx>>,
317         body_owner_def_id: DefId,
318         cause_code: &ObligationCauseCode<'_>,
319     ) {
320         let tcx = self.tcx;
321
322         let msg = format!(
323             "consider constraining the associated type `{}` to `{}`",
324             values.expected, values.found
325         );
326         let body_owner = tcx.hir().get_if_local(body_owner_def_id);
327         let current_method_ident = body_owner.and_then(|n| n.ident()).map(|i| i.name);
328
329         // We don't want to suggest calling an assoc fn in a scope where that isn't feasible.
330         let callable_scope = matches!(
331             body_owner,
332             Some(
333                 hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(..), .. })
334                     | hir::Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(..), .. })
335                     | hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }),
336             )
337         );
338         let impl_comparison =
339             matches!(cause_code, ObligationCauseCode::CompareImplItemObligation { .. });
340         let assoc = tcx.associated_item(proj_ty.def_id);
341         if !callable_scope || impl_comparison {
342             // We do not want to suggest calling functions when the reason of the
343             // type error is a comparison of an `impl` with its `trait` or when the
344             // scope is outside of a `Body`.
345         } else {
346             // If we find a suitable associated function that returns the expected type, we don't
347             // want the more general suggestion later in this method about "consider constraining
348             // the associated type or calling a method that returns the associated type".
349             let point_at_assoc_fn = self.point_at_methods_that_satisfy_associated_type(
350                 diag,
351                 assoc.container_id(tcx),
352                 current_method_ident,
353                 proj_ty.def_id,
354                 values.expected,
355             );
356             // Possibly suggest constraining the associated type to conform to the
357             // found type.
358             if self.suggest_constraint(diag, &msg, body_owner_def_id, proj_ty, values.found)
359                 || point_at_assoc_fn
360             {
361                 return;
362             }
363         }
364
365         self.suggest_constraining_opaque_associated_type(diag, &msg, proj_ty, values.found);
366
367         if self.point_at_associated_type(diag, body_owner_def_id, values.found) {
368             return;
369         }
370
371         if !impl_comparison {
372             // Generic suggestion when we can't be more specific.
373             if callable_scope {
374                 diag.help(&format!(
375                     "{} or calling a method that returns `{}`",
376                     msg, values.expected
377                 ));
378             } else {
379                 diag.help(&msg);
380             }
381             diag.note(
382                 "for more information, visit \
383                  https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
384             );
385         }
386         if tcx.sess.teach(&diag.get_code().unwrap()) {
387             diag.help(
388                 "given an associated type `T` and a method `foo`:
389 ```
390 trait Trait {
391 type T;
392 fn foo(&tcx) -> Self::T;
393 }
394 ```
395 the only way of implementing method `foo` is to constrain `T` with an explicit associated type:
396 ```
397 impl Trait for X {
398 type T = String;
399 fn foo(&tcx) -> Self::T { String::new() }
400 }
401 ```",
402             );
403         }
404     }
405
406     /// When the expected `impl Trait` is not defined in the current item, it will come from
407     /// a return type. This can occur when dealing with `TryStream` (#71035).
408     fn suggest_constraining_opaque_associated_type(
409         &self,
410         diag: &mut Diagnostic,
411         msg: &str,
412         proj_ty: &ty::AliasTy<'tcx>,
413         ty: Ty<'tcx>,
414     ) -> bool {
415         let tcx = self.tcx;
416
417         let assoc = tcx.associated_item(proj_ty.def_id);
418         if let ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) = *proj_ty.self_ty().kind() {
419             let opaque_local_def_id = def_id.as_local();
420             let opaque_hir_ty = if let Some(opaque_local_def_id) = opaque_local_def_id {
421                 match &tcx.hir().expect_item(opaque_local_def_id).kind {
422                     hir::ItemKind::OpaqueTy(opaque_hir_ty) => opaque_hir_ty,
423                     _ => bug!("The HirId comes from a `ty::Opaque`"),
424                 }
425             } else {
426                 return false;
427             };
428
429             let (trait_ref, assoc_substs) = proj_ty.trait_ref_and_own_substs(tcx);
430
431             self.constrain_generic_bound_associated_type_structured_suggestion(
432                 diag,
433                 &trait_ref,
434                 opaque_hir_ty.bounds,
435                 assoc,
436                 assoc_substs,
437                 ty,
438                 msg,
439                 true,
440             )
441         } else {
442             false
443         }
444     }
445
446     fn point_at_methods_that_satisfy_associated_type(
447         &self,
448         diag: &mut Diagnostic,
449         assoc_container_id: DefId,
450         current_method_ident: Option<Symbol>,
451         proj_ty_item_def_id: DefId,
452         expected: Ty<'tcx>,
453     ) -> bool {
454         let tcx = self.tcx;
455
456         let items = tcx.associated_items(assoc_container_id);
457         // Find all the methods in the trait that could be called to construct the
458         // expected associated type.
459         // FIXME: consider suggesting the use of associated `const`s.
460         let methods: Vec<(Span, String)> = items
461             .in_definition_order()
462             .filter(|item| {
463                 ty::AssocKind::Fn == item.kind && Some(item.name) != current_method_ident
464             })
465             .filter_map(|item| {
466                 let method = tcx.fn_sig(item.def_id);
467                 match *method.output().skip_binder().kind() {
468                     ty::Alias(ty::Projection, ty::AliasTy { def_id: item_def_id, .. })
469                         if item_def_id == proj_ty_item_def_id =>
470                     {
471                         Some((
472                             tcx.def_span(item.def_id),
473                             format!("consider calling `{}`", tcx.def_path_str(item.def_id)),
474                         ))
475                     }
476                     _ => None,
477                 }
478             })
479             .collect();
480         if !methods.is_empty() {
481             // Use a single `help:` to show all the methods in the trait that can
482             // be used to construct the expected associated type.
483             let mut span: MultiSpan =
484                 methods.iter().map(|(sp, _)| *sp).collect::<Vec<Span>>().into();
485             let msg = format!(
486                 "{some} method{s} {are} available that return{r} `{ty}`",
487                 some = if methods.len() == 1 { "a" } else { "some" },
488                 s = pluralize!(methods.len()),
489                 are = pluralize!("is", methods.len()),
490                 r = if methods.len() == 1 { "s" } else { "" },
491                 ty = expected
492             );
493             for (sp, label) in methods.into_iter() {
494                 span.push_span_label(sp, label);
495             }
496             diag.span_help(span, &msg);
497             return true;
498         }
499         false
500     }
501
502     fn point_at_associated_type(
503         &self,
504         diag: &mut Diagnostic,
505         body_owner_def_id: DefId,
506         found: Ty<'tcx>,
507     ) -> bool {
508         let tcx = self.tcx;
509
510         let Some(hir_id) = body_owner_def_id.as_local() else {
511             return false;
512         };
513         let hir_id = tcx.hir().local_def_id_to_hir_id(hir_id);
514         // When `body_owner` is an `impl` or `trait` item, look in its associated types for
515         // `expected` and point at it.
516         let parent_id = tcx.hir().get_parent_item(hir_id);
517         let item = tcx.hir().find_by_def_id(parent_id.def_id);
518
519         debug!("expected_projection parent item {:?}", item);
520
521         let param_env = tcx.param_env(body_owner_def_id);
522
523         match item {
524             Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Trait(.., items), .. })) => {
525                 // FIXME: account for `#![feature(specialization)]`
526                 for item in &items[..] {
527                     match item.kind {
528                         hir::AssocItemKind::Type => {
529                             // FIXME: account for returning some type in a trait fn impl that has
530                             // an assoc type as a return type (#72076).
531                             if let hir::Defaultness::Default { has_value: true } =
532                                 tcx.impl_defaultness(item.id.owner_id)
533                             {
534                                 let assoc_ty = tcx.bound_type_of(item.id.owner_id).subst_identity();
535                                 if self.infcx.can_eq(param_env, assoc_ty, found).is_ok() {
536                                     diag.span_label(
537                                         item.span,
538                                         "associated type defaults can't be assumed inside the \
539                                             trait defining them",
540                                     );
541                                     return true;
542                                 }
543                             }
544                         }
545                         _ => {}
546                     }
547                 }
548             }
549             Some(hir::Node::Item(hir::Item {
550                 kind: hir::ItemKind::Impl(hir::Impl { items, .. }),
551                 ..
552             })) => {
553                 for item in &items[..] {
554                     if let hir::AssocItemKind::Type = item.kind {
555                         let assoc_ty = tcx.bound_type_of(item.id.owner_id).subst_identity();
556
557                         if self.infcx.can_eq(param_env, assoc_ty, found).is_ok() {
558                             diag.span_label(item.span, "expected this associated type");
559                             return true;
560                         }
561                     }
562                 }
563             }
564             _ => {}
565         }
566         false
567     }
568
569     /// Given a slice of `hir::GenericBound`s, if any of them corresponds to the `trait_ref`
570     /// requirement, provide a structured suggestion to constrain it to a given type `ty`.
571     ///
572     /// `is_bound_surely_present` indicates whether we know the bound we're looking for is
573     /// inside `bounds`. If that's the case then we can consider `bounds` containing only one
574     /// trait bound as the one we're looking for. This can help in cases where the associated
575     /// type is defined on a supertrait of the one present in the bounds.
576     fn constrain_generic_bound_associated_type_structured_suggestion(
577         &self,
578         diag: &mut Diagnostic,
579         trait_ref: &ty::TraitRef<'tcx>,
580         bounds: hir::GenericBounds<'_>,
581         assoc: &ty::AssocItem,
582         assoc_substs: &[ty::GenericArg<'tcx>],
583         ty: Ty<'tcx>,
584         msg: &str,
585         is_bound_surely_present: bool,
586     ) -> bool {
587         // FIXME: we would want to call `resolve_vars_if_possible` on `ty` before suggesting.
588
589         let trait_bounds = bounds.iter().filter_map(|bound| match bound {
590             hir::GenericBound::Trait(ptr, hir::TraitBoundModifier::None) => Some(ptr),
591             _ => None,
592         });
593
594         let matching_trait_bounds = trait_bounds
595             .clone()
596             .filter(|ptr| ptr.trait_ref.trait_def_id() == Some(trait_ref.def_id))
597             .collect::<Vec<_>>();
598
599         let span = match &matching_trait_bounds[..] {
600             &[ptr] => ptr.span,
601             &[] if is_bound_surely_present => match &trait_bounds.collect::<Vec<_>>()[..] {
602                 &[ptr] => ptr.span,
603                 _ => return false,
604             },
605             _ => return false,
606         };
607
608         self.constrain_associated_type_structured_suggestion(
609             diag,
610             span,
611             assoc,
612             assoc_substs,
613             ty,
614             msg,
615         )
616     }
617
618     /// Given a span corresponding to a bound, provide a structured suggestion to set an
619     /// associated type to a given type `ty`.
620     fn constrain_associated_type_structured_suggestion(
621         &self,
622         diag: &mut Diagnostic,
623         span: Span,
624         assoc: &ty::AssocItem,
625         assoc_substs: &[ty::GenericArg<'tcx>],
626         ty: Ty<'tcx>,
627         msg: &str,
628     ) -> bool {
629         let tcx = self.tcx;
630
631         if let Ok(has_params) =
632             tcx.sess.source_map().span_to_snippet(span).map(|snippet| snippet.ends_with('>'))
633         {
634             let (span, sugg) = if has_params {
635                 let pos = span.hi() - BytePos(1);
636                 let span = Span::new(pos, pos, span.ctxt(), span.parent());
637                 (span, format!(", {} = {}", assoc.ident(tcx), ty))
638             } else {
639                 let item_args = self.format_generic_args(assoc_substs);
640                 (span.shrink_to_hi(), format!("<{}{} = {}>", assoc.ident(tcx), item_args, ty))
641             };
642             diag.span_suggestion_verbose(span, msg, sugg, MaybeIncorrect);
643             return true;
644         }
645         false
646     }
647
648     pub fn format_generic_args(&self, args: &[ty::GenericArg<'tcx>]) -> String {
649         FmtPrinter::new(self.tcx, hir::def::Namespace::TypeNS)
650             .path_generic_args(Ok, args)
651             .expect("could not write to `String`.")
652             .into_buffer()
653     }
654 }