]> git.lizzy.rs Git - rust.git/blob - crates/hir-ty/src/display.rs
feat: Handle operators like their trait functions in the IDE
[rust.git] / crates / hir-ty / src / display.rs
1 //! The `HirDisplay` trait, which serves two purposes: Turning various bits from
2 //! HIR back into source code, and just displaying them for debugging/testing
3 //! purposes.
4
5 use std::fmt::{self, Debug};
6
7 use base_db::CrateId;
8 use chalk_ir::BoundVar;
9 use hir_def::{
10     body,
11     db::DefDatabase,
12     find_path,
13     generics::{TypeOrConstParamData, TypeParamProvenance},
14     intern::{Internable, Interned},
15     item_scope::ItemInNs,
16     path::{Path, PathKind},
17     type_ref::{ConstScalar, TraitBoundModifier, TypeBound, TypeRef},
18     visibility::Visibility,
19     HasModule, ItemContainerId, Lookup, ModuleId, TraitId,
20 };
21 use hir_expand::{hygiene::Hygiene, name::Name};
22 use itertools::Itertools;
23 use syntax::SmolStr;
24
25 use crate::{
26     db::HirDatabase,
27     from_assoc_type_id, from_foreign_def_id, from_placeholder_idx, lt_from_placeholder_idx,
28     mapping::from_chalk,
29     primitive, subst_prefix, to_assoc_type_id,
30     utils::{self, generics},
31     AdtId, AliasEq, AliasTy, Binders, CallableDefId, CallableSig, Const, ConstValue, DomainGoal,
32     GenericArg, ImplTraitId, Interner, Lifetime, LifetimeData, LifetimeOutlives, Mutability,
33     OpaqueTy, ProjectionTy, ProjectionTyExt, QuantifiedWhereClause, Scalar, Substitution, TraitRef,
34     TraitRefExt, Ty, TyExt, TyKind, WhereClause,
35 };
36
37 pub struct HirFormatter<'a> {
38     pub db: &'a dyn HirDatabase,
39     fmt: &'a mut dyn fmt::Write,
40     buf: String,
41     curr_size: usize,
42     pub(crate) max_size: Option<usize>,
43     omit_verbose_types: bool,
44     display_target: DisplayTarget,
45 }
46
47 pub trait HirDisplay {
48     fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError>;
49
50     /// Returns a `Display`able type that is human-readable.
51     fn into_displayable<'a>(
52         &'a self,
53         db: &'a dyn HirDatabase,
54         max_size: Option<usize>,
55         omit_verbose_types: bool,
56         display_target: DisplayTarget,
57     ) -> HirDisplayWrapper<'a, Self>
58     where
59         Self: Sized,
60     {
61         assert!(
62             !matches!(display_target, DisplayTarget::SourceCode { .. }),
63             "HirDisplayWrapper cannot fail with DisplaySourceCodeError, use HirDisplay::hir_fmt directly instead"
64         );
65         HirDisplayWrapper { db, t: self, max_size, omit_verbose_types, display_target }
66     }
67
68     /// Returns a `Display`able type that is human-readable.
69     /// Use this for showing types to the user (e.g. diagnostics)
70     fn display<'a>(&'a self, db: &'a dyn HirDatabase) -> HirDisplayWrapper<'a, Self>
71     where
72         Self: Sized,
73     {
74         HirDisplayWrapper {
75             db,
76             t: self,
77             max_size: None,
78             omit_verbose_types: false,
79             display_target: DisplayTarget::Diagnostics,
80         }
81     }
82
83     /// Returns a `Display`able type that is human-readable and tries to be succinct.
84     /// Use this for showing types to the user where space is constrained (e.g. doc popups)
85     fn display_truncated<'a>(
86         &'a self,
87         db: &'a dyn HirDatabase,
88         max_size: Option<usize>,
89     ) -> HirDisplayWrapper<'a, Self>
90     where
91         Self: Sized,
92     {
93         HirDisplayWrapper {
94             db,
95             t: self,
96             max_size,
97             omit_verbose_types: true,
98             display_target: DisplayTarget::Diagnostics,
99         }
100     }
101
102     /// Returns a String representation of `self` that can be inserted into the given module.
103     /// Use this when generating code (e.g. assists)
104     fn display_source_code<'a>(
105         &'a self,
106         db: &'a dyn HirDatabase,
107         module_id: ModuleId,
108     ) -> Result<String, DisplaySourceCodeError> {
109         let mut result = String::new();
110         match self.hir_fmt(&mut HirFormatter {
111             db,
112             fmt: &mut result,
113             buf: String::with_capacity(20),
114             curr_size: 0,
115             max_size: None,
116             omit_verbose_types: false,
117             display_target: DisplayTarget::SourceCode { module_id },
118         }) {
119             Ok(()) => {}
120             Err(HirDisplayError::FmtError) => panic!("Writing to String can't fail!"),
121             Err(HirDisplayError::DisplaySourceCodeError(e)) => return Err(e),
122         };
123         Ok(result)
124     }
125
126     /// Returns a String representation of `self` for test purposes
127     fn display_test<'a>(&'a self, db: &'a dyn HirDatabase) -> HirDisplayWrapper<'a, Self>
128     where
129         Self: Sized,
130     {
131         HirDisplayWrapper {
132             db,
133             t: self,
134             max_size: None,
135             omit_verbose_types: false,
136             display_target: DisplayTarget::Test,
137         }
138     }
139 }
140
141 impl<'a> HirFormatter<'a> {
142     pub fn write_joined<T: HirDisplay>(
143         &mut self,
144         iter: impl IntoIterator<Item = T>,
145         sep: &str,
146     ) -> Result<(), HirDisplayError> {
147         let mut first = true;
148         for e in iter {
149             if !first {
150                 write!(self, "{}", sep)?;
151             }
152             first = false;
153
154             // Abbreviate multiple omitted types with a single ellipsis.
155             if self.should_truncate() {
156                 return write!(self, "{}", TYPE_HINT_TRUNCATION);
157             }
158
159             e.hir_fmt(self)?;
160         }
161         Ok(())
162     }
163
164     /// This allows using the `write!` macro directly with a `HirFormatter`.
165     pub fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> Result<(), HirDisplayError> {
166         // We write to a buffer first to track output size
167         self.buf.clear();
168         fmt::write(&mut self.buf, args)?;
169         self.curr_size += self.buf.len();
170
171         // Then we write to the internal formatter from the buffer
172         self.fmt.write_str(&self.buf).map_err(HirDisplayError::from)
173     }
174
175     pub fn write_str(&mut self, s: &str) -> Result<(), HirDisplayError> {
176         self.fmt.write_str(s)?;
177         Ok(())
178     }
179
180     pub fn write_char(&mut self, c: char) -> Result<(), HirDisplayError> {
181         self.fmt.write_char(c)?;
182         Ok(())
183     }
184
185     pub fn should_truncate(&self) -> bool {
186         match self.max_size {
187             Some(max_size) => self.curr_size >= max_size,
188             None => false,
189         }
190     }
191
192     pub fn omit_verbose_types(&self) -> bool {
193         self.omit_verbose_types
194     }
195 }
196
197 #[derive(Clone, Copy)]
198 pub enum DisplayTarget {
199     /// Display types for inlays, doc popups, autocompletion, etc...
200     /// Showing `{unknown}` or not qualifying paths is fine here.
201     /// There's no reason for this to fail.
202     Diagnostics,
203     /// Display types for inserting them in source files.
204     /// The generated code should compile, so paths need to be qualified.
205     SourceCode { module_id: ModuleId },
206     /// Only for test purpose to keep real types
207     Test,
208 }
209
210 impl DisplayTarget {
211     fn is_source_code(&self) -> bool {
212         matches!(self, Self::SourceCode { .. })
213     }
214     fn is_test(&self) -> bool {
215         matches!(self, Self::Test)
216     }
217 }
218
219 #[derive(Debug)]
220 pub enum DisplaySourceCodeError {
221     PathNotFound,
222     UnknownType,
223     Closure,
224 }
225
226 pub enum HirDisplayError {
227     /// Errors that can occur when generating source code
228     DisplaySourceCodeError(DisplaySourceCodeError),
229     /// `FmtError` is required to be compatible with std::fmt::Display
230     FmtError,
231 }
232 impl From<fmt::Error> for HirDisplayError {
233     fn from(_: fmt::Error) -> Self {
234         Self::FmtError
235     }
236 }
237
238 pub struct HirDisplayWrapper<'a, T> {
239     db: &'a dyn HirDatabase,
240     t: &'a T,
241     max_size: Option<usize>,
242     omit_verbose_types: bool,
243     display_target: DisplayTarget,
244 }
245
246 impl<'a, T> fmt::Display for HirDisplayWrapper<'a, T>
247 where
248     T: HirDisplay,
249 {
250     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
251         match self.t.hir_fmt(&mut HirFormatter {
252             db: self.db,
253             fmt: f,
254             buf: String::with_capacity(20),
255             curr_size: 0,
256             max_size: self.max_size,
257             omit_verbose_types: self.omit_verbose_types,
258             display_target: self.display_target,
259         }) {
260             Ok(()) => Ok(()),
261             Err(HirDisplayError::FmtError) => Err(fmt::Error),
262             Err(HirDisplayError::DisplaySourceCodeError(_)) => {
263                 // This should never happen
264                 panic!("HirDisplay::hir_fmt failed with DisplaySourceCodeError when calling Display::fmt!")
265             }
266         }
267     }
268 }
269
270 const TYPE_HINT_TRUNCATION: &str = "…";
271
272 impl<T: HirDisplay> HirDisplay for &'_ T {
273     fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
274         HirDisplay::hir_fmt(*self, f)
275     }
276 }
277
278 impl<T: HirDisplay + Internable> HirDisplay for Interned<T> {
279     fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
280         HirDisplay::hir_fmt(self.as_ref(), f)
281     }
282 }
283
284 impl HirDisplay for ProjectionTy {
285     fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
286         if f.should_truncate() {
287             return write!(f, "{}", TYPE_HINT_TRUNCATION);
288         }
289
290         let trait_ = f.db.trait_data(self.trait_(f.db));
291         write!(f, "<")?;
292         self.self_type_parameter(Interner).hir_fmt(f)?;
293         write!(f, " as {}", trait_.name)?;
294         if self.substitution.len(Interner) > 1 {
295             write!(f, "<")?;
296             f.write_joined(&self.substitution.as_slice(Interner)[1..], ", ")?;
297             write!(f, ">")?;
298         }
299         write!(f, ">::{}", f.db.type_alias_data(from_assoc_type_id(self.associated_ty_id)).name)?;
300         Ok(())
301     }
302 }
303
304 impl HirDisplay for OpaqueTy {
305     fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
306         if f.should_truncate() {
307             return write!(f, "{}", TYPE_HINT_TRUNCATION);
308         }
309
310         self.substitution.at(Interner, 0).hir_fmt(f)
311     }
312 }
313
314 impl HirDisplay for GenericArg {
315     fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
316         match self.interned() {
317             crate::GenericArgData::Ty(ty) => ty.hir_fmt(f),
318             crate::GenericArgData::Lifetime(lt) => lt.hir_fmt(f),
319             crate::GenericArgData::Const(c) => c.hir_fmt(f),
320         }
321     }
322 }
323
324 impl HirDisplay for Const {
325     fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
326         let data = self.interned();
327         match data.value {
328             ConstValue::BoundVar(idx) => idx.hir_fmt(f),
329             ConstValue::InferenceVar(..) => write!(f, "#c#"),
330             ConstValue::Placeholder(idx) => {
331                 let id = from_placeholder_idx(f.db, idx);
332                 let generics = generics(f.db.upcast(), id.parent);
333                 let param_data = &generics.params.type_or_consts[id.local_id];
334                 write!(f, "{}", param_data.name().unwrap())
335             }
336             ConstValue::Concrete(c) => write!(f, "{}", c.interned),
337         }
338     }
339 }
340
341 impl HirDisplay for BoundVar {
342     fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
343         write!(f, "?{}.{}", self.debruijn.depth(), self.index)
344     }
345 }
346
347 impl HirDisplay for Ty {
348     fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
349         if f.should_truncate() {
350             return write!(f, "{}", TYPE_HINT_TRUNCATION);
351         }
352
353         match self.kind(Interner) {
354             TyKind::Never => write!(f, "!")?,
355             TyKind::Str => write!(f, "str")?,
356             TyKind::Scalar(Scalar::Bool) => write!(f, "bool")?,
357             TyKind::Scalar(Scalar::Char) => write!(f, "char")?,
358             &TyKind::Scalar(Scalar::Float(t)) => write!(f, "{}", primitive::float_ty_to_string(t))?,
359             &TyKind::Scalar(Scalar::Int(t)) => write!(f, "{}", primitive::int_ty_to_string(t))?,
360             &TyKind::Scalar(Scalar::Uint(t)) => write!(f, "{}", primitive::uint_ty_to_string(t))?,
361             TyKind::Slice(t) => {
362                 write!(f, "[")?;
363                 t.hir_fmt(f)?;
364                 write!(f, "]")?;
365             }
366             TyKind::Array(t, c) => {
367                 write!(f, "[")?;
368                 t.hir_fmt(f)?;
369                 write!(f, "; ")?;
370                 c.hir_fmt(f)?;
371                 write!(f, "]")?;
372             }
373             TyKind::Raw(m, t) | TyKind::Ref(m, _, t) => {
374                 if matches!(self.kind(Interner), TyKind::Raw(..)) {
375                     write!(
376                         f,
377                         "*{}",
378                         match m {
379                             Mutability::Not => "const ",
380                             Mutability::Mut => "mut ",
381                         }
382                     )?;
383                 } else {
384                     write!(
385                         f,
386                         "&{}",
387                         match m {
388                             Mutability::Not => "",
389                             Mutability::Mut => "mut ",
390                         }
391                     )?;
392                 }
393
394                 // FIXME: all this just to decide whether to use parentheses...
395                 let contains_impl_fn = |bounds: &[QuantifiedWhereClause]| {
396                     bounds.iter().any(|bound| {
397                         if let WhereClause::Implemented(trait_ref) = bound.skip_binders() {
398                             let trait_ = trait_ref.hir_trait_id();
399                             fn_traits(f.db.upcast(), trait_).any(|it| it == trait_)
400                         } else {
401                             false
402                         }
403                     })
404                 };
405                 let (preds_to_print, has_impl_fn_pred) = match t.kind(Interner) {
406                     TyKind::Dyn(dyn_ty) if dyn_ty.bounds.skip_binders().interned().len() > 1 => {
407                         let bounds = dyn_ty.bounds.skip_binders().interned();
408                         (bounds.len(), contains_impl_fn(bounds))
409                     }
410                     TyKind::Alias(AliasTy::Opaque(OpaqueTy {
411                         opaque_ty_id,
412                         substitution: parameters,
413                     }))
414                     | TyKind::OpaqueType(opaque_ty_id, parameters) => {
415                         let impl_trait_id =
416                             f.db.lookup_intern_impl_trait_id((*opaque_ty_id).into());
417                         if let ImplTraitId::ReturnTypeImplTrait(func, idx) = impl_trait_id {
418                             let datas =
419                                 f.db.return_type_impl_traits(func)
420                                     .expect("impl trait id without data");
421                             let data = (*datas)
422                                 .as_ref()
423                                 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
424                             let bounds = data.substitute(Interner, parameters);
425                             let mut len = bounds.skip_binders().len();
426
427                             // Don't count Sized but count when it absent
428                             // (i.e. when explicit ?Sized bound is set).
429                             let default_sized = SizedByDefault::Sized {
430                                 anchor: func.lookup(f.db.upcast()).module(f.db.upcast()).krate(),
431                             };
432                             let sized_bounds = bounds
433                                 .skip_binders()
434                                 .iter()
435                                 .filter(|b| {
436                                     matches!(
437                                         b.skip_binders(),
438                                         WhereClause::Implemented(trait_ref)
439                                             if default_sized.is_sized_trait(
440                                                 trait_ref.hir_trait_id(),
441                                                 f.db.upcast(),
442                                             ),
443                                     )
444                                 })
445                                 .count();
446                             match sized_bounds {
447                                 0 => len += 1,
448                                 _ => {
449                                     len = len.saturating_sub(sized_bounds);
450                                 }
451                             }
452
453                             (len, contains_impl_fn(bounds.skip_binders()))
454                         } else {
455                             (0, false)
456                         }
457                     }
458                     _ => (0, false),
459                 };
460
461                 if has_impl_fn_pred && preds_to_print <= 2 {
462                     return t.hir_fmt(f);
463                 }
464
465                 if preds_to_print > 1 {
466                     write!(f, "(")?;
467                     t.hir_fmt(f)?;
468                     write!(f, ")")?;
469                 } else {
470                     t.hir_fmt(f)?;
471                 }
472             }
473             TyKind::Tuple(_, substs) => {
474                 if substs.len(Interner) == 1 {
475                     write!(f, "(")?;
476                     substs.at(Interner, 0).hir_fmt(f)?;
477                     write!(f, ",)")?;
478                 } else {
479                     write!(f, "(")?;
480                     f.write_joined(&*substs.as_slice(Interner), ", ")?;
481                     write!(f, ")")?;
482                 }
483             }
484             TyKind::Function(fn_ptr) => {
485                 let sig = CallableSig::from_fn_ptr(fn_ptr);
486                 sig.hir_fmt(f)?;
487             }
488             TyKind::FnDef(def, parameters) => {
489                 let def = from_chalk(f.db, *def);
490                 let sig = f.db.callable_item_signature(def).substitute(Interner, parameters);
491                 match def {
492                     CallableDefId::FunctionId(ff) => {
493                         write!(f, "fn {}", f.db.function_data(ff).name)?
494                     }
495                     CallableDefId::StructId(s) => write!(f, "{}", f.db.struct_data(s).name)?,
496                     CallableDefId::EnumVariantId(e) => {
497                         write!(f, "{}", f.db.enum_data(e.parent).variants[e.local_id].name)?
498                     }
499                 };
500                 if parameters.len(Interner) > 0 {
501                     let generics = generics(f.db.upcast(), def.into());
502                     let (parent_params, self_param, type_params, const_params, _impl_trait_params) =
503                         generics.provenance_split();
504                     let total_len = parent_params + self_param + type_params + const_params;
505                     // We print all params except implicit impl Trait params. Still a bit weird; should we leave out parent and self?
506                     if total_len > 0 {
507                         write!(f, "<")?;
508                         f.write_joined(&parameters.as_slice(Interner)[..total_len], ", ")?;
509                         write!(f, ">")?;
510                     }
511                 }
512                 write!(f, "(")?;
513                 f.write_joined(sig.params(), ", ")?;
514                 write!(f, ")")?;
515                 let ret = sig.ret();
516                 if !ret.is_unit() {
517                     write!(f, " -> ")?;
518                     ret.hir_fmt(f)?;
519                 }
520             }
521             TyKind::Adt(AdtId(def_id), parameters) => {
522                 match f.display_target {
523                     DisplayTarget::Diagnostics | DisplayTarget::Test => {
524                         let name = match *def_id {
525                             hir_def::AdtId::StructId(it) => f.db.struct_data(it).name.clone(),
526                             hir_def::AdtId::UnionId(it) => f.db.union_data(it).name.clone(),
527                             hir_def::AdtId::EnumId(it) => f.db.enum_data(it).name.clone(),
528                         };
529                         write!(f, "{}", name)?;
530                     }
531                     DisplayTarget::SourceCode { module_id } => {
532                         if let Some(path) = find_path::find_path(
533                             f.db.upcast(),
534                             ItemInNs::Types((*def_id).into()),
535                             module_id,
536                         ) {
537                             write!(f, "{}", path)?;
538                         } else {
539                             return Err(HirDisplayError::DisplaySourceCodeError(
540                                 DisplaySourceCodeError::PathNotFound,
541                             ));
542                         }
543                     }
544                 }
545
546                 if parameters.len(Interner) > 0 {
547                     let parameters_to_write = if f.display_target.is_source_code()
548                         || f.omit_verbose_types()
549                     {
550                         match self
551                             .as_generic_def(f.db)
552                             .map(|generic_def_id| f.db.generic_defaults(generic_def_id))
553                             .filter(|defaults| !defaults.is_empty())
554                         {
555                             None => parameters.as_slice(Interner),
556                             Some(default_parameters) => {
557                                 fn should_show(
558                                     parameter: &GenericArg,
559                                     default_parameters: &[Binders<GenericArg>],
560                                     i: usize,
561                                     parameters: &Substitution,
562                                 ) -> bool {
563                                     if parameter.ty(Interner).map(|x| x.kind(Interner))
564                                         == Some(&TyKind::Error)
565                                     {
566                                         return true;
567                                     }
568                                     if let Some(ConstValue::Concrete(c)) =
569                                         parameter.constant(Interner).map(|x| x.data(Interner).value)
570                                     {
571                                         if c.interned == ConstScalar::Unknown {
572                                             return true;
573                                         }
574                                     }
575                                     let default_parameter = match default_parameters.get(i) {
576                                         Some(x) => x,
577                                         None => return true,
578                                     };
579                                     let actual_default = default_parameter
580                                         .clone()
581                                         .substitute(Interner, &subst_prefix(parameters, i));
582                                     parameter != &actual_default
583                                 }
584                                 let mut default_from = 0;
585                                 for (i, parameter) in parameters.iter(Interner).enumerate() {
586                                     if should_show(parameter, &default_parameters, i, parameters) {
587                                         default_from = i + 1;
588                                     }
589                                 }
590                                 &parameters.as_slice(Interner)[0..default_from]
591                             }
592                         }
593                     } else {
594                         parameters.as_slice(Interner)
595                     };
596                     if !parameters_to_write.is_empty() {
597                         write!(f, "<")?;
598
599                         if f.display_target.is_source_code() {
600                             let mut first = true;
601                             for generic_arg in parameters_to_write {
602                                 if !first {
603                                     write!(f, ", ")?;
604                                 }
605                                 first = false;
606
607                                 if generic_arg.ty(Interner).map(|ty| ty.kind(Interner))
608                                     == Some(&TyKind::Error)
609                                 {
610                                     write!(f, "_")?;
611                                 } else {
612                                     generic_arg.hir_fmt(f)?;
613                                 }
614                             }
615                         } else {
616                             f.write_joined(parameters_to_write, ", ")?;
617                         }
618
619                         write!(f, ">")?;
620                     }
621                 }
622             }
623             TyKind::AssociatedType(assoc_type_id, parameters) => {
624                 let type_alias = from_assoc_type_id(*assoc_type_id);
625                 let trait_ = match type_alias.lookup(f.db.upcast()).container {
626                     ItemContainerId::TraitId(it) => it,
627                     _ => panic!("not an associated type"),
628                 };
629                 let trait_ = f.db.trait_data(trait_);
630                 let type_alias_data = f.db.type_alias_data(type_alias);
631
632                 // Use placeholder associated types when the target is test (https://rust-lang.github.io/chalk/book/clauses/type_equality.html#placeholder-associated-types)
633                 if f.display_target.is_test() {
634                     write!(f, "{}::{}", trait_.name, type_alias_data.name)?;
635                     if parameters.len(Interner) > 0 {
636                         write!(f, "<")?;
637                         f.write_joined(&*parameters.as_slice(Interner), ", ")?;
638                         write!(f, ">")?;
639                     }
640                 } else {
641                     let projection_ty = ProjectionTy {
642                         associated_ty_id: to_assoc_type_id(type_alias),
643                         substitution: parameters.clone(),
644                     };
645
646                     projection_ty.hir_fmt(f)?;
647                 }
648             }
649             TyKind::Foreign(type_alias) => {
650                 let type_alias = f.db.type_alias_data(from_foreign_def_id(*type_alias));
651                 write!(f, "{}", type_alias.name)?;
652             }
653             TyKind::OpaqueType(opaque_ty_id, parameters) => {
654                 let impl_trait_id = f.db.lookup_intern_impl_trait_id((*opaque_ty_id).into());
655                 match impl_trait_id {
656                     ImplTraitId::ReturnTypeImplTrait(func, idx) => {
657                         let datas =
658                             f.db.return_type_impl_traits(func).expect("impl trait id without data");
659                         let data = (*datas)
660                             .as_ref()
661                             .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
662                         let bounds = data.substitute(Interner, &parameters);
663                         let krate = func.lookup(f.db.upcast()).module(f.db.upcast()).krate();
664                         write_bounds_like_dyn_trait_with_prefix(
665                             "impl",
666                             bounds.skip_binders(),
667                             SizedByDefault::Sized { anchor: krate },
668                             f,
669                         )?;
670                         // FIXME: it would maybe be good to distinguish this from the alias type (when debug printing), and to show the substitution
671                     }
672                     ImplTraitId::AsyncBlockTypeImplTrait(..) => {
673                         write!(f, "impl Future<Output = ")?;
674                         parameters.at(Interner, 0).hir_fmt(f)?;
675                         write!(f, ">")?;
676                     }
677                 }
678             }
679             TyKind::Closure(.., substs) => {
680                 if f.display_target.is_source_code() {
681                     return Err(HirDisplayError::DisplaySourceCodeError(
682                         DisplaySourceCodeError::Closure,
683                     ));
684                 }
685                 let sig = substs.at(Interner, 0).assert_ty_ref(Interner).callable_sig(f.db);
686                 if let Some(sig) = sig {
687                     if sig.params().is_empty() {
688                         write!(f, "||")?;
689                     } else if f.should_truncate() {
690                         write!(f, "|{}|", TYPE_HINT_TRUNCATION)?;
691                     } else {
692                         write!(f, "|")?;
693                         f.write_joined(sig.params(), ", ")?;
694                         write!(f, "|")?;
695                     };
696
697                     write!(f, " -> ")?;
698                     sig.ret().hir_fmt(f)?;
699                 } else {
700                     write!(f, "{{closure}}")?;
701                 }
702             }
703             TyKind::Placeholder(idx) => {
704                 let id = from_placeholder_idx(f.db, *idx);
705                 let generics = generics(f.db.upcast(), id.parent);
706                 let param_data = &generics.params.type_or_consts[id.local_id];
707                 match param_data {
708                     TypeOrConstParamData::TypeParamData(p) => match p.provenance {
709                         TypeParamProvenance::TypeParamList | TypeParamProvenance::TraitSelf => {
710                             write!(f, "{}", p.name.clone().unwrap_or_else(Name::missing))?
711                         }
712                         TypeParamProvenance::ArgumentImplTrait => {
713                             let substs = generics.placeholder_subst(f.db);
714                             let bounds =
715                                 f.db.generic_predicates(id.parent)
716                                     .iter()
717                                     .map(|pred| pred.clone().substitute(Interner, &substs))
718                                     .filter(|wc| match &wc.skip_binders() {
719                                         WhereClause::Implemented(tr) => {
720                                             &tr.self_type_parameter(Interner) == self
721                                         }
722                                         WhereClause::AliasEq(AliasEq {
723                                             alias: AliasTy::Projection(proj),
724                                             ty: _,
725                                         }) => &proj.self_type_parameter(Interner) == self,
726                                         _ => false,
727                                     })
728                                     .collect::<Vec<_>>();
729                             let krate = id.parent.module(f.db.upcast()).krate();
730                             write_bounds_like_dyn_trait_with_prefix(
731                                 "impl",
732                                 &bounds,
733                                 SizedByDefault::Sized { anchor: krate },
734                                 f,
735                             )?;
736                         }
737                     },
738                     TypeOrConstParamData::ConstParamData(p) => {
739                         write!(f, "{}", p.name)?;
740                     }
741                 }
742             }
743             TyKind::BoundVar(idx) => idx.hir_fmt(f)?,
744             TyKind::Dyn(dyn_ty) => {
745                 write_bounds_like_dyn_trait_with_prefix(
746                     "dyn",
747                     dyn_ty.bounds.skip_binders().interned(),
748                     SizedByDefault::NotSized,
749                     f,
750                 )?;
751             }
752             TyKind::Alias(AliasTy::Projection(p_ty)) => p_ty.hir_fmt(f)?,
753             TyKind::Alias(AliasTy::Opaque(opaque_ty)) => {
754                 let impl_trait_id = f.db.lookup_intern_impl_trait_id(opaque_ty.opaque_ty_id.into());
755                 match impl_trait_id {
756                     ImplTraitId::ReturnTypeImplTrait(func, idx) => {
757                         let datas =
758                             f.db.return_type_impl_traits(func).expect("impl trait id without data");
759                         let data = (*datas)
760                             .as_ref()
761                             .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
762                         let bounds = data.substitute(Interner, &opaque_ty.substitution);
763                         let krate = func.lookup(f.db.upcast()).module(f.db.upcast()).krate();
764                         write_bounds_like_dyn_trait_with_prefix(
765                             "impl",
766                             bounds.skip_binders(),
767                             SizedByDefault::Sized { anchor: krate },
768                             f,
769                         )?;
770                     }
771                     ImplTraitId::AsyncBlockTypeImplTrait(..) => {
772                         write!(f, "{{async block}}")?;
773                     }
774                 };
775             }
776             TyKind::Error => {
777                 if f.display_target.is_source_code() {
778                     return Err(HirDisplayError::DisplaySourceCodeError(
779                         DisplaySourceCodeError::UnknownType,
780                     ));
781                 }
782                 write!(f, "{{unknown}}")?;
783             }
784             TyKind::InferenceVar(..) => write!(f, "_")?,
785             TyKind::Generator(..) => write!(f, "{{generator}}")?,
786             TyKind::GeneratorWitness(..) => write!(f, "{{generator witness}}")?,
787         }
788         Ok(())
789     }
790 }
791
792 impl HirDisplay for CallableSig {
793     fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
794         write!(f, "fn(")?;
795         f.write_joined(self.params(), ", ")?;
796         if self.is_varargs {
797             if self.params().is_empty() {
798                 write!(f, "...")?;
799             } else {
800                 write!(f, ", ...")?;
801             }
802         }
803         write!(f, ")")?;
804         let ret = self.ret();
805         if !ret.is_unit() {
806             write!(f, " -> ")?;
807             ret.hir_fmt(f)?;
808         }
809         Ok(())
810     }
811 }
812
813 fn fn_traits(db: &dyn DefDatabase, trait_: TraitId) -> impl Iterator<Item = TraitId> {
814     let krate = trait_.lookup(db).container.krate();
815     utils::fn_traits(db, krate)
816 }
817
818 #[derive(Clone, Copy, PartialEq, Eq)]
819 pub enum SizedByDefault {
820     NotSized,
821     Sized { anchor: CrateId },
822 }
823
824 impl SizedByDefault {
825     fn is_sized_trait(self, trait_: TraitId, db: &dyn DefDatabase) -> bool {
826         match self {
827             Self::NotSized => false,
828             Self::Sized { anchor } => {
829                 let sized_trait = db
830                     .lang_item(anchor, SmolStr::new_inline("sized"))
831                     .and_then(|lang_item| lang_item.as_trait());
832                 Some(trait_) == sized_trait
833             }
834         }
835     }
836 }
837
838 pub fn write_bounds_like_dyn_trait_with_prefix(
839     prefix: &str,
840     predicates: &[QuantifiedWhereClause],
841     default_sized: SizedByDefault,
842     f: &mut HirFormatter<'_>,
843 ) -> Result<(), HirDisplayError> {
844     write!(f, "{}", prefix)?;
845     if !predicates.is_empty()
846         || predicates.is_empty() && matches!(default_sized, SizedByDefault::Sized { .. })
847     {
848         write!(f, " ")?;
849         write_bounds_like_dyn_trait(predicates, default_sized, f)
850     } else {
851         Ok(())
852     }
853 }
854
855 fn write_bounds_like_dyn_trait(
856     predicates: &[QuantifiedWhereClause],
857     default_sized: SizedByDefault,
858     f: &mut HirFormatter<'_>,
859 ) -> Result<(), HirDisplayError> {
860     // Note: This code is written to produce nice results (i.e.
861     // corresponding to surface Rust) for types that can occur in
862     // actual Rust. It will have weird results if the predicates
863     // aren't as expected (i.e. self types = $0, projection
864     // predicates for a certain trait come after the Implemented
865     // predicate for that trait).
866     let mut first = true;
867     let mut angle_open = false;
868     let mut is_fn_trait = false;
869     let mut is_sized = false;
870     for p in predicates.iter() {
871         match p.skip_binders() {
872             WhereClause::Implemented(trait_ref) => {
873                 let trait_ = trait_ref.hir_trait_id();
874                 if default_sized.is_sized_trait(trait_, f.db.upcast()) {
875                     is_sized = true;
876                     if matches!(default_sized, SizedByDefault::Sized { .. }) {
877                         // Don't print +Sized, but rather +?Sized if absent.
878                         continue;
879                     }
880                 }
881                 if !is_fn_trait {
882                     is_fn_trait = fn_traits(f.db.upcast(), trait_).any(|it| it == trait_);
883                 }
884                 if !is_fn_trait && angle_open {
885                     write!(f, ">")?;
886                     angle_open = false;
887                 }
888                 if !first {
889                     write!(f, " + ")?;
890                 }
891                 // We assume that the self type is ^0.0 (i.e. the
892                 // existential) here, which is the only thing that's
893                 // possible in actual Rust, and hence don't print it
894                 write!(f, "{}", f.db.trait_data(trait_).name)?;
895                 if let [_, params @ ..] = &*trait_ref.substitution.as_slice(Interner) {
896                     if is_fn_trait {
897                         if let Some(args) =
898                             params.first().and_then(|it| it.assert_ty_ref(Interner).as_tuple())
899                         {
900                             write!(f, "(")?;
901                             f.write_joined(args.as_slice(Interner), ", ")?;
902                             write!(f, ")")?;
903                         }
904                     } else if !params.is_empty() {
905                         write!(f, "<")?;
906                         f.write_joined(params, ", ")?;
907                         // there might be assoc type bindings, so we leave the angle brackets open
908                         angle_open = true;
909                     }
910                 }
911             }
912             WhereClause::AliasEq(alias_eq) if is_fn_trait => {
913                 is_fn_trait = false;
914                 if !alias_eq.ty.is_unit() {
915                     write!(f, " -> ")?;
916                     alias_eq.ty.hir_fmt(f)?;
917                 }
918             }
919             WhereClause::AliasEq(AliasEq { ty, alias }) => {
920                 // in types in actual Rust, these will always come
921                 // after the corresponding Implemented predicate
922                 if angle_open {
923                     write!(f, ", ")?;
924                 } else {
925                     write!(f, "<")?;
926                     angle_open = true;
927                 }
928                 if let AliasTy::Projection(proj) = alias {
929                     let type_alias =
930                         f.db.type_alias_data(from_assoc_type_id(proj.associated_ty_id));
931                     write!(f, "{} = ", type_alias.name)?;
932                 }
933                 ty.hir_fmt(f)?;
934             }
935
936             // FIXME implement these
937             WhereClause::LifetimeOutlives(_) => {}
938             WhereClause::TypeOutlives(_) => {}
939         }
940         first = false;
941     }
942     if angle_open {
943         write!(f, ">")?;
944     }
945     if matches!(default_sized, SizedByDefault::Sized { .. }) {
946         if !is_sized {
947             write!(f, "{}?Sized", if first { "" } else { " + " })?;
948         } else if first {
949             write!(f, "Sized")?;
950         }
951     }
952     Ok(())
953 }
954
955 fn fmt_trait_ref(
956     tr: &TraitRef,
957     f: &mut HirFormatter<'_>,
958     use_as: bool,
959 ) -> Result<(), HirDisplayError> {
960     if f.should_truncate() {
961         return write!(f, "{}", TYPE_HINT_TRUNCATION);
962     }
963
964     tr.self_type_parameter(Interner).hir_fmt(f)?;
965     if use_as {
966         write!(f, " as ")?;
967     } else {
968         write!(f, ": ")?;
969     }
970     write!(f, "{}", f.db.trait_data(tr.hir_trait_id()).name)?;
971     if tr.substitution.len(Interner) > 1 {
972         write!(f, "<")?;
973         f.write_joined(&tr.substitution.as_slice(Interner)[1..], ", ")?;
974         write!(f, ">")?;
975     }
976     Ok(())
977 }
978
979 impl HirDisplay for TraitRef {
980     fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
981         fmt_trait_ref(self, f, false)
982     }
983 }
984
985 impl HirDisplay for WhereClause {
986     fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
987         if f.should_truncate() {
988             return write!(f, "{}", TYPE_HINT_TRUNCATION);
989         }
990
991         match self {
992             WhereClause::Implemented(trait_ref) => trait_ref.hir_fmt(f)?,
993             WhereClause::AliasEq(AliasEq { alias: AliasTy::Projection(projection_ty), ty }) => {
994                 write!(f, "<")?;
995                 fmt_trait_ref(&projection_ty.trait_ref(f.db), f, true)?;
996                 write!(
997                     f,
998                     ">::{} = ",
999                     f.db.type_alias_data(from_assoc_type_id(projection_ty.associated_ty_id)).name,
1000                 )?;
1001                 ty.hir_fmt(f)?;
1002             }
1003             WhereClause::AliasEq(_) => write!(f, "{{error}}")?,
1004
1005             // FIXME implement these
1006             WhereClause::TypeOutlives(..) => {}
1007             WhereClause::LifetimeOutlives(..) => {}
1008         }
1009         Ok(())
1010     }
1011 }
1012
1013 impl HirDisplay for LifetimeOutlives {
1014     fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
1015         self.a.hir_fmt(f)?;
1016         write!(f, ": ")?;
1017         self.b.hir_fmt(f)
1018     }
1019 }
1020
1021 impl HirDisplay for Lifetime {
1022     fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
1023         self.interned().hir_fmt(f)
1024     }
1025 }
1026
1027 impl HirDisplay for LifetimeData {
1028     fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
1029         match self {
1030             LifetimeData::BoundVar(idx) => idx.hir_fmt(f),
1031             LifetimeData::InferenceVar(_) => write!(f, "_"),
1032             LifetimeData::Placeholder(idx) => {
1033                 let id = lt_from_placeholder_idx(f.db, *idx);
1034                 let generics = generics(f.db.upcast(), id.parent);
1035                 let param_data = &generics.params.lifetimes[id.local_id];
1036                 write!(f, "{}", param_data.name)
1037             }
1038             LifetimeData::Static => write!(f, "'static"),
1039             LifetimeData::Empty(_) => Ok(()),
1040             LifetimeData::Erased => Ok(()),
1041             LifetimeData::Phantom(_, _) => Ok(()),
1042         }
1043     }
1044 }
1045
1046 impl HirDisplay for DomainGoal {
1047     fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
1048         match self {
1049             DomainGoal::Holds(wc) => {
1050                 write!(f, "Holds(")?;
1051                 wc.hir_fmt(f)?;
1052                 write!(f, ")")?;
1053             }
1054             _ => write!(f, "?")?,
1055         }
1056         Ok(())
1057     }
1058 }
1059
1060 pub fn write_visibility(
1061     module_id: ModuleId,
1062     vis: Visibility,
1063     f: &mut HirFormatter<'_>,
1064 ) -> Result<(), HirDisplayError> {
1065     match vis {
1066         Visibility::Public => write!(f, "pub "),
1067         Visibility::Module(vis_id) => {
1068             let def_map = module_id.def_map(f.db.upcast());
1069             let root_module_id = def_map.module_id(def_map.root());
1070             if vis_id == module_id {
1071                 // pub(self) or omitted
1072                 Ok(())
1073             } else if root_module_id == vis_id {
1074                 write!(f, "pub(crate) ")
1075             } else if module_id.containing_module(f.db.upcast()) == Some(vis_id) {
1076                 write!(f, "pub(super) ")
1077             } else {
1078                 write!(f, "pub(in ...) ")
1079             }
1080         }
1081     }
1082 }
1083
1084 impl HirDisplay for TypeRef {
1085     fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
1086         match self {
1087             TypeRef::Never => write!(f, "!")?,
1088             TypeRef::Placeholder => write!(f, "_")?,
1089             TypeRef::Tuple(elems) => {
1090                 write!(f, "(")?;
1091                 f.write_joined(elems, ", ")?;
1092                 if elems.len() == 1 {
1093                     write!(f, ",")?;
1094                 }
1095                 write!(f, ")")?;
1096             }
1097             TypeRef::Path(path) => path.hir_fmt(f)?,
1098             TypeRef::RawPtr(inner, mutability) => {
1099                 let mutability = match mutability {
1100                     hir_def::type_ref::Mutability::Shared => "*const ",
1101                     hir_def::type_ref::Mutability::Mut => "*mut ",
1102                 };
1103                 write!(f, "{}", mutability)?;
1104                 inner.hir_fmt(f)?;
1105             }
1106             TypeRef::Reference(inner, lifetime, mutability) => {
1107                 let mutability = match mutability {
1108                     hir_def::type_ref::Mutability::Shared => "",
1109                     hir_def::type_ref::Mutability::Mut => "mut ",
1110                 };
1111                 write!(f, "&")?;
1112                 if let Some(lifetime) = lifetime {
1113                     write!(f, "{} ", lifetime.name)?;
1114                 }
1115                 write!(f, "{}", mutability)?;
1116                 inner.hir_fmt(f)?;
1117             }
1118             TypeRef::Array(inner, len) => {
1119                 write!(f, "[")?;
1120                 inner.hir_fmt(f)?;
1121                 write!(f, "; {}]", len)?;
1122             }
1123             TypeRef::Slice(inner) => {
1124                 write!(f, "[")?;
1125                 inner.hir_fmt(f)?;
1126                 write!(f, "]")?;
1127             }
1128             TypeRef::Fn(parameters, is_varargs) => {
1129                 // FIXME: Function pointer qualifiers.
1130                 write!(f, "fn(")?;
1131                 if let Some(((_, return_type), function_parameters)) = parameters.split_last() {
1132                     for index in 0..function_parameters.len() {
1133                         let (param_name, param_type) = &function_parameters[index];
1134                         if let Some(name) = param_name {
1135                             write!(f, "{}: ", name)?;
1136                         }
1137
1138                         param_type.hir_fmt(f)?;
1139
1140                         if index != function_parameters.len() - 1 {
1141                             write!(f, ", ")?;
1142                         }
1143                     }
1144                     if *is_varargs {
1145                         write!(f, "{}...", if parameters.len() == 1 { "" } else { ", " })?;
1146                     }
1147                     write!(f, ")")?;
1148                     match &return_type {
1149                         TypeRef::Tuple(tup) if tup.is_empty() => {}
1150                         _ => {
1151                             write!(f, " -> ")?;
1152                             return_type.hir_fmt(f)?;
1153                         }
1154                     }
1155                 }
1156             }
1157             TypeRef::ImplTrait(bounds) => {
1158                 write!(f, "impl ")?;
1159                 f.write_joined(bounds, " + ")?;
1160             }
1161             TypeRef::DynTrait(bounds) => {
1162                 write!(f, "dyn ")?;
1163                 f.write_joined(bounds, " + ")?;
1164             }
1165             TypeRef::Macro(macro_call) => {
1166                 let macro_call = macro_call.to_node(f.db.upcast());
1167                 let ctx = body::LowerCtx::with_hygiene(f.db.upcast(), &Hygiene::new_unhygienic());
1168                 match macro_call.path() {
1169                     Some(path) => match Path::from_src(path, &ctx) {
1170                         Some(path) => path.hir_fmt(f)?,
1171                         None => write!(f, "{{macro}}")?,
1172                     },
1173                     None => write!(f, "{{macro}}")?,
1174                 }
1175                 write!(f, "!(..)")?;
1176             }
1177             TypeRef::Error => write!(f, "{{error}}")?,
1178         }
1179         Ok(())
1180     }
1181 }
1182
1183 impl HirDisplay for TypeBound {
1184     fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
1185         match self {
1186             TypeBound::Path(path, modifier) => {
1187                 match modifier {
1188                     TraitBoundModifier::None => (),
1189                     TraitBoundModifier::Maybe => write!(f, "?")?,
1190                 }
1191                 path.hir_fmt(f)
1192             }
1193             TypeBound::Lifetime(lifetime) => write!(f, "{}", lifetime.name),
1194             TypeBound::ForLifetime(lifetimes, path) => {
1195                 write!(f, "for<{}> ", lifetimes.iter().format(", "))?;
1196                 path.hir_fmt(f)
1197             }
1198             TypeBound::Error => write!(f, "{{error}}"),
1199         }
1200     }
1201 }
1202
1203 impl HirDisplay for Path {
1204     fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
1205         match (self.type_anchor(), self.kind()) {
1206             (Some(anchor), _) => {
1207                 write!(f, "<")?;
1208                 anchor.hir_fmt(f)?;
1209                 write!(f, ">")?;
1210             }
1211             (_, PathKind::Plain) => {}
1212             (_, PathKind::Abs) => {}
1213             (_, PathKind::Crate) => write!(f, "crate")?,
1214             (_, PathKind::Super(0)) => write!(f, "self")?,
1215             (_, PathKind::Super(n)) => {
1216                 for i in 0..*n {
1217                     if i > 0 {
1218                         write!(f, "::")?;
1219                     }
1220                     write!(f, "super")?;
1221                 }
1222             }
1223             (_, PathKind::DollarCrate(id)) => {
1224                 // Resolve `$crate` to the crate's display name.
1225                 // FIXME: should use the dependency name instead if available, but that depends on
1226                 // the crate invoking `HirDisplay`
1227                 let crate_graph = f.db.crate_graph();
1228                 let name = crate_graph[*id]
1229                     .display_name
1230                     .as_ref()
1231                     .map(|name| name.canonical_name())
1232                     .unwrap_or("$crate");
1233                 write!(f, "{name}")?
1234             }
1235         }
1236
1237         for (seg_idx, segment) in self.segments().iter().enumerate() {
1238             if !matches!(self.kind(), PathKind::Plain) || seg_idx > 0 {
1239                 write!(f, "::")?;
1240             }
1241             write!(f, "{}", segment.name)?;
1242             if let Some(generic_args) = segment.args_and_bindings {
1243                 // We should be in type context, so format as `Foo<Bar>` instead of `Foo::<Bar>`.
1244                 // Do we actually format expressions?
1245                 if generic_args.desugared_from_fn {
1246                     // First argument will be a tuple, which already includes the parentheses.
1247                     // If the tuple only contains 1 item, write it manually to avoid the trailing `,`.
1248                     if let hir_def::path::GenericArg::Type(TypeRef::Tuple(v)) =
1249                         &generic_args.args[0]
1250                     {
1251                         if v.len() == 1 {
1252                             write!(f, "(")?;
1253                             v[0].hir_fmt(f)?;
1254                             write!(f, ")")?;
1255                         } else {
1256                             generic_args.args[0].hir_fmt(f)?;
1257                         }
1258                     }
1259                     if let Some(ret) = &generic_args.bindings[0].type_ref {
1260                         if !matches!(ret, TypeRef::Tuple(v) if v.is_empty()) {
1261                             write!(f, " -> ")?;
1262                             ret.hir_fmt(f)?;
1263                         }
1264                     }
1265                     return Ok(());
1266                 }
1267
1268                 write!(f, "<")?;
1269                 let mut first = true;
1270                 for arg in &generic_args.args {
1271                     if first {
1272                         first = false;
1273                         if generic_args.has_self_type {
1274                             // FIXME: Convert to `<Ty as Trait>` form.
1275                             write!(f, "Self = ")?;
1276                         }
1277                     } else {
1278                         write!(f, ", ")?;
1279                     }
1280                     arg.hir_fmt(f)?;
1281                 }
1282                 for binding in &generic_args.bindings {
1283                     if first {
1284                         first = false;
1285                     } else {
1286                         write!(f, ", ")?;
1287                     }
1288                     write!(f, "{}", binding.name)?;
1289                     match &binding.type_ref {
1290                         Some(ty) => {
1291                             write!(f, " = ")?;
1292                             ty.hir_fmt(f)?
1293                         }
1294                         None => {
1295                             write!(f, ": ")?;
1296                             f.write_joined(&binding.bounds, " + ")?;
1297                         }
1298                     }
1299                 }
1300                 write!(f, ">")?;
1301             }
1302         }
1303         Ok(())
1304     }
1305 }
1306
1307 impl HirDisplay for hir_def::path::GenericArg {
1308     fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
1309         match self {
1310             hir_def::path::GenericArg::Type(ty) => ty.hir_fmt(f),
1311             hir_def::path::GenericArg::Const(c) => write!(f, "{}", c),
1312             hir_def::path::GenericArg::Lifetime(lifetime) => write!(f, "{}", lifetime.name),
1313         }
1314     }
1315 }