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