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