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