]> git.lizzy.rs Git - rust.git/blob - crates/hir_ty/src/display.rs
bca628a5c8864d6fb3f1bce939fe6504db0201ee
[rust.git] / crates / hir_ty / src / display.rs
1 //! The `HirDisplay` trait, which serves two purposes: Turning various bits from
2 //! HIR back into source code, and just displaying them for debugging/testing
3 //! purposes.
4
5 use std::fmt::{self, Debug};
6
7 use base_db::CrateId;
8 use chalk_ir::BoundVar;
9 use hir_def::{
10     body,
11     db::DefDatabase,
12     find_path,
13     generics::TypeParamProvenance,
14     intern::{Internable, Interned},
15     item_scope::ItemInNs,
16     path::{Path, PathKind},
17     type_ref::{TraitBoundModifier, TypeBound, TypeRef},
18     visibility::Visibility,
19     HasModule, ItemContainerId, Lookup, ModuleId, TraitId,
20 };
21 use hir_expand::{hygiene::Hygiene, name::Name};
22 use itertools::Itertools;
23 use syntax::SmolStr;
24
25 use crate::{
26     const_from_placeholder_idx,
27     db::HirDatabase,
28     from_assoc_type_id, from_foreign_def_id, from_placeholder_idx, lt_from_placeholder_idx,
29     mapping::from_chalk,
30     primitive, subst_prefix, to_assoc_type_id,
31     utils::{self, generics},
32     AdtId, AliasEq, AliasTy, CallableDefId, CallableSig, Const, ConstValue, DomainGoal, GenericArg,
33     ImplTraitId, Interner, Lifetime, LifetimeData, LifetimeOutlives, Mutability, OpaqueTy,
34     ProjectionTy, ProjectionTyExt, QuantifiedWhereClause, Scalar, TraitRef, TraitRefExt, Ty, TyExt,
35     TyKind, WhereClause,
36 };
37
38 pub struct HirFormatter<'a> {
39     pub db: &'a dyn HirDatabase,
40     fmt: &'a mut dyn fmt::Write,
41     buf: String,
42     curr_size: usize,
43     pub(crate) max_size: Option<usize>,
44     omit_verbose_types: bool,
45     display_target: DisplayTarget,
46 }
47
48 pub trait HirDisplay {
49     fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError>;
50
51     /// Returns a `Display`able type that is human-readable.
52     fn into_displayable<'a>(
53         &'a self,
54         db: &'a dyn HirDatabase,
55         max_size: Option<usize>,
56         omit_verbose_types: bool,
57         display_target: DisplayTarget,
58     ) -> HirDisplayWrapper<'a, Self>
59     where
60         Self: Sized,
61     {
62         assert!(
63             !matches!(display_target, DisplayTarget::SourceCode { .. }),
64             "HirDisplayWrapper cannot fail with DisplaySourceCodeError, use HirDisplay::hir_fmt directly instead"
65         );
66         HirDisplayWrapper { db, t: self, max_size, omit_verbose_types, display_target }
67     }
68
69     /// Returns a `Display`able type that is human-readable.
70     /// Use this for showing types to the user (e.g. diagnostics)
71     fn display<'a>(&'a self, db: &'a dyn HirDatabase) -> HirDisplayWrapper<'a, Self>
72     where
73         Self: Sized,
74     {
75         HirDisplayWrapper {
76             db,
77             t: self,
78             max_size: None,
79             omit_verbose_types: false,
80             display_target: DisplayTarget::Diagnostics,
81         }
82     }
83
84     /// Returns a `Display`able type that is human-readable and tries to be succinct.
85     /// Use this for showing types to the user where space is constrained (e.g. doc popups)
86     fn display_truncated<'a>(
87         &'a self,
88         db: &'a dyn HirDatabase,
89         max_size: Option<usize>,
90     ) -> HirDisplayWrapper<'a, Self>
91     where
92         Self: Sized,
93     {
94         HirDisplayWrapper {
95             db,
96             t: self,
97             max_size,
98             omit_verbose_types: true,
99             display_target: DisplayTarget::Diagnostics,
100         }
101     }
102
103     /// Returns a String representation of `self` that can be inserted into the given module.
104     /// Use this when generating code (e.g. assists)
105     fn display_source_code<'a>(
106         &'a self,
107         db: &'a dyn HirDatabase,
108         module_id: ModuleId,
109     ) -> Result<String, DisplaySourceCodeError> {
110         let mut result = String::new();
111         match self.hir_fmt(&mut HirFormatter {
112             db,
113             fmt: &mut result,
114             buf: String::with_capacity(20),
115             curr_size: 0,
116             max_size: None,
117             omit_verbose_types: false,
118             display_target: DisplayTarget::SourceCode { module_id },
119         }) {
120             Ok(()) => {}
121             Err(HirDisplayError::FmtError) => panic!("Writing to String can't fail!"),
122             Err(HirDisplayError::DisplaySourceCodeError(e)) => return Err(e),
123         };
124         Ok(result)
125     }
126
127     /// Returns a String representation of `self` for test purposes
128     fn display_test<'a>(&'a self, db: &'a dyn HirDatabase) -> HirDisplayWrapper<'a, Self>
129     where
130         Self: Sized,
131     {
132         HirDisplayWrapper {
133             db,
134             t: self,
135             max_size: None,
136             omit_verbose_types: false,
137             display_target: DisplayTarget::Test,
138         }
139     }
140 }
141
142 impl<'a> HirFormatter<'a> {
143     pub fn write_joined<T: HirDisplay>(
144         &mut self,
145         iter: impl IntoIterator<Item = T>,
146         sep: &str,
147     ) -> Result<(), HirDisplayError> {
148         let mut first = true;
149         for e in iter {
150             if !first {
151                 write!(self, "{}", sep)?;
152             }
153             first = false;
154
155             // Abbreviate multiple omitted types with a single ellipsis.
156             if self.should_truncate() {
157                 return write!(self, "{}", TYPE_HINT_TRUNCATION);
158             }
159
160             e.hir_fmt(self)?;
161         }
162         Ok(())
163     }
164
165     /// This allows using the `write!` macro directly with a `HirFormatter`.
166     pub fn write_fmt(&mut self, args: fmt::Arguments) -> Result<(), HirDisplayError> {
167         // We write to a buffer first to track output size
168         self.buf.clear();
169         fmt::write(&mut self.buf, args)?;
170         self.curr_size += self.buf.len();
171
172         // Then we write to the internal formatter from the buffer
173         self.fmt.write_str(&self.buf).map_err(HirDisplayError::from)
174     }
175
176     pub fn should_truncate(&self) -> bool {
177         match self.max_size {
178             Some(max_size) => self.curr_size >= max_size,
179             None => false,
180         }
181     }
182
183     pub fn omit_verbose_types(&self) -> bool {
184         self.omit_verbose_types
185     }
186 }
187
188 #[derive(Clone, Copy)]
189 pub enum DisplayTarget {
190     /// Display types for inlays, doc popups, autocompletion, etc...
191     /// Showing `{unknown}` or not qualifying paths is fine here.
192     /// There's no reason for this to fail.
193     Diagnostics,
194     /// Display types for inserting them in source files.
195     /// The generated code should compile, so paths need to be qualified.
196     SourceCode { module_id: ModuleId },
197     /// Only for test purpose to keep real types
198     Test,
199 }
200
201 impl DisplayTarget {
202     fn is_source_code(&self) -> bool {
203         matches!(self, Self::SourceCode { .. })
204     }
205     fn is_test(&self) -> bool {
206         matches!(self, Self::Test)
207     }
208 }
209
210 #[derive(Debug)]
211 pub enum DisplaySourceCodeError {
212     PathNotFound,
213     UnknownType,
214     Closure,
215 }
216
217 pub enum HirDisplayError {
218     /// Errors that can occur when generating source code
219     DisplaySourceCodeError(DisplaySourceCodeError),
220     /// `FmtError` is required to be compatible with std::fmt::Display
221     FmtError,
222 }
223 impl From<fmt::Error> for HirDisplayError {
224     fn from(_: fmt::Error) -> Self {
225         Self::FmtError
226     }
227 }
228
229 pub struct HirDisplayWrapper<'a, T> {
230     db: &'a dyn HirDatabase,
231     t: &'a T,
232     max_size: Option<usize>,
233     omit_verbose_types: bool,
234     display_target: DisplayTarget,
235 }
236
237 impl<'a, T> fmt::Display for HirDisplayWrapper<'a, T>
238 where
239     T: HirDisplay,
240 {
241     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
242         println!("formatting..");
243         match self.t.hir_fmt(&mut HirFormatter {
244             db: self.db,
245             fmt: f,
246             buf: String::with_capacity(20),
247             curr_size: 0,
248             max_size: self.max_size,
249             omit_verbose_types: self.omit_verbose_types,
250             display_target: self.display_target,
251         }) {
252             Ok(()) => Ok(()),
253             Err(HirDisplayError::FmtError) => Err(fmt::Error),
254             Err(HirDisplayError::DisplaySourceCodeError(_)) => {
255                 // This should never happen
256                 panic!("HirDisplay::hir_fmt failed with DisplaySourceCodeError when calling Display::fmt!")
257             }
258         }
259     }
260 }
261
262 const TYPE_HINT_TRUNCATION: &str = "…";
263
264 impl<T: HirDisplay> HirDisplay for &'_ T {
265     fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
266         HirDisplay::hir_fmt(*self, f)
267     }
268 }
269
270 impl<T: HirDisplay + Internable> HirDisplay for Interned<T> {
271     fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
272         HirDisplay::hir_fmt(self.as_ref(), f)
273     }
274 }
275
276 impl HirDisplay for ProjectionTy {
277     fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
278         if f.should_truncate() {
279             return write!(f, "{}", TYPE_HINT_TRUNCATION);
280         }
281
282         let trait_ = f.db.trait_data(self.trait_(f.db));
283         write!(f, "<")?;
284         self.self_type_parameter(Interner).hir_fmt(f)?;
285         write!(f, " as {}", trait_.name)?;
286         if self.substitution.len(Interner) > 1 {
287             write!(f, "<")?;
288             f.write_joined(&self.substitution.as_slice(Interner)[1..], ", ")?;
289             write!(f, ">")?;
290         }
291         write!(f, ">::{}", f.db.type_alias_data(from_assoc_type_id(self.associated_ty_id)).name)?;
292         Ok(())
293     }
294 }
295
296 impl HirDisplay for OpaqueTy {
297     fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
298         if f.should_truncate() {
299             return write!(f, "{}", TYPE_HINT_TRUNCATION);
300         }
301
302         self.substitution.at(Interner, 0).hir_fmt(f)
303     }
304 }
305
306 impl HirDisplay for GenericArg {
307     fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
308         match self.interned() {
309             crate::GenericArgData::Ty(ty) => ty.hir_fmt(f),
310             crate::GenericArgData::Lifetime(lt) => lt.hir_fmt(f),
311             crate::GenericArgData::Const(c) => c.hir_fmt(f),
312         }
313     }
314 }
315
316 impl HirDisplay for Const {
317     fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
318         let data = self.interned();
319         match data.value {
320             ConstValue::BoundVar(idx) => idx.hir_fmt(f),
321             ConstValue::InferenceVar(..) => write!(f, "_"),
322             ConstValue::Placeholder(idx) => {
323                 let id = const_from_placeholder_idx(f.db, idx);
324                 let generics = generics(f.db.upcast(), id.parent);
325                 let param_data = &generics.params.consts[id.local_id];
326                 write!(f, "{}", param_data.name)
327             }
328             ConstValue::Concrete(c) => write!(f, "{}", c.interned),
329         }
330     }
331 }
332
333 impl HirDisplay for BoundVar {
334     fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
335         write!(f, "?{}.{}", self.debruijn.depth(), self.index)
336     }
337 }
338
339 impl HirDisplay for Ty {
340     fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
341         if f.should_truncate() {
342             return write!(f, "{}", TYPE_HINT_TRUNCATION);
343         }
344
345         let interner_kind = self.kind(Interner);
346         println!("interner kind: {interner_kind:?}");
347
348         match self.kind(Interner) {
349             TyKind::Never => write!(f, "!")?,
350             TyKind::Str => write!(f, "str")?,
351             TyKind::Scalar(Scalar::Bool) => write!(f, "bool")?,
352             TyKind::Scalar(Scalar::Char) => write!(f, "char")?,
353             &TyKind::Scalar(Scalar::Float(t)) => write!(f, "{}", primitive::float_ty_to_string(t))?,
354             &TyKind::Scalar(Scalar::Int(t)) => write!(f, "{}", primitive::int_ty_to_string(t))?,
355             &TyKind::Scalar(Scalar::Uint(t)) => write!(f, "{}", primitive::uint_ty_to_string(t))?,
356             TyKind::Slice(t) => {
357                 write!(f, "[")?;
358                 t.hir_fmt(f)?;
359                 write!(f, "]")?;
360             }
361             TyKind::Array(t, c) => {
362                 write!(f, "[")?;
363                 t.hir_fmt(f)?;
364                 write!(f, "; ")?;
365                 c.hir_fmt(f)?;
366                 write!(f, "]")?;
367             }
368             TyKind::Raw(m, t) | TyKind::Ref(m, _, t) => {
369                 if matches!(self.kind(Interner), TyKind::Raw(..)) {
370                     write!(
371                         f,
372                         "*{}",
373                         match m {
374                             Mutability::Not => "const ",
375                             Mutability::Mut => "mut ",
376                         }
377                     )?;
378                 } else {
379                     write!(
380                         f,
381                         "&{}",
382                         match m {
383                             Mutability::Not => "",
384                             Mutability::Mut => "mut ",
385                         }
386                     )?;
387                 }
388
389                 // FIXME: all this just to decide whether to use parentheses...
390                 let contains_impl_fn = |bounds: &[QuantifiedWhereClause]| {
391                     bounds.iter().any(|bound| {
392                         if let WhereClause::Implemented(trait_ref) = bound.skip_binders() {
393                             let trait_ = trait_ref.hir_trait_id();
394                             fn_traits(f.db.upcast(), trait_).any(|it| it == trait_)
395                         } else {
396                             false
397                         }
398                     })
399                 };
400                 let (preds_to_print, has_impl_fn_pred) = match t.kind(Interner) {
401                     TyKind::Dyn(dyn_ty) if dyn_ty.bounds.skip_binders().interned().len() > 1 => {
402                         let bounds = dyn_ty.bounds.skip_binders().interned();
403                         (bounds.len(), contains_impl_fn(bounds))
404                     }
405                     TyKind::Alias(AliasTy::Opaque(OpaqueTy {
406                         opaque_ty_id,
407                         substitution: parameters,
408                     }))
409                     | TyKind::OpaqueType(opaque_ty_id, parameters) => {
410                         let impl_trait_id =
411                             f.db.lookup_intern_impl_trait_id((*opaque_ty_id).into());
412                         if let ImplTraitId::ReturnTypeImplTrait(func, idx) = impl_trait_id {
413                             let datas =
414                                 f.db.return_type_impl_traits(func)
415                                     .expect("impl trait id without data");
416                             let data = (*datas)
417                                 .as_ref()
418                                 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
419                             let bounds = data.substitute(Interner, parameters);
420                             let mut len = bounds.skip_binders().len();
421
422                             // Don't count Sized but count when it absent
423                             // (i.e. when explicit ?Sized bound is set).
424                             let default_sized = SizedByDefault::Sized {
425                                 anchor: func.lookup(f.db.upcast()).module(f.db.upcast()).krate(),
426                             };
427                             let sized_bounds = bounds
428                                 .skip_binders()
429                                 .iter()
430                                 .filter(|b| {
431                                     matches!(
432                                         b.skip_binders(),
433                                         WhereClause::Implemented(trait_ref)
434                                             if default_sized.is_sized_trait(
435                                                 trait_ref.hir_trait_id(),
436                                                 f.db.upcast(),
437                                             ),
438                                     )
439                                 })
440                                 .count();
441                             match sized_bounds {
442                                 0 => len += 1,
443                                 _ => {
444                                     len = len.saturating_sub(sized_bounds);
445                                 }
446                             }
447
448                             (len, contains_impl_fn(bounds.skip_binders()))
449                         } else {
450                             (0, false)
451                         }
452                     }
453                     _ => (0, false),
454                 };
455
456                 if has_impl_fn_pred && preds_to_print <= 2 {
457                     return t.hir_fmt(f);
458                 }
459
460                 if preds_to_print > 1 {
461                     write!(f, "(")?;
462                     t.hir_fmt(f)?;
463                     write!(f, ")")?;
464                 } else {
465                     t.hir_fmt(f)?;
466                 }
467             }
468             TyKind::Tuple(_, substs) => {
469                 if substs.len(Interner) == 1 {
470                     write!(f, "(")?;
471                     substs.at(Interner, 0).hir_fmt(f)?;
472                     write!(f, ",)")?;
473                 } else {
474                     write!(f, "(")?;
475                     f.write_joined(&*substs.as_slice(Interner), ", ")?;
476                     write!(f, ")")?;
477                 }
478             }
479             TyKind::Function(fn_ptr) => {
480                 let sig = CallableSig::from_fn_ptr(fn_ptr);
481                 sig.hir_fmt(f)?;
482             }
483             TyKind::FnDef(def, parameters) => {
484                 let def = from_chalk(f.db, *def);
485                 let sig = f.db.callable_item_signature(def).substitute(Interner, parameters);
486                 match def {
487                     CallableDefId::FunctionId(ff) => {
488                         write!(f, "fn {}", f.db.function_data(ff).name)?
489                     }
490                     CallableDefId::StructId(s) => write!(f, "{}", f.db.struct_data(s).name)?,
491                     CallableDefId::EnumVariantId(e) => {
492                         write!(f, "{}", f.db.enum_data(e.parent).variants[e.local_id].name)?
493                     }
494                 };
495                 if parameters.len(Interner) > 0 {
496                     let generics = generics(f.db.upcast(), def.into());
497                     let (parent_params, self_param, type_params, _impl_trait_params) =
498                         generics.provenance_split();
499                     let total_len = parent_params + self_param + type_params;
500                     // We print all params except implicit impl Trait params. Still a bit weird; should we leave out parent and self?
501                     if total_len > 0 {
502                         write!(f, "<")?;
503                         f.write_joined(&parameters.as_slice(Interner)[..total_len], ", ")?;
504                         write!(f, ">")?;
505                     }
506                 }
507                 write!(f, "(")?;
508                 f.write_joined(sig.params(), ", ")?;
509                 write!(f, ")")?;
510                 let ret = sig.ret();
511                 if !ret.is_unit() {
512                     write!(f, " -> ")?;
513                     ret.hir_fmt(f)?;
514                 }
515             }
516             TyKind::Adt(AdtId(def_id), parameters) => {
517                 match f.display_target {
518                     DisplayTarget::Diagnostics | DisplayTarget::Test => {
519                         let name = match *def_id {
520                             hir_def::AdtId::StructId(it) => f.db.struct_data(it).name.clone(),
521                             hir_def::AdtId::UnionId(it) => f.db.union_data(it).name.clone(),
522                             hir_def::AdtId::EnumId(it) => f.db.enum_data(it).name.clone(),
523                         };
524                         write!(f, "{}", name)?;
525                     }
526                     DisplayTarget::SourceCode { module_id } => {
527                         if let Some(path) = find_path::find_path(
528                             f.db.upcast(),
529                             ItemInNs::Types((*def_id).into()),
530                             module_id,
531                         ) {
532                             write!(f, "{}", path)?;
533                         } else {
534                             return Err(HirDisplayError::DisplaySourceCodeError(
535                                 DisplaySourceCodeError::PathNotFound,
536                             ));
537                         }
538                     }
539                 }
540
541                 if parameters.len(Interner) > 0 {
542                     let parameters_to_write = if f.display_target.is_source_code()
543                         || f.omit_verbose_types()
544                     {
545                         match self
546                             .as_generic_def(f.db)
547                             .map(|generic_def_id| f.db.generic_defaults(generic_def_id))
548                             .filter(|defaults| !defaults.is_empty())
549                         {
550                             None => parameters.as_slice(Interner),
551                             Some(default_parameters) => {
552                                 let mut default_from = 0;
553                                 for (i, parameter) in parameters.iter(Interner).enumerate() {
554                                     match (
555                                         parameter.assert_ty_ref(Interner).kind(Interner),
556                                         default_parameters.get(i),
557                                     ) {
558                                         (&TyKind::Error, _) | (_, None) => {
559                                             default_from = i + 1;
560                                         }
561                                         (_, Some(default_parameter)) => {
562                                             let actual_default = default_parameter
563                                                 .clone()
564                                                 .substitute(Interner, &subst_prefix(parameters, i));
565                                             if parameter.assert_ty_ref(Interner) != &actual_default
566                                             {
567                                                 default_from = i + 1;
568                                             }
569                                         }
570                                     }
571                                 }
572                                 &parameters.as_slice(Interner)[0..default_from]
573                             }
574                         }
575                     } else {
576                         parameters.as_slice(Interner)
577                     };
578                     if !parameters_to_write.is_empty() {
579                         write!(f, "<")?;
580
581                         if f.display_target.is_source_code() {
582                             let mut first = true;
583                             for generic_arg in parameters_to_write {
584                                 if !first {
585                                     write!(f, ", ")?;
586                                 }
587                                 first = false;
588
589                                 if generic_arg.ty(Interner).map(|ty| ty.kind(Interner))
590                                     == Some(&TyKind::Error)
591                                 {
592                                     write!(f, "_")?;
593                                 } else {
594                                     generic_arg.hir_fmt(f)?;
595                                 }
596                             }
597                         } else {
598                             f.write_joined(parameters_to_write, ", ")?;
599                         }
600
601                         write!(f, ">")?;
602                     }
603                 }
604             }
605             TyKind::AssociatedType(assoc_type_id, parameters) => {
606                 let type_alias = from_assoc_type_id(*assoc_type_id);
607                 let trait_ = match type_alias.lookup(f.db.upcast()).container {
608                     ItemContainerId::TraitId(it) => it,
609                     _ => panic!("not an associated type"),
610                 };
611                 let trait_ = f.db.trait_data(trait_);
612                 let type_alias_data = f.db.type_alias_data(type_alias);
613
614                 // Use placeholder associated types when the target is test (https://rust-lang.github.io/chalk/book/clauses/type_equality.html#placeholder-associated-types)
615                 if f.display_target.is_test() {
616                     write!(f, "{}::{}", trait_.name, type_alias_data.name)?;
617                     if parameters.len(Interner) > 0 {
618                         write!(f, "<")?;
619                         f.write_joined(&*parameters.as_slice(Interner), ", ")?;
620                         write!(f, ">")?;
621                     }
622                 } else {
623                     let projection_ty = ProjectionTy {
624                         associated_ty_id: to_assoc_type_id(type_alias),
625                         substitution: parameters.clone(),
626                     };
627
628                     projection_ty.hir_fmt(f)?;
629                 }
630             }
631             TyKind::Foreign(type_alias) => {
632                 let type_alias = f.db.type_alias_data(from_foreign_def_id(*type_alias));
633                 write!(f, "{}", type_alias.name)?;
634             }
635             TyKind::OpaqueType(opaque_ty_id, parameters) => {
636                 let impl_trait_id = f.db.lookup_intern_impl_trait_id((*opaque_ty_id).into());
637                 match impl_trait_id {
638                     ImplTraitId::ReturnTypeImplTrait(func, idx) => {
639                         let datas =
640                             f.db.return_type_impl_traits(func).expect("impl trait id without data");
641                         let data = (*datas)
642                             .as_ref()
643                             .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
644                         let bounds = data.substitute(Interner, &parameters);
645                         let krate = func.lookup(f.db.upcast()).module(f.db.upcast()).krate();
646                         write_bounds_like_dyn_trait_with_prefix(
647                             "impl",
648                             bounds.skip_binders(),
649                             SizedByDefault::Sized { anchor: krate },
650                             f,
651                         )?;
652                         // FIXME: it would maybe be good to distinguish this from the alias type (when debug printing), and to show the substitution
653                     }
654                     ImplTraitId::AsyncBlockTypeImplTrait(..) => {
655                         write!(f, "impl Future<Output = ")?;
656                         parameters.at(Interner, 0).hir_fmt(f)?;
657                         write!(f, ">")?;
658                     }
659                 }
660             }
661             TyKind::Closure(.., substs) => {
662                 if f.display_target.is_source_code() {
663                     return Err(HirDisplayError::DisplaySourceCodeError(
664                         DisplaySourceCodeError::Closure,
665                     ));
666                 }
667                 let sig = substs.at(Interner, 0).assert_ty_ref(Interner).callable_sig(f.db);
668                 if let Some(sig) = sig {
669                     if sig.params().is_empty() {
670                         write!(f, "||")?;
671                     } else if f.should_truncate() {
672                         write!(f, "|{}|", TYPE_HINT_TRUNCATION)?;
673                     } else {
674                         write!(f, "|")?;
675                         f.write_joined(sig.params(), ", ")?;
676                         write!(f, "|")?;
677                     };
678
679                     write!(f, " -> ")?;
680                     sig.ret().hir_fmt(f)?;
681                 } else {
682                     write!(f, "{{closure}}")?;
683                 }
684             }
685             TyKind::Placeholder(idx) => {
686                 let id = from_placeholder_idx(f.db, *idx);
687                 let generics = generics(f.db.upcast(), id.parent);
688                 let param_data = &generics.params.types[id.local_id];
689                 match param_data.provenance {
690                     TypeParamProvenance::TypeParamList | TypeParamProvenance::TraitSelf => {
691                         write!(f, "{}", param_data.name.clone().unwrap_or_else(Name::missing))?
692                     }
693                     TypeParamProvenance::ArgumentImplTrait => {
694                         let substs = generics.type_params_subst(f.db);
695                         let bounds =
696                             f.db.generic_predicates(id.parent)
697                                 .iter()
698                                 .map(|pred| pred.clone().substitute(Interner, &substs))
699                                 .filter(|wc| match &wc.skip_binders() {
700                                     WhereClause::Implemented(tr) => {
701                                         &tr.self_type_parameter(Interner) == self
702                                     }
703                                     WhereClause::AliasEq(AliasEq {
704                                         alias: AliasTy::Projection(proj),
705                                         ty: _,
706                                     }) => &proj.self_type_parameter(Interner) == self,
707                                     _ => false,
708                                 })
709                                 .collect::<Vec<_>>();
710                         let krate = id.parent.module(f.db.upcast()).krate();
711                         write_bounds_like_dyn_trait_with_prefix(
712                             "impl",
713                             &bounds,
714                             SizedByDefault::Sized { anchor: krate },
715                             f,
716                         )?;
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                 write!(f, "fn(")?;
1103                 for index in 0..parameters.len() - 1 {
1104                     let (param_name,param_type) = &parameters[index];
1105                     match param_name {
1106                         Some(name) => {
1107                             write!(f, "{}: ", name)?;
1108                             param_type.hir_fmt(f)?;
1109                         },
1110                         None => write!(f, " : {:?}", param_type)?,
1111                     };
1112
1113                     if index != parameters.len() - 2 {
1114                         write!(f, ", ")?;
1115                     }
1116                 }
1117                 if *is_varargs {
1118                     write!(f, "{}...", if parameters.len() == 1 { "" } else { ", " })?;
1119                 }
1120                 write!(f, ")")?;
1121                 let ret_ty = &parameters.last().unwrap().1;
1122                 match ret_ty {
1123                     TypeRef::Tuple(tup) if tup.is_empty() => {}
1124                     _ => {
1125                         write!(f, " -> ")?;
1126                         ret_ty.hir_fmt(f)?;
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(_)) => write!(f, "{{extern_crate}}")?,
1197         }
1198
1199         for (seg_idx, segment) in self.segments().iter().enumerate() {
1200             if !matches!(self.kind(), PathKind::Plain) || seg_idx > 0 {
1201                 write!(f, "::")?;
1202             }
1203             write!(f, "{}", segment.name)?;
1204             if let Some(generic_args) = segment.args_and_bindings {
1205                 // We should be in type context, so format as `Foo<Bar>` instead of `Foo::<Bar>`.
1206                 // Do we actually format expressions?
1207                 if generic_args.desugared_from_fn {
1208                     // First argument will be a tuple, which already includes the parentheses.
1209                     // If the tuple only contains 1 item, write it manually to avoid the trailing `,`.
1210                     if let hir_def::path::GenericArg::Type(TypeRef::Tuple(v)) =
1211                         &generic_args.args[0]
1212                     {
1213                         if v.len() == 1 {
1214                             write!(f, "(")?;
1215                             v[0].hir_fmt(f)?;
1216                             write!(f, ")")?;
1217                         } else {
1218                             generic_args.args[0].hir_fmt(f)?;
1219                         }
1220                     }
1221                     if let Some(ret) = &generic_args.bindings[0].type_ref {
1222                         if !matches!(ret, TypeRef::Tuple(v) if v.is_empty()) {
1223                             write!(f, " -> ")?;
1224                             ret.hir_fmt(f)?;
1225                         }
1226                     }
1227                     return Ok(());
1228                 }
1229
1230                 write!(f, "<")?;
1231                 let mut first = true;
1232                 for arg in &generic_args.args {
1233                     if first {
1234                         first = false;
1235                         if generic_args.has_self_type {
1236                             // FIXME: Convert to `<Ty as Trait>` form.
1237                             write!(f, "Self = ")?;
1238                         }
1239                     } else {
1240                         write!(f, ", ")?;
1241                     }
1242                     arg.hir_fmt(f)?;
1243                 }
1244                 for binding in &generic_args.bindings {
1245                     if first {
1246                         first = false;
1247                     } else {
1248                         write!(f, ", ")?;
1249                     }
1250                     write!(f, "{}", binding.name)?;
1251                     match &binding.type_ref {
1252                         Some(ty) => {
1253                             write!(f, " = ")?;
1254                             ty.hir_fmt(f)?
1255                         }
1256                         None => {
1257                             write!(f, ": ")?;
1258                             f.write_joined(&binding.bounds, " + ")?;
1259                         }
1260                     }
1261                 }
1262                 write!(f, ">")?;
1263             }
1264         }
1265         Ok(())
1266     }
1267 }
1268
1269 impl HirDisplay for hir_def::path::GenericArg {
1270     fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1271         match self {
1272             hir_def::path::GenericArg::Type(ty) => ty.hir_fmt(f),
1273             hir_def::path::GenericArg::Lifetime(lifetime) => write!(f, "{}", lifetime.name),
1274         }
1275     }
1276 }