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};
8 use chalk_ir::BoundVar;
13 generics::{TypeOrConstParamData, TypeParamProvenance},
14 intern::{Internable, Interned},
16 path::{Path, PathKind},
17 type_ref::{ConstScalar, TraitBoundModifier, TypeBound, TypeRef},
18 visibility::Visibility,
19 HasModule, ItemContainerId, Lookup, ModuleId, TraitId,
21 use hir_expand::{hygiene::Hygiene, name::Name};
22 use itertools::Itertools;
27 from_assoc_type_id, from_foreign_def_id, from_placeholder_idx, lt_from_placeholder_idx,
29 primitive, subst_prefix, to_assoc_type_id,
30 utils::{self, generics},
31 AdtId, AliasEq, AliasTy, Binders, CallableDefId, CallableSig, Const, ConstValue, DomainGoal,
32 GenericArg, ImplTraitId, Interner, Lifetime, LifetimeData, LifetimeOutlives, Mutability,
33 OpaqueTy, ProjectionTy, ProjectionTyExt, QuantifiedWhereClause, Scalar, Substitution, TraitRef,
34 TraitRefExt, Ty, TyExt, TyKind, WhereClause,
37 pub struct HirFormatter<'a> {
38 pub db: &'a dyn HirDatabase,
39 fmt: &'a mut dyn fmt::Write,
42 pub(crate) max_size: Option<usize>,
43 omit_verbose_types: bool,
44 display_target: DisplayTarget,
47 pub trait HirDisplay {
48 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError>;
50 /// Returns a `Display`able type that is human-readable.
51 fn into_displayable<'a>(
53 db: &'a dyn HirDatabase,
54 max_size: Option<usize>,
55 omit_verbose_types: bool,
56 display_target: DisplayTarget,
57 ) -> HirDisplayWrapper<'a, Self>
62 !matches!(display_target, DisplayTarget::SourceCode { .. }),
63 "HirDisplayWrapper cannot fail with DisplaySourceCodeError, use HirDisplay::hir_fmt directly instead"
65 HirDisplayWrapper { db, t: self, max_size, omit_verbose_types, display_target }
68 /// Returns a `Display`able type that is human-readable.
69 /// Use this for showing types to the user (e.g. diagnostics)
70 fn display<'a>(&'a self, db: &'a dyn HirDatabase) -> HirDisplayWrapper<'a, Self>
78 omit_verbose_types: false,
79 display_target: DisplayTarget::Diagnostics,
83 /// Returns a `Display`able type that is human-readable and tries to be succinct.
84 /// Use this for showing types to the user where space is constrained (e.g. doc popups)
85 fn display_truncated<'a>(
87 db: &'a dyn HirDatabase,
88 max_size: Option<usize>,
89 ) -> HirDisplayWrapper<'a, Self>
97 omit_verbose_types: true,
98 display_target: DisplayTarget::Diagnostics,
102 /// Returns a String representation of `self` that can be inserted into the given module.
103 /// Use this when generating code (e.g. assists)
104 fn display_source_code<'a>(
106 db: &'a dyn HirDatabase,
108 ) -> Result<String, DisplaySourceCodeError> {
109 let mut result = String::new();
110 match self.hir_fmt(&mut HirFormatter {
113 buf: String::with_capacity(20),
116 omit_verbose_types: false,
117 display_target: DisplayTarget::SourceCode { module_id },
120 Err(HirDisplayError::FmtError) => panic!("Writing to String can't fail!"),
121 Err(HirDisplayError::DisplaySourceCodeError(e)) => return Err(e),
126 /// Returns a String representation of `self` for test purposes
127 fn display_test<'a>(&'a self, db: &'a dyn HirDatabase) -> HirDisplayWrapper<'a, Self>
135 omit_verbose_types: false,
136 display_target: DisplayTarget::Test,
141 impl<'a> HirFormatter<'a> {
142 pub fn write_joined<T: HirDisplay>(
144 iter: impl IntoIterator<Item = T>,
146 ) -> Result<(), HirDisplayError> {
147 let mut first = true;
150 write!(self, "{}", sep)?;
154 // Abbreviate multiple omitted types with a single ellipsis.
155 if self.should_truncate() {
156 return write!(self, "{}", TYPE_HINT_TRUNCATION);
164 /// This allows using the `write!` macro directly with a `HirFormatter`.
165 pub fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> Result<(), HirDisplayError> {
166 // We write to a buffer first to track output size
168 fmt::write(&mut self.buf, args)?;
169 self.curr_size += self.buf.len();
171 // Then we write to the internal formatter from the buffer
172 self.fmt.write_str(&self.buf).map_err(HirDisplayError::from)
175 pub fn write_str(&mut self, s: &str) -> Result<(), HirDisplayError> {
176 self.fmt.write_str(s)?;
180 pub fn write_char(&mut self, c: char) -> Result<(), HirDisplayError> {
181 self.fmt.write_char(c)?;
185 pub fn should_truncate(&self) -> bool {
186 match self.max_size {
187 Some(max_size) => self.curr_size >= max_size,
192 pub fn omit_verbose_types(&self) -> bool {
193 self.omit_verbose_types
197 #[derive(Clone, Copy)]
198 pub enum DisplayTarget {
199 /// Display types for inlays, doc popups, autocompletion, etc...
200 /// Showing `{unknown}` or not qualifying paths is fine here.
201 /// There's no reason for this to fail.
203 /// Display types for inserting them in source files.
204 /// The generated code should compile, so paths need to be qualified.
205 SourceCode { module_id: ModuleId },
206 /// Only for test purpose to keep real types
211 fn is_source_code(&self) -> bool {
212 matches!(self, Self::SourceCode { .. })
214 fn is_test(&self) -> bool {
215 matches!(self, Self::Test)
220 pub enum DisplaySourceCodeError {
226 pub enum HirDisplayError {
227 /// Errors that can occur when generating source code
228 DisplaySourceCodeError(DisplaySourceCodeError),
229 /// `FmtError` is required to be compatible with std::fmt::Display
232 impl From<fmt::Error> for HirDisplayError {
233 fn from(_: fmt::Error) -> Self {
238 pub struct HirDisplayWrapper<'a, T> {
239 db: &'a dyn HirDatabase,
241 max_size: Option<usize>,
242 omit_verbose_types: bool,
243 display_target: DisplayTarget,
246 impl<'a, T> fmt::Display for HirDisplayWrapper<'a, T>
250 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
251 match self.t.hir_fmt(&mut HirFormatter {
254 buf: String::with_capacity(20),
256 max_size: self.max_size,
257 omit_verbose_types: self.omit_verbose_types,
258 display_target: self.display_target,
261 Err(HirDisplayError::FmtError) => Err(fmt::Error),
262 Err(HirDisplayError::DisplaySourceCodeError(_)) => {
263 // This should never happen
264 panic!("HirDisplay::hir_fmt failed with DisplaySourceCodeError when calling Display::fmt!")
270 const TYPE_HINT_TRUNCATION: &str = "…";
272 impl<T: HirDisplay> HirDisplay for &'_ T {
273 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
274 HirDisplay::hir_fmt(*self, f)
278 impl<T: HirDisplay + Internable> HirDisplay for Interned<T> {
279 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
280 HirDisplay::hir_fmt(self.as_ref(), f)
284 impl HirDisplay for ProjectionTy {
285 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
286 if f.should_truncate() {
287 return write!(f, "{}", TYPE_HINT_TRUNCATION);
290 let trait_ = f.db.trait_data(self.trait_(f.db));
292 self.self_type_parameter(Interner).hir_fmt(f)?;
293 write!(f, " as {}", trait_.name)?;
294 if self.substitution.len(Interner) > 1 {
296 f.write_joined(&self.substitution.as_slice(Interner)[1..], ", ")?;
299 write!(f, ">::{}", f.db.type_alias_data(from_assoc_type_id(self.associated_ty_id)).name)?;
304 impl HirDisplay for OpaqueTy {
305 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
306 if f.should_truncate() {
307 return write!(f, "{}", TYPE_HINT_TRUNCATION);
310 self.substitution.at(Interner, 0).hir_fmt(f)
314 impl HirDisplay for GenericArg {
315 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
316 match self.interned() {
317 crate::GenericArgData::Ty(ty) => ty.hir_fmt(f),
318 crate::GenericArgData::Lifetime(lt) => lt.hir_fmt(f),
319 crate::GenericArgData::Const(c) => c.hir_fmt(f),
324 impl HirDisplay for Const {
325 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
326 let data = self.interned();
328 ConstValue::BoundVar(idx) => idx.hir_fmt(f),
329 ConstValue::InferenceVar(..) => write!(f, "#c#"),
330 ConstValue::Placeholder(idx) => {
331 let id = from_placeholder_idx(f.db, idx);
332 let generics = generics(f.db.upcast(), id.parent);
333 let param_data = &generics.params.type_or_consts[id.local_id];
334 write!(f, "{}", param_data.name().unwrap())
336 ConstValue::Concrete(c) => write!(f, "{}", c.interned),
341 impl HirDisplay for BoundVar {
342 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
343 write!(f, "?{}.{}", self.debruijn.depth(), self.index)
347 impl HirDisplay for Ty {
348 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
349 if f.should_truncate() {
350 return write!(f, "{}", TYPE_HINT_TRUNCATION);
353 match self.kind(Interner) {
354 TyKind::Never => write!(f, "!")?,
355 TyKind::Str => write!(f, "str")?,
356 TyKind::Scalar(Scalar::Bool) => write!(f, "bool")?,
357 TyKind::Scalar(Scalar::Char) => write!(f, "char")?,
358 &TyKind::Scalar(Scalar::Float(t)) => write!(f, "{}", primitive::float_ty_to_string(t))?,
359 &TyKind::Scalar(Scalar::Int(t)) => write!(f, "{}", primitive::int_ty_to_string(t))?,
360 &TyKind::Scalar(Scalar::Uint(t)) => write!(f, "{}", primitive::uint_ty_to_string(t))?,
361 TyKind::Slice(t) => {
366 TyKind::Array(t, c) => {
373 TyKind::Raw(m, t) | TyKind::Ref(m, _, t) => {
374 if matches!(self.kind(Interner), TyKind::Raw(..)) {
379 Mutability::Not => "const ",
380 Mutability::Mut => "mut ",
388 Mutability::Not => "",
389 Mutability::Mut => "mut ",
394 // FIXME: all this just to decide whether to use parentheses...
395 let contains_impl_fn = |bounds: &[QuantifiedWhereClause]| {
396 bounds.iter().any(|bound| {
397 if let WhereClause::Implemented(trait_ref) = bound.skip_binders() {
398 let trait_ = trait_ref.hir_trait_id();
399 fn_traits(f.db.upcast(), trait_).any(|it| it == trait_)
405 let (preds_to_print, has_impl_fn_pred) = match t.kind(Interner) {
406 TyKind::Dyn(dyn_ty) if dyn_ty.bounds.skip_binders().interned().len() > 1 => {
407 let bounds = dyn_ty.bounds.skip_binders().interned();
408 (bounds.len(), contains_impl_fn(bounds))
410 TyKind::Alias(AliasTy::Opaque(OpaqueTy {
412 substitution: parameters,
414 | TyKind::OpaqueType(opaque_ty_id, parameters) => {
416 f.db.lookup_intern_impl_trait_id((*opaque_ty_id).into());
417 if let ImplTraitId::ReturnTypeImplTrait(func, idx) = impl_trait_id {
419 f.db.return_type_impl_traits(func)
420 .expect("impl trait id without data");
423 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
424 let bounds = data.substitute(Interner, parameters);
425 let mut len = bounds.skip_binders().len();
427 // Don't count Sized but count when it absent
428 // (i.e. when explicit ?Sized bound is set).
429 let default_sized = SizedByDefault::Sized {
430 anchor: func.lookup(f.db.upcast()).module(f.db.upcast()).krate(),
432 let sized_bounds = bounds
438 WhereClause::Implemented(trait_ref)
439 if default_sized.is_sized_trait(
440 trait_ref.hir_trait_id(),
449 len = len.saturating_sub(sized_bounds);
453 (len, contains_impl_fn(bounds.skip_binders()))
461 if has_impl_fn_pred && preds_to_print <= 2 {
465 if preds_to_print > 1 {
473 TyKind::Tuple(_, substs) => {
474 if substs.len(Interner) == 1 {
476 substs.at(Interner, 0).hir_fmt(f)?;
480 f.write_joined(&*substs.as_slice(Interner), ", ")?;
484 TyKind::Function(fn_ptr) => {
485 let sig = CallableSig::from_fn_ptr(fn_ptr);
488 TyKind::FnDef(def, parameters) => {
489 let def = from_chalk(f.db, *def);
490 let sig = f.db.callable_item_signature(def).substitute(Interner, parameters);
492 CallableDefId::FunctionId(ff) => {
493 write!(f, "fn {}", f.db.function_data(ff).name)?
495 CallableDefId::StructId(s) => write!(f, "{}", f.db.struct_data(s).name)?,
496 CallableDefId::EnumVariantId(e) => {
497 write!(f, "{}", f.db.enum_data(e.parent).variants[e.local_id].name)?
500 if parameters.len(Interner) > 0 {
501 let generics = generics(f.db.upcast(), def.into());
502 let (parent_params, self_param, type_params, const_params, _impl_trait_params) =
503 generics.provenance_split();
504 let total_len = parent_params + self_param + type_params + const_params;
505 // We print all params except implicit impl Trait params. Still a bit weird; should we leave out parent and self?
508 f.write_joined(¶meters.as_slice(Interner)[..total_len], ", ")?;
513 f.write_joined(sig.params(), ", ")?;
521 TyKind::Adt(AdtId(def_id), parameters) => {
522 match f.display_target {
523 DisplayTarget::Diagnostics | DisplayTarget::Test => {
524 let name = match *def_id {
525 hir_def::AdtId::StructId(it) => f.db.struct_data(it).name.clone(),
526 hir_def::AdtId::UnionId(it) => f.db.union_data(it).name.clone(),
527 hir_def::AdtId::EnumId(it) => f.db.enum_data(it).name.clone(),
529 write!(f, "{}", name)?;
531 DisplayTarget::SourceCode { module_id } => {
532 if let Some(path) = find_path::find_path(
534 ItemInNs::Types((*def_id).into()),
537 write!(f, "{}", path)?;
539 return Err(HirDisplayError::DisplaySourceCodeError(
540 DisplaySourceCodeError::PathNotFound,
546 if parameters.len(Interner) > 0 {
547 let parameters_to_write = if f.display_target.is_source_code()
548 || f.omit_verbose_types()
551 .as_generic_def(f.db)
552 .map(|generic_def_id| f.db.generic_defaults(generic_def_id))
553 .filter(|defaults| !defaults.is_empty())
555 None => parameters.as_slice(Interner),
556 Some(default_parameters) => {
558 parameter: &GenericArg,
559 default_parameters: &[Binders<GenericArg>],
561 parameters: &Substitution,
563 if parameter.ty(Interner).map(|x| x.kind(Interner))
564 == Some(&TyKind::Error)
568 if let Some(ConstValue::Concrete(c)) =
569 parameter.constant(Interner).map(|x| x.data(Interner).value)
571 if c.interned == ConstScalar::Unknown {
575 let default_parameter = match default_parameters.get(i) {
579 let actual_default = default_parameter
581 .substitute(Interner, &subst_prefix(parameters, i));
582 parameter != &actual_default
584 let mut default_from = 0;
585 for (i, parameter) in parameters.iter(Interner).enumerate() {
586 if should_show(parameter, &default_parameters, i, parameters) {
587 default_from = i + 1;
590 ¶meters.as_slice(Interner)[0..default_from]
594 parameters.as_slice(Interner)
596 if !parameters_to_write.is_empty() {
599 if f.display_target.is_source_code() {
600 let mut first = true;
601 for generic_arg in parameters_to_write {
607 if generic_arg.ty(Interner).map(|ty| ty.kind(Interner))
608 == Some(&TyKind::Error)
612 generic_arg.hir_fmt(f)?;
616 f.write_joined(parameters_to_write, ", ")?;
623 TyKind::AssociatedType(assoc_type_id, parameters) => {
624 let type_alias = from_assoc_type_id(*assoc_type_id);
625 let trait_ = match type_alias.lookup(f.db.upcast()).container {
626 ItemContainerId::TraitId(it) => it,
627 _ => panic!("not an associated type"),
629 let trait_ = f.db.trait_data(trait_);
630 let type_alias_data = f.db.type_alias_data(type_alias);
632 // Use placeholder associated types when the target is test (https://rust-lang.github.io/chalk/book/clauses/type_equality.html#placeholder-associated-types)
633 if f.display_target.is_test() {
634 write!(f, "{}::{}", trait_.name, type_alias_data.name)?;
635 if parameters.len(Interner) > 0 {
637 f.write_joined(&*parameters.as_slice(Interner), ", ")?;
641 let projection_ty = ProjectionTy {
642 associated_ty_id: to_assoc_type_id(type_alias),
643 substitution: parameters.clone(),
646 projection_ty.hir_fmt(f)?;
649 TyKind::Foreign(type_alias) => {
650 let type_alias = f.db.type_alias_data(from_foreign_def_id(*type_alias));
651 write!(f, "{}", type_alias.name)?;
653 TyKind::OpaqueType(opaque_ty_id, parameters) => {
654 let impl_trait_id = f.db.lookup_intern_impl_trait_id((*opaque_ty_id).into());
655 match impl_trait_id {
656 ImplTraitId::ReturnTypeImplTrait(func, idx) => {
658 f.db.return_type_impl_traits(func).expect("impl trait id without data");
661 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
662 let bounds = data.substitute(Interner, ¶meters);
663 let krate = func.lookup(f.db.upcast()).module(f.db.upcast()).krate();
664 write_bounds_like_dyn_trait_with_prefix(
666 bounds.skip_binders(),
667 SizedByDefault::Sized { anchor: krate },
670 // FIXME: it would maybe be good to distinguish this from the alias type (when debug printing), and to show the substitution
672 ImplTraitId::AsyncBlockTypeImplTrait(..) => {
673 write!(f, "impl Future<Output = ")?;
674 parameters.at(Interner, 0).hir_fmt(f)?;
679 TyKind::Closure(.., substs) => {
680 if f.display_target.is_source_code() {
681 return Err(HirDisplayError::DisplaySourceCodeError(
682 DisplaySourceCodeError::Closure,
685 let sig = substs.at(Interner, 0).assert_ty_ref(Interner).callable_sig(f.db);
686 if let Some(sig) = sig {
687 if sig.params().is_empty() {
689 } else if f.should_truncate() {
690 write!(f, "|{}|", TYPE_HINT_TRUNCATION)?;
693 f.write_joined(sig.params(), ", ")?;
698 sig.ret().hir_fmt(f)?;
700 write!(f, "{{closure}}")?;
703 TyKind::Placeholder(idx) => {
704 let id = from_placeholder_idx(f.db, *idx);
705 let generics = generics(f.db.upcast(), id.parent);
706 let param_data = &generics.params.type_or_consts[id.local_id];
708 TypeOrConstParamData::TypeParamData(p) => match p.provenance {
709 TypeParamProvenance::TypeParamList | TypeParamProvenance::TraitSelf => {
710 write!(f, "{}", p.name.clone().unwrap_or_else(Name::missing))?
712 TypeParamProvenance::ArgumentImplTrait => {
713 let substs = generics.placeholder_subst(f.db);
715 f.db.generic_predicates(id.parent)
717 .map(|pred| pred.clone().substitute(Interner, &substs))
718 .filter(|wc| match &wc.skip_binders() {
719 WhereClause::Implemented(tr) => {
720 &tr.self_type_parameter(Interner) == self
722 WhereClause::AliasEq(AliasEq {
723 alias: AliasTy::Projection(proj),
725 }) => &proj.self_type_parameter(Interner) == self,
728 .collect::<Vec<_>>();
729 let krate = id.parent.module(f.db.upcast()).krate();
730 write_bounds_like_dyn_trait_with_prefix(
733 SizedByDefault::Sized { anchor: krate },
738 TypeOrConstParamData::ConstParamData(p) => {
739 write!(f, "{}", p.name)?;
743 TyKind::BoundVar(idx) => idx.hir_fmt(f)?,
744 TyKind::Dyn(dyn_ty) => {
745 write_bounds_like_dyn_trait_with_prefix(
747 dyn_ty.bounds.skip_binders().interned(),
748 SizedByDefault::NotSized,
752 TyKind::Alias(AliasTy::Projection(p_ty)) => p_ty.hir_fmt(f)?,
753 TyKind::Alias(AliasTy::Opaque(opaque_ty)) => {
754 let impl_trait_id = f.db.lookup_intern_impl_trait_id(opaque_ty.opaque_ty_id.into());
755 match impl_trait_id {
756 ImplTraitId::ReturnTypeImplTrait(func, idx) => {
758 f.db.return_type_impl_traits(func).expect("impl trait id without data");
761 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
762 let bounds = data.substitute(Interner, &opaque_ty.substitution);
763 let krate = func.lookup(f.db.upcast()).module(f.db.upcast()).krate();
764 write_bounds_like_dyn_trait_with_prefix(
766 bounds.skip_binders(),
767 SizedByDefault::Sized { anchor: krate },
771 ImplTraitId::AsyncBlockTypeImplTrait(..) => {
772 write!(f, "{{async block}}")?;
777 if f.display_target.is_source_code() {
778 return Err(HirDisplayError::DisplaySourceCodeError(
779 DisplaySourceCodeError::UnknownType,
782 write!(f, "{{unknown}}")?;
784 TyKind::InferenceVar(..) => write!(f, "_")?,
785 TyKind::Generator(..) => write!(f, "{{generator}}")?,
786 TyKind::GeneratorWitness(..) => write!(f, "{{generator witness}}")?,
792 impl HirDisplay for CallableSig {
793 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
795 f.write_joined(self.params(), ", ")?;
797 if self.params().is_empty() {
804 let ret = self.ret();
813 fn fn_traits(db: &dyn DefDatabase, trait_: TraitId) -> impl Iterator<Item = TraitId> {
814 let krate = trait_.lookup(db).container.krate();
815 utils::fn_traits(db, krate)
818 #[derive(Clone, Copy, PartialEq, Eq)]
819 pub enum SizedByDefault {
821 Sized { anchor: CrateId },
824 impl SizedByDefault {
825 fn is_sized_trait(self, trait_: TraitId, db: &dyn DefDatabase) -> bool {
827 Self::NotSized => false,
828 Self::Sized { anchor } => {
830 .lang_item(anchor, SmolStr::new_inline("sized"))
831 .and_then(|lang_item| lang_item.as_trait());
832 Some(trait_) == sized_trait
838 pub fn write_bounds_like_dyn_trait_with_prefix(
840 predicates: &[QuantifiedWhereClause],
841 default_sized: SizedByDefault,
842 f: &mut HirFormatter<'_>,
843 ) -> Result<(), HirDisplayError> {
844 write!(f, "{}", prefix)?;
845 if !predicates.is_empty()
846 || predicates.is_empty() && matches!(default_sized, SizedByDefault::Sized { .. })
849 write_bounds_like_dyn_trait(predicates, default_sized, f)
855 fn write_bounds_like_dyn_trait(
856 predicates: &[QuantifiedWhereClause],
857 default_sized: SizedByDefault,
858 f: &mut HirFormatter<'_>,
859 ) -> Result<(), HirDisplayError> {
860 // Note: This code is written to produce nice results (i.e.
861 // corresponding to surface Rust) for types that can occur in
862 // actual Rust. It will have weird results if the predicates
863 // aren't as expected (i.e. self types = $0, projection
864 // predicates for a certain trait come after the Implemented
865 // predicate for that trait).
866 let mut first = true;
867 let mut angle_open = false;
868 let mut is_fn_trait = false;
869 let mut is_sized = false;
870 for p in predicates.iter() {
871 match p.skip_binders() {
872 WhereClause::Implemented(trait_ref) => {
873 let trait_ = trait_ref.hir_trait_id();
874 if default_sized.is_sized_trait(trait_, f.db.upcast()) {
876 if matches!(default_sized, SizedByDefault::Sized { .. }) {
877 // Don't print +Sized, but rather +?Sized if absent.
882 is_fn_trait = fn_traits(f.db.upcast(), trait_).any(|it| it == trait_);
884 if !is_fn_trait && angle_open {
891 // We assume that the self type is ^0.0 (i.e. the
892 // existential) here, which is the only thing that's
893 // possible in actual Rust, and hence don't print it
894 write!(f, "{}", f.db.trait_data(trait_).name)?;
895 if let [_, params @ ..] = &*trait_ref.substitution.as_slice(Interner) {
898 params.first().and_then(|it| it.assert_ty_ref(Interner).as_tuple())
901 f.write_joined(args.as_slice(Interner), ", ")?;
904 } else if !params.is_empty() {
906 f.write_joined(params, ", ")?;
907 // there might be assoc type bindings, so we leave the angle brackets open
912 WhereClause::AliasEq(alias_eq) if is_fn_trait => {
914 if !alias_eq.ty.is_unit() {
916 alias_eq.ty.hir_fmt(f)?;
919 WhereClause::AliasEq(AliasEq { ty, alias }) => {
920 // in types in actual Rust, these will always come
921 // after the corresponding Implemented predicate
928 if let AliasTy::Projection(proj) = alias {
930 f.db.type_alias_data(from_assoc_type_id(proj.associated_ty_id));
931 write!(f, "{} = ", type_alias.name)?;
936 // FIXME implement these
937 WhereClause::LifetimeOutlives(_) => {}
938 WhereClause::TypeOutlives(_) => {}
945 if matches!(default_sized, SizedByDefault::Sized { .. }) {
947 write!(f, "{}?Sized", if first { "" } else { " + " })?;
957 f: &mut HirFormatter<'_>,
959 ) -> Result<(), HirDisplayError> {
960 if f.should_truncate() {
961 return write!(f, "{}", TYPE_HINT_TRUNCATION);
964 tr.self_type_parameter(Interner).hir_fmt(f)?;
970 write!(f, "{}", f.db.trait_data(tr.hir_trait_id()).name)?;
971 if tr.substitution.len(Interner) > 1 {
973 f.write_joined(&tr.substitution.as_slice(Interner)[1..], ", ")?;
979 impl HirDisplay for TraitRef {
980 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
981 fmt_trait_ref(self, f, false)
985 impl HirDisplay for WhereClause {
986 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
987 if f.should_truncate() {
988 return write!(f, "{}", TYPE_HINT_TRUNCATION);
992 WhereClause::Implemented(trait_ref) => trait_ref.hir_fmt(f)?,
993 WhereClause::AliasEq(AliasEq { alias: AliasTy::Projection(projection_ty), ty }) => {
995 fmt_trait_ref(&projection_ty.trait_ref(f.db), f, true)?;
999 f.db.type_alias_data(from_assoc_type_id(projection_ty.associated_ty_id)).name,
1003 WhereClause::AliasEq(_) => write!(f, "{{error}}")?,
1005 // FIXME implement these
1006 WhereClause::TypeOutlives(..) => {}
1007 WhereClause::LifetimeOutlives(..) => {}
1013 impl HirDisplay for LifetimeOutlives {
1014 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
1021 impl HirDisplay for Lifetime {
1022 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
1023 self.interned().hir_fmt(f)
1027 impl HirDisplay for LifetimeData {
1028 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
1030 LifetimeData::BoundVar(idx) => idx.hir_fmt(f),
1031 LifetimeData::InferenceVar(_) => write!(f, "_"),
1032 LifetimeData::Placeholder(idx) => {
1033 let id = lt_from_placeholder_idx(f.db, *idx);
1034 let generics = generics(f.db.upcast(), id.parent);
1035 let param_data = &generics.params.lifetimes[id.local_id];
1036 write!(f, "{}", param_data.name)
1038 LifetimeData::Static => write!(f, "'static"),
1039 LifetimeData::Empty(_) => Ok(()),
1040 LifetimeData::Erased => Ok(()),
1041 LifetimeData::Phantom(_, _) => Ok(()),
1046 impl HirDisplay for DomainGoal {
1047 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
1049 DomainGoal::Holds(wc) => {
1050 write!(f, "Holds(")?;
1054 _ => write!(f, "?")?,
1060 pub fn write_visibility(
1061 module_id: ModuleId,
1063 f: &mut HirFormatter<'_>,
1064 ) -> Result<(), HirDisplayError> {
1066 Visibility::Public => write!(f, "pub "),
1067 Visibility::Module(vis_id) => {
1068 let def_map = module_id.def_map(f.db.upcast());
1069 let root_module_id = def_map.module_id(def_map.root());
1070 if vis_id == module_id {
1071 // pub(self) or omitted
1073 } else if root_module_id == vis_id {
1074 write!(f, "pub(crate) ")
1075 } else if module_id.containing_module(f.db.upcast()) == Some(vis_id) {
1076 write!(f, "pub(super) ")
1078 write!(f, "pub(in ...) ")
1084 impl HirDisplay for TypeRef {
1085 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
1087 TypeRef::Never => write!(f, "!")?,
1088 TypeRef::Placeholder => write!(f, "_")?,
1089 TypeRef::Tuple(elems) => {
1091 f.write_joined(elems, ", ")?;
1092 if elems.len() == 1 {
1097 TypeRef::Path(path) => path.hir_fmt(f)?,
1098 TypeRef::RawPtr(inner, mutability) => {
1099 let mutability = match mutability {
1100 hir_def::type_ref::Mutability::Shared => "*const ",
1101 hir_def::type_ref::Mutability::Mut => "*mut ",
1103 write!(f, "{}", mutability)?;
1106 TypeRef::Reference(inner, lifetime, mutability) => {
1107 let mutability = match mutability {
1108 hir_def::type_ref::Mutability::Shared => "",
1109 hir_def::type_ref::Mutability::Mut => "mut ",
1112 if let Some(lifetime) = lifetime {
1113 write!(f, "{} ", lifetime.name)?;
1115 write!(f, "{}", mutability)?;
1118 TypeRef::Array(inner, len) => {
1121 write!(f, "; {}]", len)?;
1123 TypeRef::Slice(inner) => {
1128 TypeRef::Fn(parameters, is_varargs) => {
1129 // FIXME: Function pointer qualifiers.
1131 if let Some(((_, return_type), function_parameters)) = parameters.split_last() {
1132 for index in 0..function_parameters.len() {
1133 let (param_name, param_type) = &function_parameters[index];
1134 if let Some(name) = param_name {
1135 write!(f, "{}: ", name)?;
1138 param_type.hir_fmt(f)?;
1140 if index != function_parameters.len() - 1 {
1145 write!(f, "{}...", if parameters.len() == 1 { "" } else { ", " })?;
1148 match &return_type {
1149 TypeRef::Tuple(tup) if tup.is_empty() => {}
1152 return_type.hir_fmt(f)?;
1157 TypeRef::ImplTrait(bounds) => {
1158 write!(f, "impl ")?;
1159 f.write_joined(bounds, " + ")?;
1161 TypeRef::DynTrait(bounds) => {
1163 f.write_joined(bounds, " + ")?;
1165 TypeRef::Macro(macro_call) => {
1166 let macro_call = macro_call.to_node(f.db.upcast());
1167 let ctx = body::LowerCtx::with_hygiene(f.db.upcast(), &Hygiene::new_unhygienic());
1168 match macro_call.path() {
1169 Some(path) => match Path::from_src(path, &ctx) {
1170 Some(path) => path.hir_fmt(f)?,
1171 None => write!(f, "{{macro}}")?,
1173 None => write!(f, "{{macro}}")?,
1175 write!(f, "!(..)")?;
1177 TypeRef::Error => write!(f, "{{error}}")?,
1183 impl HirDisplay for TypeBound {
1184 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
1186 TypeBound::Path(path, modifier) => {
1188 TraitBoundModifier::None => (),
1189 TraitBoundModifier::Maybe => write!(f, "?")?,
1193 TypeBound::Lifetime(lifetime) => write!(f, "{}", lifetime.name),
1194 TypeBound::ForLifetime(lifetimes, path) => {
1195 write!(f, "for<{}> ", lifetimes.iter().format(", "))?;
1198 TypeBound::Error => write!(f, "{{error}}"),
1203 impl HirDisplay for Path {
1204 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
1205 match (self.type_anchor(), self.kind()) {
1206 (Some(anchor), _) => {
1211 (_, PathKind::Plain) => {}
1212 (_, PathKind::Abs) => {}
1213 (_, PathKind::Crate) => write!(f, "crate")?,
1214 (_, PathKind::Super(0)) => write!(f, "self")?,
1215 (_, PathKind::Super(n)) => {
1220 write!(f, "super")?;
1223 (_, PathKind::DollarCrate(id)) => {
1224 // Resolve `$crate` to the crate's display name.
1225 // FIXME: should use the dependency name instead if available, but that depends on
1226 // the crate invoking `HirDisplay`
1227 let crate_graph = f.db.crate_graph();
1228 let name = crate_graph[*id]
1231 .map(|name| name.canonical_name())
1232 .unwrap_or("$crate");
1233 write!(f, "{name}")?
1237 for (seg_idx, segment) in self.segments().iter().enumerate() {
1238 if !matches!(self.kind(), PathKind::Plain) || seg_idx > 0 {
1241 write!(f, "{}", segment.name)?;
1242 if let Some(generic_args) = segment.args_and_bindings {
1243 // We should be in type context, so format as `Foo<Bar>` instead of `Foo::<Bar>`.
1244 // Do we actually format expressions?
1245 if generic_args.desugared_from_fn {
1246 // First argument will be a tuple, which already includes the parentheses.
1247 // If the tuple only contains 1 item, write it manually to avoid the trailing `,`.
1248 if let hir_def::path::GenericArg::Type(TypeRef::Tuple(v)) =
1249 &generic_args.args[0]
1256 generic_args.args[0].hir_fmt(f)?;
1259 if let Some(ret) = &generic_args.bindings[0].type_ref {
1260 if !matches!(ret, TypeRef::Tuple(v) if v.is_empty()) {
1269 let mut first = true;
1270 for arg in &generic_args.args {
1273 if generic_args.has_self_type {
1274 // FIXME: Convert to `<Ty as Trait>` form.
1275 write!(f, "Self = ")?;
1282 for binding in &generic_args.bindings {
1288 write!(f, "{}", binding.name)?;
1289 match &binding.type_ref {
1296 f.write_joined(&binding.bounds, " + ")?;
1307 impl HirDisplay for hir_def::path::GenericArg {
1308 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
1310 hir_def::path::GenericArg::Type(ty) => ty.hir_fmt(f),
1311 hir_def::path::GenericArg::Const(c) => write!(f, "{}", c),
1312 hir_def::path::GenericArg::Lifetime(lifetime) => write!(f, "{}", lifetime.name),