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