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