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
5 use std::fmt::{self, Debug};
7 use chalk_ir::BoundVar;
12 generics::TypeParamProvenance,
13 intern::{Internable, Interned},
15 path::{Path, PathKind},
16 type_ref::{TraitBoundModifier, TypeBound, TypeRef},
17 visibility::Visibility,
18 AssocContainerId, Lookup, ModuleId, TraitId,
20 use hir_expand::{hygiene::Hygiene, name::Name};
21 use itertools::Itertools;
24 const_from_placeholder_idx,
26 from_assoc_type_id, from_foreign_def_id, from_placeholder_idx, lt_from_placeholder_idx,
28 primitive, subst_prefix, to_assoc_type_id,
29 utils::{self, generics},
30 AdtId, AliasEq, AliasTy, CallableDefId, CallableSig, Const, ConstValue, DomainGoal, GenericArg,
31 ImplTraitId, Interner, Lifetime, LifetimeData, LifetimeOutlives, Mutability, OpaqueTy,
32 ProjectionTy, ProjectionTyExt, QuantifiedWhereClause, Scalar, TraitRef, TraitRefExt, Ty, TyExt,
36 pub struct HirFormatter<'a> {
37 pub db: &'a dyn HirDatabase,
38 fmt: &'a mut dyn fmt::Write,
41 pub(crate) max_size: Option<usize>,
42 omit_verbose_types: bool,
43 display_target: DisplayTarget,
46 pub trait HirDisplay {
47 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError>;
49 /// Returns a `Display`able type that is human-readable.
50 fn into_displayable<'a>(
52 db: &'a dyn HirDatabase,
53 max_size: Option<usize>,
54 omit_verbose_types: bool,
55 display_target: DisplayTarget,
56 ) -> HirDisplayWrapper<'a, Self>
61 !matches!(display_target, DisplayTarget::SourceCode { .. }),
62 "HirDisplayWrapper cannot fail with DisplaySourceCodeError, use HirDisplay::hir_fmt directly instead"
64 HirDisplayWrapper { db, t: self, max_size, omit_verbose_types, display_target }
67 /// Returns a `Display`able type that is human-readable.
68 /// Use this for showing types to the user (e.g. diagnostics)
69 fn display<'a>(&'a self, db: &'a dyn HirDatabase) -> HirDisplayWrapper<'a, Self>
77 omit_verbose_types: false,
78 display_target: DisplayTarget::Diagnostics,
82 /// Returns a `Display`able type that is human-readable and tries to be succinct.
83 /// Use this for showing types to the user where space is constrained (e.g. doc popups)
84 fn display_truncated<'a>(
86 db: &'a dyn HirDatabase,
87 max_size: Option<usize>,
88 ) -> HirDisplayWrapper<'a, Self>
96 omit_verbose_types: true,
97 display_target: DisplayTarget::Diagnostics,
101 /// Returns a String representation of `self` that can be inserted into the given module.
102 /// Use this when generating code (e.g. assists)
103 fn display_source_code<'a>(
105 db: &'a dyn HirDatabase,
107 ) -> Result<String, DisplaySourceCodeError> {
108 let mut result = String::new();
109 match self.hir_fmt(&mut HirFormatter {
112 buf: String::with_capacity(20),
115 omit_verbose_types: false,
116 display_target: DisplayTarget::SourceCode { module_id },
119 Err(HirDisplayError::FmtError) => panic!("Writing to String can't fail!"),
120 Err(HirDisplayError::DisplaySourceCodeError(e)) => return Err(e),
125 /// Returns a String representation of `self` for test purposes
126 fn display_test<'a>(&'a self, db: &'a dyn HirDatabase) -> HirDisplayWrapper<'a, Self>
134 omit_verbose_types: false,
135 display_target: DisplayTarget::Test,
140 impl<'a> HirFormatter<'a> {
141 pub fn write_joined<T: HirDisplay>(
143 iter: impl IntoIterator<Item = T>,
145 ) -> Result<(), HirDisplayError> {
146 let mut first = true;
149 write!(self, "{}", sep)?;
157 /// This allows using the `write!` macro directly with a `HirFormatter`.
158 pub fn write_fmt(&mut self, args: fmt::Arguments) -> Result<(), HirDisplayError> {
159 // We write to a buffer first to track output size
161 fmt::write(&mut self.buf, args)?;
162 self.curr_size += self.buf.len();
164 // Then we write to the internal formatter from the buffer
165 self.fmt.write_str(&self.buf).map_err(HirDisplayError::from)
168 pub fn should_truncate(&self) -> bool {
169 if let Some(max_size) = self.max_size {
170 self.curr_size >= max_size
176 pub fn omit_verbose_types(&self) -> bool {
177 self.omit_verbose_types
181 #[derive(Clone, Copy)]
182 pub enum DisplayTarget {
183 /// Display types for inlays, doc popups, autocompletion, etc...
184 /// Showing `{unknown}` or not qualifying paths is fine here.
185 /// There's no reason for this to fail.
187 /// Display types for inserting them in source files.
188 /// The generated code should compile, so paths need to be qualified.
189 SourceCode { module_id: ModuleId },
190 /// Only for test purpose to keep real types
195 fn is_source_code(&self) -> bool {
196 matches!(self, Self::SourceCode { .. })
198 fn is_test(&self) -> bool {
199 matches!(self, Self::Test)
204 pub enum DisplaySourceCodeError {
210 pub enum HirDisplayError {
211 /// Errors that can occur when generating source code
212 DisplaySourceCodeError(DisplaySourceCodeError),
213 /// `FmtError` is required to be compatible with std::fmt::Display
216 impl From<fmt::Error> for HirDisplayError {
217 fn from(_: fmt::Error) -> Self {
222 pub struct HirDisplayWrapper<'a, T> {
223 db: &'a dyn HirDatabase,
225 max_size: Option<usize>,
226 omit_verbose_types: bool,
227 display_target: DisplayTarget,
230 impl<'a, T> fmt::Display for HirDisplayWrapper<'a, T>
234 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
235 match self.t.hir_fmt(&mut HirFormatter {
238 buf: String::with_capacity(20),
240 max_size: self.max_size,
241 omit_verbose_types: self.omit_verbose_types,
242 display_target: self.display_target,
245 Err(HirDisplayError::FmtError) => Err(fmt::Error),
246 Err(HirDisplayError::DisplaySourceCodeError(_)) => {
247 // This should never happen
248 panic!("HirDisplay::hir_fmt failed with DisplaySourceCodeError when calling Display::fmt!")
254 const TYPE_HINT_TRUNCATION: &str = "…";
256 impl<T: HirDisplay> HirDisplay for &'_ T {
257 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
258 HirDisplay::hir_fmt(*self, f)
262 impl<T: HirDisplay + Internable> HirDisplay for Interned<T> {
263 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
264 HirDisplay::hir_fmt(self.as_ref(), f)
268 impl HirDisplay for ProjectionTy {
269 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
270 if f.should_truncate() {
271 return write!(f, "{}", TYPE_HINT_TRUNCATION);
274 let trait_ = f.db.trait_data(self.trait_(f.db));
276 self.self_type_parameter(&Interner).hir_fmt(f)?;
277 write!(f, " as {}", trait_.name)?;
278 if self.substitution.len(&Interner) > 1 {
280 f.write_joined(&self.substitution.as_slice(&Interner)[1..], ", ")?;
283 write!(f, ">::{}", f.db.type_alias_data(from_assoc_type_id(self.associated_ty_id)).name)?;
288 impl HirDisplay for OpaqueTy {
289 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
290 if f.should_truncate() {
291 return write!(f, "{}", TYPE_HINT_TRUNCATION);
294 self.substitution.at(&Interner, 0).hir_fmt(f)
298 impl HirDisplay for GenericArg {
299 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
300 match self.interned() {
301 crate::GenericArgData::Ty(ty) => ty.hir_fmt(f),
302 crate::GenericArgData::Lifetime(lt) => lt.hir_fmt(f),
303 crate::GenericArgData::Const(c) => c.hir_fmt(f),
308 impl HirDisplay for Const {
309 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
310 let data = self.interned();
312 ConstValue::BoundVar(idx) => idx.hir_fmt(f),
313 ConstValue::InferenceVar(..) => write!(f, "_"),
314 ConstValue::Placeholder(idx) => {
315 let id = const_from_placeholder_idx(f.db, idx);
316 let generics = generics(f.db.upcast(), id.parent);
317 let param_data = &generics.params.consts[id.local_id];
318 write!(f, "{}", param_data.name)
320 ConstValue::Concrete(c) => write!(f, "{}", c.interned),
325 impl HirDisplay for BoundVar {
326 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
327 write!(f, "?{}.{}", self.debruijn.depth(), self.index)
331 impl HirDisplay for Ty {
332 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
333 if f.should_truncate() {
334 return write!(f, "{}", TYPE_HINT_TRUNCATION);
337 match self.kind(&Interner) {
338 TyKind::Never => write!(f, "!")?,
339 TyKind::Str => write!(f, "str")?,
340 TyKind::Scalar(Scalar::Bool) => write!(f, "bool")?,
341 TyKind::Scalar(Scalar::Char) => write!(f, "char")?,
342 &TyKind::Scalar(Scalar::Float(t)) => write!(f, "{}", primitive::float_ty_to_string(t))?,
343 &TyKind::Scalar(Scalar::Int(t)) => write!(f, "{}", primitive::int_ty_to_string(t))?,
344 &TyKind::Scalar(Scalar::Uint(t)) => write!(f, "{}", primitive::uint_ty_to_string(t))?,
345 TyKind::Slice(t) => {
350 TyKind::Array(t, c) => {
357 TyKind::Raw(m, t) | TyKind::Ref(m, _, t) => {
358 if matches!(self.kind(&Interner), TyKind::Raw(..)) {
363 Mutability::Not => "const ",
364 Mutability::Mut => "mut ",
372 Mutability::Not => "",
373 Mutability::Mut => "mut ",
378 // FIXME: all this just to decide whether to use parentheses...
380 let predicates: Vec<_> = match t.kind(&Interner) {
381 TyKind::Dyn(dyn_ty) if dyn_ty.bounds.skip_binders().interned().len() > 1 => {
382 dyn_ty.bounds.skip_binders().interned().iter().cloned().collect()
384 TyKind::Alias(AliasTy::Opaque(OpaqueTy {
386 substitution: parameters,
388 | TyKind::OpaqueType(opaque_ty_id, parameters) => {
390 f.db.lookup_intern_impl_trait_id((*opaque_ty_id).into());
391 if let ImplTraitId::ReturnTypeImplTrait(func, idx) = impl_trait_id {
393 f.db.return_type_impl_traits(func)
394 .expect("impl trait id without data");
397 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
398 let bounds = data.substitute(&Interner, parameters);
399 bounds.into_value_and_skipped_binders().0
407 if let Some(WhereClause::Implemented(trait_ref)) =
408 predicates.get(0).map(|b| b.skip_binders())
410 let trait_ = trait_ref.hir_trait_id();
411 if fn_traits(f.db.upcast(), trait_).any(|it| it == trait_)
412 && predicates.len() <= 2
418 if predicates.len() > 1 {
426 TyKind::Tuple(_, substs) => {
427 if substs.len(&Interner) == 1 {
429 substs.at(&Interner, 0).hir_fmt(f)?;
433 f.write_joined(&*substs.as_slice(&Interner), ", ")?;
437 TyKind::Function(fn_ptr) => {
438 let sig = CallableSig::from_fn_ptr(fn_ptr);
441 TyKind::FnDef(def, parameters) => {
442 let def = from_chalk(f.db, *def);
443 let sig = f.db.callable_item_signature(def).substitute(&Interner, parameters);
445 CallableDefId::FunctionId(ff) => {
446 write!(f, "fn {}", f.db.function_data(ff).name)?
448 CallableDefId::StructId(s) => write!(f, "{}", f.db.struct_data(s).name)?,
449 CallableDefId::EnumVariantId(e) => {
450 write!(f, "{}", f.db.enum_data(e.parent).variants[e.local_id].name)?
453 if parameters.len(&Interner) > 0 {
454 let generics = generics(f.db.upcast(), def.into());
455 let (parent_params, self_param, type_params, _impl_trait_params) =
456 generics.provenance_split();
457 let total_len = parent_params + self_param + type_params;
458 // We print all params except implicit impl Trait params. Still a bit weird; should we leave out parent and self?
461 f.write_joined(¶meters.as_slice(&Interner)[..total_len], ", ")?;
466 f.write_joined(sig.params(), ", ")?;
474 TyKind::Adt(AdtId(def_id), parameters) => {
475 match f.display_target {
476 DisplayTarget::Diagnostics | DisplayTarget::Test => {
477 let name = match *def_id {
478 hir_def::AdtId::StructId(it) => f.db.struct_data(it).name.clone(),
479 hir_def::AdtId::UnionId(it) => f.db.union_data(it).name.clone(),
480 hir_def::AdtId::EnumId(it) => f.db.enum_data(it).name.clone(),
482 write!(f, "{}", name)?;
484 DisplayTarget::SourceCode { module_id } => {
485 if let Some(path) = find_path::find_path(
487 ItemInNs::Types((*def_id).into()),
490 write!(f, "{}", path)?;
492 return Err(HirDisplayError::DisplaySourceCodeError(
493 DisplaySourceCodeError::PathNotFound,
499 if parameters.len(&Interner) > 0 {
500 let parameters_to_write = if f.display_target.is_source_code()
501 || f.omit_verbose_types()
504 .as_generic_def(f.db)
505 .map(|generic_def_id| f.db.generic_defaults(generic_def_id))
506 .filter(|defaults| !defaults.is_empty())
508 None => parameters.as_slice(&Interner),
509 Some(default_parameters) => {
510 let mut default_from = 0;
511 for (i, parameter) in parameters.iter(&Interner).enumerate() {
513 parameter.assert_ty_ref(&Interner).kind(&Interner),
514 default_parameters.get(i),
516 (&TyKind::Error, _) | (_, None) => {
517 default_from = i + 1;
519 (_, Some(default_parameter)) => {
521 default_parameter.clone().substitute(
523 &subst_prefix(parameters, i),
525 if parameter.assert_ty_ref(&Interner) != &actual_default
527 default_from = i + 1;
532 ¶meters.as_slice(&Interner)[0..default_from]
536 parameters.as_slice(&Interner)
538 if !parameters_to_write.is_empty() {
540 f.write_joined(parameters_to_write, ", ")?;
545 TyKind::AssociatedType(assoc_type_id, parameters) => {
546 let type_alias = from_assoc_type_id(*assoc_type_id);
547 let trait_ = match type_alias.lookup(f.db.upcast()).container {
548 AssocContainerId::TraitId(it) => it,
549 _ => panic!("not an associated type"),
551 let trait_ = f.db.trait_data(trait_);
552 let type_alias_data = f.db.type_alias_data(type_alias);
554 // Use placeholder associated types when the target is test (https://rust-lang.github.io/chalk/book/clauses/type_equality.html#placeholder-associated-types)
555 if f.display_target.is_test() {
556 write!(f, "{}::{}", trait_.name, type_alias_data.name)?;
557 if parameters.len(&Interner) > 0 {
559 f.write_joined(&*parameters.as_slice(&Interner), ", ")?;
563 let projection_ty = ProjectionTy {
564 associated_ty_id: to_assoc_type_id(type_alias),
565 substitution: parameters.clone(),
568 projection_ty.hir_fmt(f)?;
571 TyKind::Foreign(type_alias) => {
572 let type_alias = f.db.type_alias_data(from_foreign_def_id(*type_alias));
573 write!(f, "{}", type_alias.name)?;
575 TyKind::OpaqueType(opaque_ty_id, parameters) => {
576 let impl_trait_id = f.db.lookup_intern_impl_trait_id((*opaque_ty_id).into());
577 match impl_trait_id {
578 ImplTraitId::ReturnTypeImplTrait(func, idx) => {
580 f.db.return_type_impl_traits(func).expect("impl trait id without data");
583 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
584 let bounds = data.substitute(&Interner, ¶meters);
585 write_bounds_like_dyn_trait_with_prefix(
587 bounds.skip_binders(),
588 SizedByDefault::Sized,
591 // FIXME: it would maybe be good to distinguish this from the alias type (when debug printing), and to show the substitution
593 ImplTraitId::AsyncBlockTypeImplTrait(..) => {
594 write!(f, "impl Future<Output = ")?;
595 parameters.at(&Interner, 0).hir_fmt(f)?;
600 TyKind::Closure(.., substs) => {
601 if f.display_target.is_source_code() {
602 return Err(HirDisplayError::DisplaySourceCodeError(
603 DisplaySourceCodeError::Closure,
606 let sig = substs.at(&Interner, 0).assert_ty_ref(&Interner).callable_sig(f.db);
607 if let Some(sig) = sig {
608 if sig.params().is_empty() {
610 } else if f.omit_verbose_types() {
611 write!(f, "|{}|", TYPE_HINT_TRUNCATION)?;
614 f.write_joined(sig.params(), ", ")?;
619 sig.ret().hir_fmt(f)?;
621 write!(f, "{{closure}}")?;
624 TyKind::Placeholder(idx) => {
625 let id = from_placeholder_idx(f.db, *idx);
626 let generics = generics(f.db.upcast(), id.parent);
627 let param_data = &generics.params.types[id.local_id];
628 match param_data.provenance {
629 TypeParamProvenance::TypeParamList | TypeParamProvenance::TraitSelf => {
630 write!(f, "{}", param_data.name.clone().unwrap_or_else(Name::missing))?
632 TypeParamProvenance::ArgumentImplTrait => {
633 let substs = generics.type_params_subst(f.db);
635 f.db.generic_predicates(id.parent)
637 .map(|pred| pred.clone().substitute(&Interner, &substs))
638 .filter(|wc| match &wc.skip_binders() {
639 WhereClause::Implemented(tr) => {
640 &tr.self_type_parameter(&Interner) == self
642 WhereClause::AliasEq(AliasEq {
643 alias: AliasTy::Projection(proj),
645 }) => &proj.self_type_parameter(&Interner) == self,
648 .collect::<Vec<_>>();
649 write_bounds_like_dyn_trait_with_prefix(
652 SizedByDefault::Sized,
658 TyKind::BoundVar(idx) => idx.hir_fmt(f)?,
659 TyKind::Dyn(dyn_ty) => {
660 write_bounds_like_dyn_trait_with_prefix(
662 dyn_ty.bounds.skip_binders().interned(),
663 SizedByDefault::NotSized,
667 TyKind::Alias(AliasTy::Projection(p_ty)) => p_ty.hir_fmt(f)?,
668 TyKind::Alias(AliasTy::Opaque(opaque_ty)) => {
669 let impl_trait_id = f.db.lookup_intern_impl_trait_id(opaque_ty.opaque_ty_id.into());
670 match impl_trait_id {
671 ImplTraitId::ReturnTypeImplTrait(func, idx) => {
673 f.db.return_type_impl_traits(func).expect("impl trait id without data");
676 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
677 let bounds = data.substitute(&Interner, &opaque_ty.substitution);
678 write_bounds_like_dyn_trait_with_prefix(
680 bounds.skip_binders(),
681 SizedByDefault::Sized,
685 ImplTraitId::AsyncBlockTypeImplTrait(..) => {
686 write!(f, "{{async block}}")?;
691 if f.display_target.is_source_code() {
692 return Err(HirDisplayError::DisplaySourceCodeError(
693 DisplaySourceCodeError::UnknownType,
696 write!(f, "{{unknown}}")?;
698 TyKind::InferenceVar(..) => write!(f, "_")?,
699 TyKind::Generator(..) => write!(f, "{{generator}}")?,
700 TyKind::GeneratorWitness(..) => write!(f, "{{generator witness}}")?,
706 impl HirDisplay for CallableSig {
707 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
709 f.write_joined(self.params(), ", ")?;
711 if self.params().is_empty() {
718 let ret = self.ret();
727 fn fn_traits(db: &dyn DefDatabase, trait_: TraitId) -> impl Iterator<Item = TraitId> {
728 let krate = trait_.lookup(db).container.krate();
729 utils::fn_traits(db, krate)
732 fn is_sized_trait(db: &dyn DefDatabase, trait_: TraitId) -> Option<bool> {
733 let krate = trait_.lookup(db).container.krate();
735 db.lang_item(krate, "sized".into()).and_then(|lang_item| lang_item.as_trait())?;
736 Some(trait_ == sized_trait)
739 #[derive(Clone, Copy, PartialEq, Eq)]
740 pub enum SizedByDefault {
745 pub fn write_bounds_like_dyn_trait_with_prefix(
747 predicates: &[QuantifiedWhereClause],
748 default_sized: SizedByDefault,
749 f: &mut HirFormatter,
750 ) -> Result<(), HirDisplayError> {
751 write!(f, "{}", prefix)?;
752 if !predicates.is_empty() {
754 write_bounds_like_dyn_trait(predicates, default_sized, f)
760 fn write_bounds_like_dyn_trait(
761 predicates: &[QuantifiedWhereClause],
762 default_sized: SizedByDefault,
763 f: &mut HirFormatter,
764 ) -> Result<(), HirDisplayError> {
765 // Note: This code is written to produce nice results (i.e.
766 // corresponding to surface Rust) for types that can occur in
767 // actual Rust. It will have weird results if the predicates
768 // aren't as expected (i.e. self types = $0, projection
769 // predicates for a certain trait come after the Implemented
770 // predicate for that trait).
771 let mut first = true;
772 let mut angle_open = false;
773 let mut is_fn_trait = false;
774 let mut is_sized = None;
775 for p in predicates.iter() {
776 match p.skip_binders() {
777 WhereClause::Implemented(trait_ref) => {
778 let trait_ = trait_ref.hir_trait_id();
779 match is_sized_trait(f.db.upcast(), trait_) {
781 is_sized = Some(true);
782 if default_sized == SizedByDefault::Sized {
783 // Don't print +Sized, but rather +?Sized if absent.
787 Some(false) => is_sized = is_sized.or(Some(false)),
791 is_fn_trait = fn_traits(f.db.upcast(), trait_).any(|it| it == trait_);
793 if !is_fn_trait && angle_open {
800 // We assume that the self type is ^0.0 (i.e. the
801 // existential) here, which is the only thing that's
802 // possible in actual Rust, and hence don't print it
803 write!(f, "{}", f.db.trait_data(trait_).name)?;
804 if let [_, params @ ..] = &*trait_ref.substitution.as_slice(&Interner) {
807 params.first().and_then(|it| it.assert_ty_ref(&Interner).as_tuple())
810 f.write_joined(args.as_slice(&Interner), ", ")?;
813 } else if !params.is_empty() {
815 f.write_joined(params, ", ")?;
816 // there might be assoc type bindings, so we leave the angle brackets open
821 WhereClause::AliasEq(alias_eq) if is_fn_trait => {
823 if !alias_eq.ty.is_unit() {
825 alias_eq.ty.hir_fmt(f)?;
828 WhereClause::AliasEq(AliasEq { ty, alias }) => {
829 // in types in actual Rust, these will always come
830 // after the corresponding Implemented predicate
837 if let AliasTy::Projection(proj) = alias {
839 f.db.type_alias_data(from_assoc_type_id(proj.associated_ty_id));
840 write!(f, "{} = ", type_alias.name)?;
845 // FIXME implement these
846 WhereClause::LifetimeOutlives(_) => {}
847 WhereClause::TypeOutlives(_) => {}
854 if default_sized == SizedByDefault::Sized && is_sized.is_some() {
855 if is_sized == Some(false) {
856 write!(f, "{}?Sized", if first { "" } else { " + " })?;
864 fn fmt_trait_ref(tr: &TraitRef, f: &mut HirFormatter, use_as: bool) -> Result<(), HirDisplayError> {
865 if f.should_truncate() {
866 return write!(f, "{}", TYPE_HINT_TRUNCATION);
869 tr.self_type_parameter(&Interner).hir_fmt(f)?;
875 write!(f, "{}", f.db.trait_data(tr.hir_trait_id()).name)?;
876 if tr.substitution.len(&Interner) > 1 {
878 f.write_joined(&tr.substitution.as_slice(&Interner)[1..], ", ")?;
884 impl HirDisplay for TraitRef {
885 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
886 fmt_trait_ref(self, f, false)
890 impl HirDisplay for WhereClause {
891 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
892 if f.should_truncate() {
893 return write!(f, "{}", TYPE_HINT_TRUNCATION);
897 WhereClause::Implemented(trait_ref) => trait_ref.hir_fmt(f)?,
898 WhereClause::AliasEq(AliasEq { alias: AliasTy::Projection(projection_ty), ty }) => {
900 fmt_trait_ref(&projection_ty.trait_ref(f.db), f, true)?;
904 f.db.type_alias_data(from_assoc_type_id(projection_ty.associated_ty_id)).name,
908 WhereClause::AliasEq(_) => write!(f, "{{error}}")?,
910 // FIXME implement these
911 WhereClause::TypeOutlives(..) => {}
912 WhereClause::LifetimeOutlives(..) => {}
918 impl HirDisplay for LifetimeOutlives {
919 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
926 impl HirDisplay for Lifetime {
927 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
928 self.interned().hir_fmt(f)
932 impl HirDisplay for LifetimeData {
933 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
935 LifetimeData::BoundVar(idx) => idx.hir_fmt(f),
936 LifetimeData::InferenceVar(_) => write!(f, "_"),
937 LifetimeData::Placeholder(idx) => {
938 let id = lt_from_placeholder_idx(f.db, *idx);
939 let generics = generics(f.db.upcast(), id.parent);
940 let param_data = &generics.params.lifetimes[id.local_id];
941 write!(f, "{}", param_data.name)
943 LifetimeData::Static => write!(f, "'static"),
944 LifetimeData::Empty(_) => Ok(()),
945 LifetimeData::Erased => Ok(()),
946 LifetimeData::Phantom(_, _) => Ok(()),
951 impl HirDisplay for DomainGoal {
952 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
954 DomainGoal::Holds(wc) => {
955 write!(f, "Holds(")?;
959 _ => write!(f, "?")?,
965 pub fn write_visibility(
968 f: &mut HirFormatter,
969 ) -> Result<(), HirDisplayError> {
971 Visibility::Public => write!(f, "pub "),
972 Visibility::Module(vis_id) => {
973 let def_map = module_id.def_map(f.db.upcast());
974 let root_module_id = def_map.module_id(def_map.root());
975 if vis_id == module_id {
976 // pub(self) or omitted
978 } else if root_module_id == vis_id {
979 write!(f, "pub(crate) ")
980 } else if module_id.containing_module(f.db.upcast()) == Some(vis_id) {
981 write!(f, "pub(super) ")
983 write!(f, "pub(in ...) ")
989 impl HirDisplay for TypeRef {
990 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
992 TypeRef::Never => write!(f, "!")?,
993 TypeRef::Placeholder => write!(f, "_")?,
994 TypeRef::Tuple(elems) => {
996 f.write_joined(elems, ", ")?;
997 if elems.len() == 1 {
1002 TypeRef::Path(path) => path.hir_fmt(f)?,
1003 TypeRef::RawPtr(inner, mutability) => {
1004 let mutability = match mutability {
1005 hir_def::type_ref::Mutability::Shared => "*const ",
1006 hir_def::type_ref::Mutability::Mut => "*mut ",
1008 write!(f, "{}", mutability)?;
1011 TypeRef::Reference(inner, lifetime, mutability) => {
1012 let mutability = match mutability {
1013 hir_def::type_ref::Mutability::Shared => "",
1014 hir_def::type_ref::Mutability::Mut => "mut ",
1017 if let Some(lifetime) = lifetime {
1018 write!(f, "{} ", lifetime.name)?;
1020 write!(f, "{}", mutability)?;
1023 TypeRef::Array(inner, len) => {
1026 write!(f, "; {}]", len)?;
1028 TypeRef::Slice(inner) => {
1033 TypeRef::Fn(tys, is_varargs) => {
1034 // FIXME: Function pointer qualifiers.
1036 f.write_joined(&tys[..tys.len() - 1], ", ")?;
1038 write!(f, "{}...", if tys.len() == 1 { "" } else { ", " })?;
1041 let ret_ty = tys.last().unwrap();
1043 TypeRef::Tuple(tup) if tup.is_empty() => {}
1050 TypeRef::ImplTrait(bounds) => {
1051 write!(f, "impl ")?;
1052 f.write_joined(bounds, " + ")?;
1054 TypeRef::DynTrait(bounds) => {
1056 f.write_joined(bounds, " + ")?;
1058 TypeRef::Macro(macro_call) => {
1059 let macro_call = macro_call.to_node(f.db.upcast());
1060 let ctx = body::LowerCtx::with_hygiene(f.db.upcast(), &Hygiene::new_unhygienic());
1061 match macro_call.path() {
1062 Some(path) => match Path::from_src(path, &ctx) {
1063 Some(path) => path.hir_fmt(f)?,
1064 None => write!(f, "{{macro}}")?,
1066 None => write!(f, "{{macro}}")?,
1068 write!(f, "!(..)")?;
1070 TypeRef::Error => write!(f, "{{error}}")?,
1076 impl HirDisplay for TypeBound {
1077 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1079 TypeBound::Path(path, modifier) => {
1080 // todo don't print implicit Sized; implicit ?Sized on Self of a trait
1082 TraitBoundModifier::None => (),
1083 TraitBoundModifier::Maybe => write!(f, "?")?,
1087 TypeBound::Lifetime(lifetime) => write!(f, "{}", lifetime.name),
1088 TypeBound::ForLifetime(lifetimes, path) => {
1089 write!(f, "for<{}> ", lifetimes.iter().format(", "))?;
1092 TypeBound::Error => write!(f, "{{error}}"),
1097 impl HirDisplay for Path {
1098 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1099 match (self.type_anchor(), self.kind()) {
1100 (Some(anchor), _) => {
1105 (_, PathKind::Plain) => {}
1106 (_, PathKind::Abs) => write!(f, "::")?,
1107 (_, PathKind::Crate) => write!(f, "crate")?,
1108 (_, PathKind::Super(0)) => write!(f, "self")?,
1109 (_, PathKind::Super(n)) => {
1110 write!(f, "super")?;
1112 write!(f, "::super")?;
1115 (_, PathKind::DollarCrate(_)) => write!(f, "{{extern_crate}}")?,
1118 for (seg_idx, segment) in self.segments().iter().enumerate() {
1122 write!(f, "{}", segment.name)?;
1123 if let Some(generic_args) = segment.args_and_bindings {
1124 // We should be in type context, so format as `Foo<Bar>` instead of `Foo::<Bar>`.
1125 // Do we actually format expressions?
1127 let mut first = true;
1128 for arg in &generic_args.args {
1131 if generic_args.has_self_type {
1132 // FIXME: Convert to `<Ty as Trait>` form.
1133 write!(f, "Self = ")?;
1140 for binding in &generic_args.bindings {
1146 write!(f, "{}", binding.name)?;
1147 match &binding.type_ref {
1154 f.write_joined(&binding.bounds, " + ")?;
1165 impl HirDisplay for hir_def::path::GenericArg {
1166 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1168 hir_def::path::GenericArg::Type(ty) => ty.hir_fmt(f),
1169 hir_def::path::GenericArg::Lifetime(lifetime) => write!(f, "{}", lifetime.name),