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