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