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