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