]> git.lizzy.rs Git - rust.git/blob - crates/hir_ty/src/display.rs
Merge #9535
[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: ref parameters,
387                     }))
388                     | &TyKind::OpaqueType(opaque_ty_id, ref parameters) => {
389                         let impl_trait_id = f.db.lookup_intern_impl_trait_id(opaque_ty_id.into());
390                         if let ImplTraitId::ReturnTypeImplTrait(func, idx) = impl_trait_id {
391                             datas =
392                                 f.db.return_type_impl_traits(func)
393                                     .expect("impl trait id without data");
394                             let data = (*datas)
395                                 .as_ref()
396                                 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
397                             let bounds = data.substitute(&Interner, parameters);
398                             bounds.into_value_and_skipped_binders().0
399                         } else {
400                             Vec::new()
401                         }
402                     }
403                     _ => Vec::new(),
404                 };
405
406                 if let Some(WhereClause::Implemented(trait_ref)) =
407                     predicates.get(0).map(|b| b.skip_binders())
408                 {
409                     let trait_ = trait_ref.hir_trait_id();
410                     if fn_traits(f.db.upcast(), trait_).any(|it| it == trait_)
411                         && predicates.len() <= 2
412                     {
413                         return t.hir_fmt(f);
414                     }
415                 }
416
417                 if predicates.len() > 1 {
418                     write!(f, "(")?;
419                     t.hir_fmt(f)?;
420                     write!(f, ")")?;
421                 } else {
422                     t.hir_fmt(f)?;
423                 }
424             }
425             TyKind::Tuple(_, substs) => {
426                 if substs.len(&Interner) == 1 {
427                     write!(f, "(")?;
428                     substs.at(&Interner, 0).hir_fmt(f)?;
429                     write!(f, ",)")?;
430                 } else {
431                     write!(f, "(")?;
432                     f.write_joined(&*substs.as_slice(&Interner), ", ")?;
433                     write!(f, ")")?;
434                 }
435             }
436             TyKind::Function(fn_ptr) => {
437                 let sig = CallableSig::from_fn_ptr(fn_ptr);
438                 sig.hir_fmt(f)?;
439             }
440             TyKind::FnDef(def, parameters) => {
441                 let def = from_chalk(f.db, *def);
442                 let sig = f.db.callable_item_signature(def).substitute(&Interner, parameters);
443                 match def {
444                     CallableDefId::FunctionId(ff) => {
445                         write!(f, "fn {}", f.db.function_data(ff).name)?
446                     }
447                     CallableDefId::StructId(s) => write!(f, "{}", f.db.struct_data(s).name)?,
448                     CallableDefId::EnumVariantId(e) => {
449                         write!(f, "{}", f.db.enum_data(e.parent).variants[e.local_id].name)?
450                     }
451                 };
452                 if parameters.len(&Interner) > 0 {
453                     let generics = generics(f.db.upcast(), def.into());
454                     let (parent_params, self_param, type_params, _impl_trait_params) =
455                         generics.provenance_split();
456                     let total_len = parent_params + self_param + type_params;
457                     // We print all params except implicit impl Trait params. Still a bit weird; should we leave out parent and self?
458                     if total_len > 0 {
459                         write!(f, "<")?;
460                         f.write_joined(&parameters.as_slice(&Interner)[..total_len], ", ")?;
461                         write!(f, ">")?;
462                     }
463                 }
464                 write!(f, "(")?;
465                 f.write_joined(sig.params(), ", ")?;
466                 write!(f, ")")?;
467                 let ret = sig.ret();
468                 if !ret.is_unit() {
469                     write!(f, " -> ")?;
470                     ret.hir_fmt(f)?;
471                 }
472             }
473             TyKind::Adt(AdtId(def_id), parameters) => {
474                 match f.display_target {
475                     DisplayTarget::Diagnostics | DisplayTarget::Test => {
476                         let name = match *def_id {
477                             hir_def::AdtId::StructId(it) => f.db.struct_data(it).name.clone(),
478                             hir_def::AdtId::UnionId(it) => f.db.union_data(it).name.clone(),
479                             hir_def::AdtId::EnumId(it) => f.db.enum_data(it).name.clone(),
480                         };
481                         write!(f, "{}", name)?;
482                     }
483                     DisplayTarget::SourceCode { module_id } => {
484                         if let Some(path) = find_path::find_path(
485                             f.db.upcast(),
486                             ItemInNs::Types((*def_id).into()),
487                             module_id,
488                         ) {
489                             write!(f, "{}", path)?;
490                         } else {
491                             return Err(HirDisplayError::DisplaySourceCodeError(
492                                 DisplaySourceCodeError::PathNotFound,
493                             ));
494                         }
495                     }
496                 }
497
498                 if parameters.len(&Interner) > 0 {
499                     let parameters_to_write = if f.display_target.is_source_code()
500                         || f.omit_verbose_types()
501                     {
502                         match self
503                             .as_generic_def(f.db)
504                             .map(|generic_def_id| f.db.generic_defaults(generic_def_id))
505                             .filter(|defaults| !defaults.is_empty())
506                         {
507                             None => parameters.as_slice(&Interner),
508                             Some(default_parameters) => {
509                                 let mut default_from = 0;
510                                 for (i, parameter) in parameters.iter(&Interner).enumerate() {
511                                     match (
512                                         parameter.assert_ty_ref(&Interner).kind(&Interner),
513                                         default_parameters.get(i),
514                                     ) {
515                                         (&TyKind::Error, _) | (_, None) => {
516                                             default_from = i + 1;
517                                         }
518                                         (_, Some(default_parameter)) => {
519                                             let actual_default =
520                                                 default_parameter.clone().substitute(
521                                                     &Interner,
522                                                     &subst_prefix(parameters, i),
523                                                 );
524                                             if parameter.assert_ty_ref(&Interner) != &actual_default
525                                             {
526                                                 default_from = i + 1;
527                                             }
528                                         }
529                                     }
530                                 }
531                                 &parameters.as_slice(&Interner)[0..default_from]
532                             }
533                         }
534                     } else {
535                         parameters.as_slice(&Interner)
536                     };
537                     if !parameters_to_write.is_empty() {
538                         write!(f, "<")?;
539                         f.write_joined(parameters_to_write, ", ")?;
540                         write!(f, ">")?;
541                     }
542                 }
543             }
544             TyKind::AssociatedType(assoc_type_id, parameters) => {
545                 let type_alias = from_assoc_type_id(*assoc_type_id);
546                 let trait_ = match type_alias.lookup(f.db.upcast()).container {
547                     AssocContainerId::TraitId(it) => it,
548                     _ => panic!("not an associated type"),
549                 };
550                 let trait_ = f.db.trait_data(trait_);
551                 let type_alias_data = f.db.type_alias_data(type_alias);
552
553                 // Use placeholder associated types when the target is test (https://rust-lang.github.io/chalk/book/clauses/type_equality.html#placeholder-associated-types)
554                 if f.display_target.is_test() {
555                     write!(f, "{}::{}", trait_.name, type_alias_data.name)?;
556                     if parameters.len(&Interner) > 0 {
557                         write!(f, "<")?;
558                         f.write_joined(&*parameters.as_slice(&Interner), ", ")?;
559                         write!(f, ">")?;
560                     }
561                 } else {
562                     let projection_ty = ProjectionTy {
563                         associated_ty_id: to_assoc_type_id(type_alias),
564                         substitution: parameters.clone(),
565                     };
566
567                     projection_ty.hir_fmt(f)?;
568                 }
569             }
570             TyKind::Foreign(type_alias) => {
571                 let type_alias = f.db.type_alias_data(from_foreign_def_id(*type_alias));
572                 write!(f, "{}", type_alias.name)?;
573             }
574             TyKind::OpaqueType(opaque_ty_id, parameters) => {
575                 let impl_trait_id = f.db.lookup_intern_impl_trait_id((*opaque_ty_id).into());
576                 match impl_trait_id {
577                     ImplTraitId::ReturnTypeImplTrait(func, idx) => {
578                         let datas =
579                             f.db.return_type_impl_traits(func).expect("impl trait id without data");
580                         let data = (*datas)
581                             .as_ref()
582                             .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
583                         let bounds = data.substitute(&Interner, &parameters);
584                         write_bounds_like_dyn_trait_with_prefix("impl", bounds.skip_binders(), f)?;
585                         // FIXME: it would maybe be good to distinguish this from the alias type (when debug printing), and to show the substitution
586                     }
587                     ImplTraitId::AsyncBlockTypeImplTrait(..) => {
588                         write!(f, "impl Future<Output = ")?;
589                         parameters.at(&Interner, 0).hir_fmt(f)?;
590                         write!(f, ">")?;
591                     }
592                 }
593             }
594             TyKind::Closure(.., substs) => {
595                 if f.display_target.is_source_code() {
596                     return Err(HirDisplayError::DisplaySourceCodeError(
597                         DisplaySourceCodeError::Closure,
598                     ));
599                 }
600                 let sig = substs.at(&Interner, 0).assert_ty_ref(&Interner).callable_sig(f.db);
601                 if let Some(sig) = sig {
602                     if sig.params().is_empty() {
603                         write!(f, "||")?;
604                     } else if f.omit_verbose_types() {
605                         write!(f, "|{}|", TYPE_HINT_TRUNCATION)?;
606                     } else {
607                         write!(f, "|")?;
608                         f.write_joined(sig.params(), ", ")?;
609                         write!(f, "|")?;
610                     };
611
612                     write!(f, " -> ")?;
613                     sig.ret().hir_fmt(f)?;
614                 } else {
615                     write!(f, "{{closure}}")?;
616                 }
617             }
618             TyKind::Placeholder(idx) => {
619                 let id = from_placeholder_idx(f.db, *idx);
620                 let generics = generics(f.db.upcast(), id.parent);
621                 let param_data = &generics.params.types[id.local_id];
622                 match param_data.provenance {
623                     TypeParamProvenance::TypeParamList | TypeParamProvenance::TraitSelf => {
624                         write!(f, "{}", param_data.name.clone().unwrap_or_else(Name::missing))?
625                     }
626                     TypeParamProvenance::ArgumentImplTrait => {
627                         let substs = generics.type_params_subst(f.db);
628                         let bounds =
629                             f.db.generic_predicates(id.parent)
630                                 .into_iter()
631                                 .map(|pred| pred.clone().substitute(&Interner, &substs))
632                                 .filter(|wc| match &wc.skip_binders() {
633                                     WhereClause::Implemented(tr) => {
634                                         &tr.self_type_parameter(&Interner) == self
635                                     }
636                                     WhereClause::AliasEq(AliasEq {
637                                         alias: AliasTy::Projection(proj),
638                                         ty: _,
639                                     }) => &proj.self_type_parameter(&Interner) == self,
640                                     _ => false,
641                                 })
642                                 .collect::<Vec<_>>();
643                         write_bounds_like_dyn_trait_with_prefix("impl", &bounds, f)?;
644                     }
645                 }
646             }
647             TyKind::BoundVar(idx) => idx.hir_fmt(f)?,
648             TyKind::Dyn(dyn_ty) => {
649                 write_bounds_like_dyn_trait_with_prefix(
650                     "dyn",
651                     dyn_ty.bounds.skip_binders().interned(),
652                     f,
653                 )?;
654             }
655             TyKind::Alias(AliasTy::Projection(p_ty)) => p_ty.hir_fmt(f)?,
656             TyKind::Alias(AliasTy::Opaque(opaque_ty)) => {
657                 let impl_trait_id = f.db.lookup_intern_impl_trait_id(opaque_ty.opaque_ty_id.into());
658                 match impl_trait_id {
659                     ImplTraitId::ReturnTypeImplTrait(func, idx) => {
660                         let datas =
661                             f.db.return_type_impl_traits(func).expect("impl trait id without data");
662                         let data = (*datas)
663                             .as_ref()
664                             .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
665                         let bounds = data.substitute(&Interner, &opaque_ty.substitution);
666                         write_bounds_like_dyn_trait_with_prefix("impl", bounds.skip_binders(), f)?;
667                     }
668                     ImplTraitId::AsyncBlockTypeImplTrait(..) => {
669                         write!(f, "{{async block}}")?;
670                     }
671                 };
672             }
673             TyKind::Error => {
674                 if f.display_target.is_source_code() {
675                     return Err(HirDisplayError::DisplaySourceCodeError(
676                         DisplaySourceCodeError::UnknownType,
677                     ));
678                 }
679                 write!(f, "{{unknown}}")?;
680             }
681             TyKind::InferenceVar(..) => write!(f, "_")?,
682             TyKind::Generator(..) => write!(f, "{{generator}}")?,
683             TyKind::GeneratorWitness(..) => write!(f, "{{generator witness}}")?,
684         }
685         Ok(())
686     }
687 }
688
689 impl HirDisplay for CallableSig {
690     fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
691         write!(f, "fn(")?;
692         f.write_joined(self.params(), ", ")?;
693         if self.is_varargs {
694             if self.params().is_empty() {
695                 write!(f, "...")?;
696             } else {
697                 write!(f, ", ...")?;
698             }
699         }
700         write!(f, ")")?;
701         let ret = self.ret();
702         if !ret.is_unit() {
703             write!(f, " -> ")?;
704             ret.hir_fmt(f)?;
705         }
706         Ok(())
707     }
708 }
709
710 fn fn_traits(db: &dyn DefDatabase, trait_: TraitId) -> impl Iterator<Item = TraitId> {
711     let krate = trait_.lookup(db).container.krate();
712     utils::fn_traits(db, krate)
713 }
714
715 pub fn write_bounds_like_dyn_trait_with_prefix(
716     prefix: &str,
717     predicates: &[QuantifiedWhereClause],
718     f: &mut HirFormatter,
719 ) -> Result<(), HirDisplayError> {
720     write!(f, "{}", prefix)?;
721     if !predicates.is_empty() {
722         write!(f, " ")?;
723         write_bounds_like_dyn_trait(predicates, f)
724     } else {
725         Ok(())
726     }
727 }
728
729 fn write_bounds_like_dyn_trait(
730     predicates: &[QuantifiedWhereClause],
731     f: &mut HirFormatter,
732 ) -> Result<(), HirDisplayError> {
733     // Note: This code is written to produce nice results (i.e.
734     // corresponding to surface Rust) for types that can occur in
735     // actual Rust. It will have weird results if the predicates
736     // aren't as expected (i.e. self types = $0, projection
737     // predicates for a certain trait come after the Implemented
738     // predicate for that trait).
739     let mut first = true;
740     let mut angle_open = false;
741     let mut is_fn_trait = false;
742     for p in predicates.iter() {
743         match p.skip_binders() {
744             WhereClause::Implemented(trait_ref) => {
745                 let trait_ = trait_ref.hir_trait_id();
746                 if !is_fn_trait {
747                     is_fn_trait = fn_traits(f.db.upcast(), trait_).any(|it| it == trait_);
748                 }
749                 if !is_fn_trait && angle_open {
750                     write!(f, ">")?;
751                     angle_open = false;
752                 }
753                 if !first {
754                     write!(f, " + ")?;
755                 }
756                 // We assume that the self type is ^0.0 (i.e. the
757                 // existential) here, which is the only thing that's
758                 // possible in actual Rust, and hence don't print it
759                 write!(f, "{}", f.db.trait_data(trait_).name)?;
760                 if let [_, params @ ..] = &*trait_ref.substitution.as_slice(&Interner) {
761                     if is_fn_trait {
762                         if let Some(args) =
763                             params.first().and_then(|it| it.assert_ty_ref(&Interner).as_tuple())
764                         {
765                             write!(f, "(")?;
766                             f.write_joined(args.as_slice(&Interner), ", ")?;
767                             write!(f, ")")?;
768                         }
769                     } else if !params.is_empty() {
770                         write!(f, "<")?;
771                         f.write_joined(params, ", ")?;
772                         // there might be assoc type bindings, so we leave the angle brackets open
773                         angle_open = true;
774                     }
775                 }
776             }
777             WhereClause::AliasEq(alias_eq) if is_fn_trait => {
778                 is_fn_trait = false;
779                 if !alias_eq.ty.is_unit() {
780                     write!(f, " -> ")?;
781                     alias_eq.ty.hir_fmt(f)?;
782                 }
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::ForLifetime(lifetimes, path) => {
1031                 write!(f, "for<{}> ", lifetimes.iter().format(", "))?;
1032                 path.hir_fmt(f)
1033             }
1034             TypeBound::Error => write!(f, "{{error}}"),
1035         }
1036     }
1037 }
1038
1039 impl HirDisplay for Path {
1040     fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1041         match (self.type_anchor(), self.kind()) {
1042             (Some(anchor), _) => {
1043                 write!(f, "<")?;
1044                 anchor.hir_fmt(f)?;
1045                 write!(f, ">")?;
1046             }
1047             (_, PathKind::Plain) => {}
1048             (_, PathKind::Abs) => write!(f, "::")?,
1049             (_, PathKind::Crate) => write!(f, "crate")?,
1050             (_, PathKind::Super(0)) => write!(f, "self")?,
1051             (_, PathKind::Super(n)) => {
1052                 write!(f, "super")?;
1053                 for _ in 0..*n {
1054                     write!(f, "::super")?;
1055                 }
1056             }
1057             (_, PathKind::DollarCrate(_)) => write!(f, "{{extern_crate}}")?,
1058         }
1059
1060         for (seg_idx, segment) in self.segments().iter().enumerate() {
1061             if seg_idx != 0 {
1062                 write!(f, "::")?;
1063             }
1064             write!(f, "{}", segment.name)?;
1065             if let Some(generic_args) = segment.args_and_bindings {
1066                 // We should be in type context, so format as `Foo<Bar>` instead of `Foo::<Bar>`.
1067                 // Do we actually format expressions?
1068                 write!(f, "<")?;
1069                 let mut first = true;
1070                 for arg in &generic_args.args {
1071                     if first {
1072                         first = false;
1073                         if generic_args.has_self_type {
1074                             // FIXME: Convert to `<Ty as Trait>` form.
1075                             write!(f, "Self = ")?;
1076                         }
1077                     } else {
1078                         write!(f, ", ")?;
1079                     }
1080                     arg.hir_fmt(f)?;
1081                 }
1082                 for binding in &generic_args.bindings {
1083                     if first {
1084                         first = false;
1085                     } else {
1086                         write!(f, ", ")?;
1087                     }
1088                     write!(f, "{}", binding.name)?;
1089                     match &binding.type_ref {
1090                         Some(ty) => {
1091                             write!(f, " = ")?;
1092                             ty.hir_fmt(f)?
1093                         }
1094                         None => {
1095                             write!(f, ": ")?;
1096                             f.write_joined(&binding.bounds, " + ")?;
1097                         }
1098                     }
1099                 }
1100                 write!(f, ">")?;
1101             }
1102         }
1103         Ok(())
1104     }
1105 }
1106
1107 impl HirDisplay for hir_def::path::GenericArg {
1108     fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1109         match self {
1110             hir_def::path::GenericArg::Type(ty) => ty.hir_fmt(f),
1111             hir_def::path::GenericArg::Lifetime(lifetime) => write!(f, "{}", lifetime.name),
1112         }
1113     }
1114 }