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