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