]> git.lizzy.rs Git - rust.git/blob - crates/hir_ty/src/display.rs
Merge #11173
[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
571                         if f.display_target.is_source_code() {
572                             let mut first = true;
573                             for generic_arg in parameters_to_write {
574                                 if !first {
575                                     write!(f, ", ")?;
576                                 }
577                                 first = false;
578
579                                 if generic_arg.ty(Interner).map(|ty| ty.kind(Interner))
580                                     == Some(&TyKind::Error)
581                                 {
582                                     write!(f, "_")?;
583                                 } else {
584                                     generic_arg.hir_fmt(f)?;
585                                 }
586                             }
587                         } else {
588                             f.write_joined(parameters_to_write, ", ")?;
589                         }
590
591                         write!(f, ">")?;
592                     }
593                 }
594             }
595             TyKind::AssociatedType(assoc_type_id, parameters) => {
596                 let type_alias = from_assoc_type_id(*assoc_type_id);
597                 let trait_ = match type_alias.lookup(f.db.upcast()).container {
598                     ItemContainerId::TraitId(it) => it,
599                     _ => panic!("not an associated type"),
600                 };
601                 let trait_ = f.db.trait_data(trait_);
602                 let type_alias_data = f.db.type_alias_data(type_alias);
603
604                 // Use placeholder associated types when the target is test (https://rust-lang.github.io/chalk/book/clauses/type_equality.html#placeholder-associated-types)
605                 if f.display_target.is_test() {
606                     write!(f, "{}::{}", trait_.name, type_alias_data.name)?;
607                     if parameters.len(Interner) > 0 {
608                         write!(f, "<")?;
609                         f.write_joined(&*parameters.as_slice(Interner), ", ")?;
610                         write!(f, ">")?;
611                     }
612                 } else {
613                     let projection_ty = ProjectionTy {
614                         associated_ty_id: to_assoc_type_id(type_alias),
615                         substitution: parameters.clone(),
616                     };
617
618                     projection_ty.hir_fmt(f)?;
619                 }
620             }
621             TyKind::Foreign(type_alias) => {
622                 let type_alias = f.db.type_alias_data(from_foreign_def_id(*type_alias));
623                 write!(f, "{}", type_alias.name)?;
624             }
625             TyKind::OpaqueType(opaque_ty_id, parameters) => {
626                 let impl_trait_id = f.db.lookup_intern_impl_trait_id((*opaque_ty_id).into());
627                 match impl_trait_id {
628                     ImplTraitId::ReturnTypeImplTrait(func, idx) => {
629                         let datas =
630                             f.db.return_type_impl_traits(func).expect("impl trait id without data");
631                         let data = (*datas)
632                             .as_ref()
633                             .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
634                         let bounds = data.substitute(Interner, &parameters);
635                         let krate = func.lookup(f.db.upcast()).module(f.db.upcast()).krate();
636                         write_bounds_like_dyn_trait_with_prefix(
637                             "impl",
638                             bounds.skip_binders(),
639                             SizedByDefault::Sized { anchor: krate },
640                             f,
641                         )?;
642                         // FIXME: it would maybe be good to distinguish this from the alias type (when debug printing), and to show the substitution
643                     }
644                     ImplTraitId::AsyncBlockTypeImplTrait(..) => {
645                         write!(f, "impl Future<Output = ")?;
646                         parameters.at(Interner, 0).hir_fmt(f)?;
647                         write!(f, ">")?;
648                     }
649                 }
650             }
651             TyKind::Closure(.., substs) => {
652                 if f.display_target.is_source_code() {
653                     return Err(HirDisplayError::DisplaySourceCodeError(
654                         DisplaySourceCodeError::Closure,
655                     ));
656                 }
657                 let sig = substs.at(Interner, 0).assert_ty_ref(Interner).callable_sig(f.db);
658                 if let Some(sig) = sig {
659                     if sig.params().is_empty() {
660                         write!(f, "||")?;
661                     } else if f.should_truncate() {
662                         write!(f, "|{}|", TYPE_HINT_TRUNCATION)?;
663                     } else {
664                         write!(f, "|")?;
665                         f.write_joined(sig.params(), ", ")?;
666                         write!(f, "|")?;
667                     };
668
669                     write!(f, " -> ")?;
670                     sig.ret().hir_fmt(f)?;
671                 } else {
672                     write!(f, "{{closure}}")?;
673                 }
674             }
675             TyKind::Placeholder(idx) => {
676                 let id = from_placeholder_idx(f.db, *idx);
677                 let generics = generics(f.db.upcast(), id.parent);
678                 let param_data = &generics.params.types[id.local_id];
679                 match param_data.provenance {
680                     TypeParamProvenance::TypeParamList | TypeParamProvenance::TraitSelf => {
681                         write!(f, "{}", param_data.name.clone().unwrap_or_else(Name::missing))?
682                     }
683                     TypeParamProvenance::ArgumentImplTrait => {
684                         let substs = generics.type_params_subst(f.db);
685                         let bounds =
686                             f.db.generic_predicates(id.parent)
687                                 .iter()
688                                 .map(|pred| pred.clone().substitute(Interner, &substs))
689                                 .filter(|wc| match &wc.skip_binders() {
690                                     WhereClause::Implemented(tr) => {
691                                         &tr.self_type_parameter(Interner) == self
692                                     }
693                                     WhereClause::AliasEq(AliasEq {
694                                         alias: AliasTy::Projection(proj),
695                                         ty: _,
696                                     }) => &proj.self_type_parameter(Interner) == self,
697                                     _ => false,
698                                 })
699                                 .collect::<Vec<_>>();
700                         let krate = id.parent.module(f.db.upcast()).krate();
701                         write_bounds_like_dyn_trait_with_prefix(
702                             "impl",
703                             &bounds,
704                             SizedByDefault::Sized { anchor: krate },
705                             f,
706                         )?;
707                     }
708                 }
709             }
710             TyKind::BoundVar(idx) => idx.hir_fmt(f)?,
711             TyKind::Dyn(dyn_ty) => {
712                 write_bounds_like_dyn_trait_with_prefix(
713                     "dyn",
714                     dyn_ty.bounds.skip_binders().interned(),
715                     SizedByDefault::NotSized,
716                     f,
717                 )?;
718             }
719             TyKind::Alias(AliasTy::Projection(p_ty)) => p_ty.hir_fmt(f)?,
720             TyKind::Alias(AliasTy::Opaque(opaque_ty)) => {
721                 let impl_trait_id = f.db.lookup_intern_impl_trait_id(opaque_ty.opaque_ty_id.into());
722                 match impl_trait_id {
723                     ImplTraitId::ReturnTypeImplTrait(func, idx) => {
724                         let datas =
725                             f.db.return_type_impl_traits(func).expect("impl trait id without data");
726                         let data = (*datas)
727                             .as_ref()
728                             .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
729                         let bounds = data.substitute(Interner, &opaque_ty.substitution);
730                         let krate = func.lookup(f.db.upcast()).module(f.db.upcast()).krate();
731                         write_bounds_like_dyn_trait_with_prefix(
732                             "impl",
733                             bounds.skip_binders(),
734                             SizedByDefault::Sized { anchor: krate },
735                             f,
736                         )?;
737                     }
738                     ImplTraitId::AsyncBlockTypeImplTrait(..) => {
739                         write!(f, "{{async block}}")?;
740                     }
741                 };
742             }
743             TyKind::Error => {
744                 if f.display_target.is_source_code() {
745                     return Err(HirDisplayError::DisplaySourceCodeError(
746                         DisplaySourceCodeError::UnknownType,
747                     ));
748                 }
749                 write!(f, "{{unknown}}")?;
750             }
751             TyKind::InferenceVar(..) => write!(f, "_")?,
752             TyKind::Generator(..) => write!(f, "{{generator}}")?,
753             TyKind::GeneratorWitness(..) => write!(f, "{{generator witness}}")?,
754         }
755         Ok(())
756     }
757 }
758
759 impl HirDisplay for CallableSig {
760     fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
761         write!(f, "fn(")?;
762         f.write_joined(self.params(), ", ")?;
763         if self.is_varargs {
764             if self.params().is_empty() {
765                 write!(f, "...")?;
766             } else {
767                 write!(f, ", ...")?;
768             }
769         }
770         write!(f, ")")?;
771         let ret = self.ret();
772         if !ret.is_unit() {
773             write!(f, " -> ")?;
774             ret.hir_fmt(f)?;
775         }
776         Ok(())
777     }
778 }
779
780 fn fn_traits(db: &dyn DefDatabase, trait_: TraitId) -> impl Iterator<Item = TraitId> {
781     let krate = trait_.lookup(db).container.krate();
782     utils::fn_traits(db, krate)
783 }
784
785 #[derive(Clone, Copy, PartialEq, Eq)]
786 pub enum SizedByDefault {
787     NotSized,
788     Sized { anchor: CrateId },
789 }
790
791 impl SizedByDefault {
792     fn is_sized_trait(self, trait_: TraitId, db: &dyn DefDatabase) -> bool {
793         match self {
794             Self::NotSized => false,
795             Self::Sized { anchor } => {
796                 let sized_trait = db
797                     .lang_item(anchor, SmolStr::new_inline("sized"))
798                     .and_then(|lang_item| lang_item.as_trait());
799                 Some(trait_) == sized_trait
800             }
801         }
802     }
803 }
804
805 pub fn write_bounds_like_dyn_trait_with_prefix(
806     prefix: &str,
807     predicates: &[QuantifiedWhereClause],
808     default_sized: SizedByDefault,
809     f: &mut HirFormatter,
810 ) -> Result<(), HirDisplayError> {
811     write!(f, "{}", prefix)?;
812     if !predicates.is_empty()
813         || predicates.is_empty() && matches!(default_sized, SizedByDefault::Sized { .. })
814     {
815         write!(f, " ")?;
816         write_bounds_like_dyn_trait(predicates, default_sized, f)
817     } else {
818         Ok(())
819     }
820 }
821
822 fn write_bounds_like_dyn_trait(
823     predicates: &[QuantifiedWhereClause],
824     default_sized: SizedByDefault,
825     f: &mut HirFormatter,
826 ) -> Result<(), HirDisplayError> {
827     // Note: This code is written to produce nice results (i.e.
828     // corresponding to surface Rust) for types that can occur in
829     // actual Rust. It will have weird results if the predicates
830     // aren't as expected (i.e. self types = $0, projection
831     // predicates for a certain trait come after the Implemented
832     // predicate for that trait).
833     let mut first = true;
834     let mut angle_open = false;
835     let mut is_fn_trait = false;
836     let mut is_sized = false;
837     for p in predicates.iter() {
838         match p.skip_binders() {
839             WhereClause::Implemented(trait_ref) => {
840                 let trait_ = trait_ref.hir_trait_id();
841                 if default_sized.is_sized_trait(trait_, f.db.upcast()) {
842                     is_sized = true;
843                     if matches!(default_sized, SizedByDefault::Sized { .. }) {
844                         // Don't print +Sized, but rather +?Sized if absent.
845                         continue;
846                     }
847                 }
848                 if !is_fn_trait {
849                     is_fn_trait = fn_traits(f.db.upcast(), trait_).any(|it| it == trait_);
850                 }
851                 if !is_fn_trait && angle_open {
852                     write!(f, ">")?;
853                     angle_open = false;
854                 }
855                 if !first {
856                     write!(f, " + ")?;
857                 }
858                 // We assume that the self type is ^0.0 (i.e. the
859                 // existential) here, which is the only thing that's
860                 // possible in actual Rust, and hence don't print it
861                 write!(f, "{}", f.db.trait_data(trait_).name)?;
862                 if let [_, params @ ..] = &*trait_ref.substitution.as_slice(Interner) {
863                     if is_fn_trait {
864                         if let Some(args) =
865                             params.first().and_then(|it| it.assert_ty_ref(Interner).as_tuple())
866                         {
867                             write!(f, "(")?;
868                             f.write_joined(args.as_slice(Interner), ", ")?;
869                             write!(f, ")")?;
870                         }
871                     } else if !params.is_empty() {
872                         write!(f, "<")?;
873                         f.write_joined(params, ", ")?;
874                         // there might be assoc type bindings, so we leave the angle brackets open
875                         angle_open = true;
876                     }
877                 }
878             }
879             WhereClause::AliasEq(alias_eq) if is_fn_trait => {
880                 is_fn_trait = false;
881                 if !alias_eq.ty.is_unit() {
882                     write!(f, " -> ")?;
883                     alias_eq.ty.hir_fmt(f)?;
884                 }
885             }
886             WhereClause::AliasEq(AliasEq { ty, alias }) => {
887                 // in types in actual Rust, these will always come
888                 // after the corresponding Implemented predicate
889                 if angle_open {
890                     write!(f, ", ")?;
891                 } else {
892                     write!(f, "<")?;
893                     angle_open = true;
894                 }
895                 if let AliasTy::Projection(proj) = alias {
896                     let type_alias =
897                         f.db.type_alias_data(from_assoc_type_id(proj.associated_ty_id));
898                     write!(f, "{} = ", type_alias.name)?;
899                 }
900                 ty.hir_fmt(f)?;
901             }
902
903             // FIXME implement these
904             WhereClause::LifetimeOutlives(_) => {}
905             WhereClause::TypeOutlives(_) => {}
906         }
907         first = false;
908     }
909     if angle_open {
910         write!(f, ">")?;
911     }
912     if matches!(default_sized, SizedByDefault::Sized { .. }) {
913         if !is_sized {
914             write!(f, "{}?Sized", if first { "" } else { " + " })?;
915         } else if first {
916             write!(f, "Sized")?;
917         }
918     }
919     Ok(())
920 }
921
922 fn fmt_trait_ref(tr: &TraitRef, f: &mut HirFormatter, use_as: bool) -> Result<(), HirDisplayError> {
923     if f.should_truncate() {
924         return write!(f, "{}", TYPE_HINT_TRUNCATION);
925     }
926
927     tr.self_type_parameter(Interner).hir_fmt(f)?;
928     if use_as {
929         write!(f, " as ")?;
930     } else {
931         write!(f, ": ")?;
932     }
933     write!(f, "{}", f.db.trait_data(tr.hir_trait_id()).name)?;
934     if tr.substitution.len(Interner) > 1 {
935         write!(f, "<")?;
936         f.write_joined(&tr.substitution.as_slice(Interner)[1..], ", ")?;
937         write!(f, ">")?;
938     }
939     Ok(())
940 }
941
942 impl HirDisplay for TraitRef {
943     fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
944         fmt_trait_ref(self, f, false)
945     }
946 }
947
948 impl HirDisplay for WhereClause {
949     fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
950         if f.should_truncate() {
951             return write!(f, "{}", TYPE_HINT_TRUNCATION);
952         }
953
954         match self {
955             WhereClause::Implemented(trait_ref) => trait_ref.hir_fmt(f)?,
956             WhereClause::AliasEq(AliasEq { alias: AliasTy::Projection(projection_ty), ty }) => {
957                 write!(f, "<")?;
958                 fmt_trait_ref(&projection_ty.trait_ref(f.db), f, true)?;
959                 write!(
960                     f,
961                     ">::{} = ",
962                     f.db.type_alias_data(from_assoc_type_id(projection_ty.associated_ty_id)).name,
963                 )?;
964                 ty.hir_fmt(f)?;
965             }
966             WhereClause::AliasEq(_) => write!(f, "{{error}}")?,
967
968             // FIXME implement these
969             WhereClause::TypeOutlives(..) => {}
970             WhereClause::LifetimeOutlives(..) => {}
971         }
972         Ok(())
973     }
974 }
975
976 impl HirDisplay for LifetimeOutlives {
977     fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
978         self.a.hir_fmt(f)?;
979         write!(f, ": ")?;
980         self.b.hir_fmt(f)
981     }
982 }
983
984 impl HirDisplay for Lifetime {
985     fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
986         self.interned().hir_fmt(f)
987     }
988 }
989
990 impl HirDisplay for LifetimeData {
991     fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
992         match self {
993             LifetimeData::BoundVar(idx) => idx.hir_fmt(f),
994             LifetimeData::InferenceVar(_) => write!(f, "_"),
995             LifetimeData::Placeholder(idx) => {
996                 let id = lt_from_placeholder_idx(f.db, *idx);
997                 let generics = generics(f.db.upcast(), id.parent);
998                 let param_data = &generics.params.lifetimes[id.local_id];
999                 write!(f, "{}", param_data.name)
1000             }
1001             LifetimeData::Static => write!(f, "'static"),
1002             LifetimeData::Empty(_) => Ok(()),
1003             LifetimeData::Erased => Ok(()),
1004             LifetimeData::Phantom(_, _) => Ok(()),
1005         }
1006     }
1007 }
1008
1009 impl HirDisplay for DomainGoal {
1010     fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1011         match self {
1012             DomainGoal::Holds(wc) => {
1013                 write!(f, "Holds(")?;
1014                 wc.hir_fmt(f)?;
1015                 write!(f, ")")?;
1016             }
1017             _ => write!(f, "?")?,
1018         }
1019         Ok(())
1020     }
1021 }
1022
1023 pub fn write_visibility(
1024     module_id: ModuleId,
1025     vis: Visibility,
1026     f: &mut HirFormatter,
1027 ) -> Result<(), HirDisplayError> {
1028     match vis {
1029         Visibility::Public => write!(f, "pub "),
1030         Visibility::Module(vis_id) => {
1031             let def_map = module_id.def_map(f.db.upcast());
1032             let root_module_id = def_map.module_id(def_map.root());
1033             if vis_id == module_id {
1034                 // pub(self) or omitted
1035                 Ok(())
1036             } else if root_module_id == vis_id {
1037                 write!(f, "pub(crate) ")
1038             } else if module_id.containing_module(f.db.upcast()) == Some(vis_id) {
1039                 write!(f, "pub(super) ")
1040             } else {
1041                 write!(f, "pub(in ...) ")
1042             }
1043         }
1044     }
1045 }
1046
1047 impl HirDisplay for TypeRef {
1048     fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1049         match self {
1050             TypeRef::Never => write!(f, "!")?,
1051             TypeRef::Placeholder => write!(f, "_")?,
1052             TypeRef::Tuple(elems) => {
1053                 write!(f, "(")?;
1054                 f.write_joined(elems, ", ")?;
1055                 if elems.len() == 1 {
1056                     write!(f, ",")?;
1057                 }
1058                 write!(f, ")")?;
1059             }
1060             TypeRef::Path(path) => path.hir_fmt(f)?,
1061             TypeRef::RawPtr(inner, mutability) => {
1062                 let mutability = match mutability {
1063                     hir_def::type_ref::Mutability::Shared => "*const ",
1064                     hir_def::type_ref::Mutability::Mut => "*mut ",
1065                 };
1066                 write!(f, "{}", mutability)?;
1067                 inner.hir_fmt(f)?;
1068             }
1069             TypeRef::Reference(inner, lifetime, mutability) => {
1070                 let mutability = match mutability {
1071                     hir_def::type_ref::Mutability::Shared => "",
1072                     hir_def::type_ref::Mutability::Mut => "mut ",
1073                 };
1074                 write!(f, "&")?;
1075                 if let Some(lifetime) = lifetime {
1076                     write!(f, "{} ", lifetime.name)?;
1077                 }
1078                 write!(f, "{}", mutability)?;
1079                 inner.hir_fmt(f)?;
1080             }
1081             TypeRef::Array(inner, len) => {
1082                 write!(f, "[")?;
1083                 inner.hir_fmt(f)?;
1084                 write!(f, "; {}]", len)?;
1085             }
1086             TypeRef::Slice(inner) => {
1087                 write!(f, "[")?;
1088                 inner.hir_fmt(f)?;
1089                 write!(f, "]")?;
1090             }
1091             TypeRef::Fn(tys, is_varargs) => {
1092                 // FIXME: Function pointer qualifiers.
1093                 write!(f, "fn(")?;
1094                 f.write_joined(&tys[..tys.len() - 1], ", ")?;
1095                 if *is_varargs {
1096                     write!(f, "{}...", if tys.len() == 1 { "" } else { ", " })?;
1097                 }
1098                 write!(f, ")")?;
1099                 let ret_ty = tys.last().unwrap();
1100                 match ret_ty {
1101                     TypeRef::Tuple(tup) if tup.is_empty() => {}
1102                     _ => {
1103                         write!(f, " -> ")?;
1104                         ret_ty.hir_fmt(f)?;
1105                     }
1106                 }
1107             }
1108             TypeRef::ImplTrait(bounds) => {
1109                 write!(f, "impl ")?;
1110                 f.write_joined(bounds, " + ")?;
1111             }
1112             TypeRef::DynTrait(bounds) => {
1113                 write!(f, "dyn ")?;
1114                 f.write_joined(bounds, " + ")?;
1115             }
1116             TypeRef::Macro(macro_call) => {
1117                 let macro_call = macro_call.to_node(f.db.upcast());
1118                 let ctx = body::LowerCtx::with_hygiene(f.db.upcast(), &Hygiene::new_unhygienic());
1119                 match macro_call.path() {
1120                     Some(path) => match Path::from_src(path, &ctx) {
1121                         Some(path) => path.hir_fmt(f)?,
1122                         None => write!(f, "{{macro}}")?,
1123                     },
1124                     None => write!(f, "{{macro}}")?,
1125                 }
1126                 write!(f, "!(..)")?;
1127             }
1128             TypeRef::Error => write!(f, "{{error}}")?,
1129         }
1130         Ok(())
1131     }
1132 }
1133
1134 impl HirDisplay for TypeBound {
1135     fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1136         match self {
1137             TypeBound::Path(path, modifier) => {
1138                 match modifier {
1139                     TraitBoundModifier::None => (),
1140                     TraitBoundModifier::Maybe => write!(f, "?")?,
1141                 }
1142                 path.hir_fmt(f)
1143             }
1144             TypeBound::Lifetime(lifetime) => write!(f, "{}", lifetime.name),
1145             TypeBound::ForLifetime(lifetimes, path) => {
1146                 write!(f, "for<{}> ", lifetimes.iter().format(", "))?;
1147                 path.hir_fmt(f)
1148             }
1149             TypeBound::Error => write!(f, "{{error}}"),
1150         }
1151     }
1152 }
1153
1154 impl HirDisplay for Path {
1155     fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1156         match (self.type_anchor(), self.kind()) {
1157             (Some(anchor), _) => {
1158                 write!(f, "<")?;
1159                 anchor.hir_fmt(f)?;
1160                 write!(f, ">")?;
1161             }
1162             (_, PathKind::Plain) => {}
1163             (_, PathKind::Abs) => {}
1164             (_, PathKind::Crate) => write!(f, "crate")?,
1165             (_, PathKind::Super(0)) => write!(f, "self")?,
1166             (_, PathKind::Super(n)) => {
1167                 for i in 0..*n {
1168                     if i > 0 {
1169                         write!(f, "::")?;
1170                     }
1171                     write!(f, "super")?;
1172                 }
1173             }
1174             (_, PathKind::DollarCrate(_)) => write!(f, "{{extern_crate}}")?,
1175         }
1176
1177         for (seg_idx, segment) in self.segments().iter().enumerate() {
1178             if !matches!(self.kind(), PathKind::Plain) || seg_idx > 0 {
1179                 write!(f, "::")?;
1180             }
1181             write!(f, "{}", segment.name)?;
1182             if let Some(generic_args) = segment.args_and_bindings {
1183                 // We should be in type context, so format as `Foo<Bar>` instead of `Foo::<Bar>`.
1184                 // Do we actually format expressions?
1185                 if generic_args.desugared_from_fn {
1186                     // First argument will be a tuple, which already includes the parentheses.
1187                     // If the tuple only contains 1 item, write it manually to avoid the trailing `,`.
1188                     if let hir_def::path::GenericArg::Type(TypeRef::Tuple(v)) =
1189                         &generic_args.args[0]
1190                     {
1191                         if v.len() == 1 {
1192                             write!(f, "(")?;
1193                             v[0].hir_fmt(f)?;
1194                             write!(f, ")")?;
1195                         } else {
1196                             generic_args.args[0].hir_fmt(f)?;
1197                         }
1198                     }
1199                     if let Some(ret) = &generic_args.bindings[0].type_ref {
1200                         if !matches!(ret, TypeRef::Tuple(v) if v.is_empty()) {
1201                             write!(f, " -> ")?;
1202                             ret.hir_fmt(f)?;
1203                         }
1204                     }
1205                     return Ok(());
1206                 }
1207
1208                 write!(f, "<")?;
1209                 let mut first = true;
1210                 for arg in &generic_args.args {
1211                     if first {
1212                         first = false;
1213                         if generic_args.has_self_type {
1214                             // FIXME: Convert to `<Ty as Trait>` form.
1215                             write!(f, "Self = ")?;
1216                         }
1217                     } else {
1218                         write!(f, ", ")?;
1219                     }
1220                     arg.hir_fmt(f)?;
1221                 }
1222                 for binding in &generic_args.bindings {
1223                     if first {
1224                         first = false;
1225                     } else {
1226                         write!(f, ", ")?;
1227                     }
1228                     write!(f, "{}", binding.name)?;
1229                     match &binding.type_ref {
1230                         Some(ty) => {
1231                             write!(f, " = ")?;
1232                             ty.hir_fmt(f)?
1233                         }
1234                         None => {
1235                             write!(f, ": ")?;
1236                             f.write_joined(&binding.bounds, " + ")?;
1237                         }
1238                     }
1239                 }
1240                 write!(f, ">")?;
1241             }
1242         }
1243         Ok(())
1244     }
1245 }
1246
1247 impl HirDisplay for hir_def::path::GenericArg {
1248     fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1249         match self {
1250             hir_def::path::GenericArg::Type(ty) => ty.hir_fmt(f),
1251             hir_def::path::GenericArg::Lifetime(lifetime) => write!(f, "{}", lifetime.name),
1252         }
1253     }
1254 }