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()),
538 write!(f, "{}", path)?;
540 return Err(HirDisplayError::DisplaySourceCodeError(
541 DisplaySourceCodeError::PathNotFound,
547 if parameters.len(Interner) > 0 {
548 let parameters_to_write = if f.display_target.is_source_code()
549 || f.omit_verbose_types()
552 .as_generic_def(f.db)
553 .map(|generic_def_id| f.db.generic_defaults(generic_def_id))
554 .filter(|defaults| !defaults.is_empty())
556 None => parameters.as_slice(Interner),
557 Some(default_parameters) => {
559 parameter: &GenericArg,
560 default_parameters: &[Binders<GenericArg>],
562 parameters: &Substitution,
564 if parameter.ty(Interner).map(|x| x.kind(Interner))
565 == Some(&TyKind::Error)
569 if let Some(ConstValue::Concrete(c)) =
570 parameter.constant(Interner).map(|x| x.data(Interner).value)
572 if c.interned == ConstScalar::Unknown {
576 let default_parameter = match default_parameters.get(i) {
580 let actual_default = default_parameter
582 .substitute(Interner, &subst_prefix(parameters, i));
583 parameter != &actual_default
585 let mut default_from = 0;
586 for (i, parameter) in parameters.iter(Interner).enumerate() {
587 if should_show(parameter, &default_parameters, i, parameters) {
588 default_from = i + 1;
591 ¶meters.as_slice(Interner)[0..default_from]
595 parameters.as_slice(Interner)
597 if !parameters_to_write.is_empty() {
600 if f.display_target.is_source_code() {
601 let mut first = true;
602 for generic_arg in parameters_to_write {
608 if generic_arg.ty(Interner).map(|ty| ty.kind(Interner))
609 == Some(&TyKind::Error)
613 generic_arg.hir_fmt(f)?;
617 f.write_joined(parameters_to_write, ", ")?;
624 TyKind::AssociatedType(assoc_type_id, parameters) => {
625 let type_alias = from_assoc_type_id(*assoc_type_id);
626 let trait_ = match type_alias.lookup(f.db.upcast()).container {
627 ItemContainerId::TraitId(it) => it,
628 _ => panic!("not an associated type"),
630 let trait_ = f.db.trait_data(trait_);
631 let type_alias_data = f.db.type_alias_data(type_alias);
633 // Use placeholder associated types when the target is test (https://rust-lang.github.io/chalk/book/clauses/type_equality.html#placeholder-associated-types)
634 if f.display_target.is_test() {
635 write!(f, "{}::{}", trait_.name, type_alias_data.name)?;
636 if parameters.len(Interner) > 0 {
638 f.write_joined(&*parameters.as_slice(Interner), ", ")?;
642 let projection_ty = ProjectionTy {
643 associated_ty_id: to_assoc_type_id(type_alias),
644 substitution: parameters.clone(),
647 projection_ty.hir_fmt(f)?;
650 TyKind::Foreign(type_alias) => {
651 let type_alias = f.db.type_alias_data(from_foreign_def_id(*type_alias));
652 write!(f, "{}", type_alias.name)?;
654 TyKind::OpaqueType(opaque_ty_id, parameters) => {
655 let impl_trait_id = f.db.lookup_intern_impl_trait_id((*opaque_ty_id).into());
656 match impl_trait_id {
657 ImplTraitId::ReturnTypeImplTrait(func, idx) => {
659 f.db.return_type_impl_traits(func).expect("impl trait id without data");
662 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
663 let bounds = data.substitute(Interner, ¶meters);
664 let krate = func.lookup(f.db.upcast()).module(f.db.upcast()).krate();
665 write_bounds_like_dyn_trait_with_prefix(
667 bounds.skip_binders(),
668 SizedByDefault::Sized { anchor: krate },
671 // FIXME: it would maybe be good to distinguish this from the alias type (when debug printing), and to show the substitution
673 ImplTraitId::AsyncBlockTypeImplTrait(..) => {
674 write!(f, "impl Future<Output = ")?;
675 parameters.at(Interner, 0).hir_fmt(f)?;
680 TyKind::Closure(.., substs) => {
681 if f.display_target.is_source_code() {
682 return Err(HirDisplayError::DisplaySourceCodeError(
683 DisplaySourceCodeError::Closure,
686 let sig = substs.at(Interner, 0).assert_ty_ref(Interner).callable_sig(f.db);
687 if let Some(sig) = sig {
688 if sig.params().is_empty() {
690 } else if f.should_truncate() {
691 write!(f, "|{}|", TYPE_HINT_TRUNCATION)?;
694 f.write_joined(sig.params(), ", ")?;
699 sig.ret().hir_fmt(f)?;
701 write!(f, "{{closure}}")?;
704 TyKind::Placeholder(idx) => {
705 let id = from_placeholder_idx(f.db, *idx);
706 let generics = generics(f.db.upcast(), id.parent);
707 let param_data = &generics.params.type_or_consts[id.local_id];
709 TypeOrConstParamData::TypeParamData(p) => match p.provenance {
710 TypeParamProvenance::TypeParamList | TypeParamProvenance::TraitSelf => {
711 write!(f, "{}", p.name.clone().unwrap_or_else(Name::missing))?
713 TypeParamProvenance::ArgumentImplTrait => {
714 let substs = generics.placeholder_subst(f.db);
716 f.db.generic_predicates(id.parent)
718 .map(|pred| pred.clone().substitute(Interner, &substs))
719 .filter(|wc| match &wc.skip_binders() {
720 WhereClause::Implemented(tr) => {
721 &tr.self_type_parameter(Interner) == self
723 WhereClause::AliasEq(AliasEq {
724 alias: AliasTy::Projection(proj),
726 }) => &proj.self_type_parameter(Interner) == self,
729 .collect::<Vec<_>>();
730 let krate = id.parent.module(f.db.upcast()).krate();
731 write_bounds_like_dyn_trait_with_prefix(
734 SizedByDefault::Sized { anchor: krate },
739 TypeOrConstParamData::ConstParamData(p) => {
740 write!(f, "{}", p.name)?;
744 TyKind::BoundVar(idx) => idx.hir_fmt(f)?,
745 TyKind::Dyn(dyn_ty) => {
746 write_bounds_like_dyn_trait_with_prefix(
748 dyn_ty.bounds.skip_binders().interned(),
749 SizedByDefault::NotSized,
753 TyKind::Alias(AliasTy::Projection(p_ty)) => p_ty.hir_fmt(f)?,
754 TyKind::Alias(AliasTy::Opaque(opaque_ty)) => {
755 let impl_trait_id = f.db.lookup_intern_impl_trait_id(opaque_ty.opaque_ty_id.into());
756 match impl_trait_id {
757 ImplTraitId::ReturnTypeImplTrait(func, idx) => {
759 f.db.return_type_impl_traits(func).expect("impl trait id without data");
762 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
763 let bounds = data.substitute(Interner, &opaque_ty.substitution);
764 let krate = func.lookup(f.db.upcast()).module(f.db.upcast()).krate();
765 write_bounds_like_dyn_trait_with_prefix(
767 bounds.skip_binders(),
768 SizedByDefault::Sized { anchor: krate },
772 ImplTraitId::AsyncBlockTypeImplTrait(..) => {
773 write!(f, "{{async block}}")?;
778 if f.display_target.is_source_code() {
779 return Err(HirDisplayError::DisplaySourceCodeError(
780 DisplaySourceCodeError::UnknownType,
783 write!(f, "{{unknown}}")?;
785 TyKind::InferenceVar(..) => write!(f, "_")?,
786 TyKind::Generator(..) => write!(f, "{{generator}}")?,
787 TyKind::GeneratorWitness(..) => write!(f, "{{generator witness}}")?,
793 impl HirDisplay for CallableSig {
794 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
796 f.write_joined(self.params(), ", ")?;
798 if self.params().is_empty() {
805 let ret = self.ret();
814 fn fn_traits(db: &dyn DefDatabase, trait_: TraitId) -> impl Iterator<Item = TraitId> {
815 let krate = trait_.lookup(db).container.krate();
816 utils::fn_traits(db, krate)
819 #[derive(Clone, Copy, PartialEq, Eq)]
820 pub enum SizedByDefault {
822 Sized { anchor: CrateId },
825 impl SizedByDefault {
826 fn is_sized_trait(self, trait_: TraitId, db: &dyn DefDatabase) -> bool {
828 Self::NotSized => false,
829 Self::Sized { anchor } => {
831 .lang_item(anchor, SmolStr::new_inline("sized"))
832 .and_then(|lang_item| lang_item.as_trait());
833 Some(trait_) == sized_trait
839 pub fn write_bounds_like_dyn_trait_with_prefix(
841 predicates: &[QuantifiedWhereClause],
842 default_sized: SizedByDefault,
843 f: &mut HirFormatter<'_>,
844 ) -> Result<(), HirDisplayError> {
845 write!(f, "{}", prefix)?;
846 if !predicates.is_empty()
847 || predicates.is_empty() && matches!(default_sized, SizedByDefault::Sized { .. })
850 write_bounds_like_dyn_trait(predicates, default_sized, f)
856 fn write_bounds_like_dyn_trait(
857 predicates: &[QuantifiedWhereClause],
858 default_sized: SizedByDefault,
859 f: &mut HirFormatter<'_>,
860 ) -> Result<(), HirDisplayError> {
861 // Note: This code is written to produce nice results (i.e.
862 // corresponding to surface Rust) for types that can occur in
863 // actual Rust. It will have weird results if the predicates
864 // aren't as expected (i.e. self types = $0, projection
865 // predicates for a certain trait come after the Implemented
866 // predicate for that trait).
867 let mut first = true;
868 let mut angle_open = false;
869 let mut is_fn_trait = false;
870 let mut is_sized = false;
871 for p in predicates.iter() {
872 match p.skip_binders() {
873 WhereClause::Implemented(trait_ref) => {
874 let trait_ = trait_ref.hir_trait_id();
875 if default_sized.is_sized_trait(trait_, f.db.upcast()) {
877 if matches!(default_sized, SizedByDefault::Sized { .. }) {
878 // Don't print +Sized, but rather +?Sized if absent.
883 is_fn_trait = fn_traits(f.db.upcast(), trait_).any(|it| it == trait_);
885 if !is_fn_trait && angle_open {
892 // We assume that the self type is ^0.0 (i.e. the
893 // existential) here, which is the only thing that's
894 // possible in actual Rust, and hence don't print it
895 write!(f, "{}", f.db.trait_data(trait_).name)?;
896 if let [_, params @ ..] = &*trait_ref.substitution.as_slice(Interner) {
899 params.first().and_then(|it| it.assert_ty_ref(Interner).as_tuple())
902 f.write_joined(args.as_slice(Interner), ", ")?;
905 } else if !params.is_empty() {
907 f.write_joined(params, ", ")?;
908 // there might be assoc type bindings, so we leave the angle brackets open
913 WhereClause::AliasEq(alias_eq) if is_fn_trait => {
915 if !alias_eq.ty.is_unit() {
917 alias_eq.ty.hir_fmt(f)?;
920 WhereClause::AliasEq(AliasEq { ty, alias }) => {
921 // in types in actual Rust, these will always come
922 // after the corresponding Implemented predicate
929 if let AliasTy::Projection(proj) = alias {
931 f.db.type_alias_data(from_assoc_type_id(proj.associated_ty_id));
932 write!(f, "{} = ", type_alias.name)?;
937 // FIXME implement these
938 WhereClause::LifetimeOutlives(_) => {}
939 WhereClause::TypeOutlives(_) => {}
946 if matches!(default_sized, SizedByDefault::Sized { .. }) {
948 write!(f, "{}?Sized", if first { "" } else { " + " })?;
958 f: &mut HirFormatter<'_>,
960 ) -> Result<(), HirDisplayError> {
961 if f.should_truncate() {
962 return write!(f, "{}", TYPE_HINT_TRUNCATION);
965 tr.self_type_parameter(Interner).hir_fmt(f)?;
971 write!(f, "{}", f.db.trait_data(tr.hir_trait_id()).name)?;
972 if tr.substitution.len(Interner) > 1 {
974 f.write_joined(&tr.substitution.as_slice(Interner)[1..], ", ")?;
980 impl HirDisplay for TraitRef {
981 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
982 fmt_trait_ref(self, f, false)
986 impl HirDisplay for WhereClause {
987 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
988 if f.should_truncate() {
989 return write!(f, "{}", TYPE_HINT_TRUNCATION);
993 WhereClause::Implemented(trait_ref) => trait_ref.hir_fmt(f)?,
994 WhereClause::AliasEq(AliasEq { alias: AliasTy::Projection(projection_ty), ty }) => {
996 fmt_trait_ref(&projection_ty.trait_ref(f.db), f, true)?;
1000 f.db.type_alias_data(from_assoc_type_id(projection_ty.associated_ty_id)).name,
1004 WhereClause::AliasEq(_) => write!(f, "{{error}}")?,
1006 // FIXME implement these
1007 WhereClause::TypeOutlives(..) => {}
1008 WhereClause::LifetimeOutlives(..) => {}
1014 impl HirDisplay for LifetimeOutlives {
1015 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
1022 impl HirDisplay for Lifetime {
1023 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
1024 self.interned().hir_fmt(f)
1028 impl HirDisplay for LifetimeData {
1029 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
1031 LifetimeData::BoundVar(idx) => idx.hir_fmt(f),
1032 LifetimeData::InferenceVar(_) => write!(f, "_"),
1033 LifetimeData::Placeholder(idx) => {
1034 let id = lt_from_placeholder_idx(f.db, *idx);
1035 let generics = generics(f.db.upcast(), id.parent);
1036 let param_data = &generics.params.lifetimes[id.local_id];
1037 write!(f, "{}", param_data.name)
1039 LifetimeData::Static => write!(f, "'static"),
1040 LifetimeData::Empty(_) => Ok(()),
1041 LifetimeData::Erased => Ok(()),
1042 LifetimeData::Phantom(_, _) => Ok(()),
1047 impl HirDisplay for DomainGoal {
1048 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
1050 DomainGoal::Holds(wc) => {
1051 write!(f, "Holds(")?;
1055 _ => write!(f, "?")?,
1061 pub fn write_visibility(
1062 module_id: ModuleId,
1064 f: &mut HirFormatter<'_>,
1065 ) -> Result<(), HirDisplayError> {
1067 Visibility::Public => write!(f, "pub "),
1068 Visibility::Module(vis_id) => {
1069 let def_map = module_id.def_map(f.db.upcast());
1070 let root_module_id = def_map.module_id(def_map.root());
1071 if vis_id == module_id {
1072 // pub(self) or omitted
1074 } else if root_module_id == vis_id {
1075 write!(f, "pub(crate) ")
1076 } else if module_id.containing_module(f.db.upcast()) == Some(vis_id) {
1077 write!(f, "pub(super) ")
1079 write!(f, "pub(in ...) ")
1085 impl HirDisplay for TypeRef {
1086 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
1088 TypeRef::Never => write!(f, "!")?,
1089 TypeRef::Placeholder => write!(f, "_")?,
1090 TypeRef::Tuple(elems) => {
1092 f.write_joined(elems, ", ")?;
1093 if elems.len() == 1 {
1098 TypeRef::Path(path) => path.hir_fmt(f)?,
1099 TypeRef::RawPtr(inner, mutability) => {
1100 let mutability = match mutability {
1101 hir_def::type_ref::Mutability::Shared => "*const ",
1102 hir_def::type_ref::Mutability::Mut => "*mut ",
1104 write!(f, "{}", mutability)?;
1107 TypeRef::Reference(inner, lifetime, mutability) => {
1108 let mutability = match mutability {
1109 hir_def::type_ref::Mutability::Shared => "",
1110 hir_def::type_ref::Mutability::Mut => "mut ",
1113 if let Some(lifetime) = lifetime {
1114 write!(f, "{} ", lifetime.name)?;
1116 write!(f, "{}", mutability)?;
1119 TypeRef::Array(inner, len) => {
1122 write!(f, "; {}]", len)?;
1124 TypeRef::Slice(inner) => {
1129 TypeRef::Fn(parameters, is_varargs) => {
1130 // FIXME: Function pointer qualifiers.
1132 if let Some(((_, return_type), function_parameters)) = parameters.split_last() {
1133 for index in 0..function_parameters.len() {
1134 let (param_name, param_type) = &function_parameters[index];
1135 if let Some(name) = param_name {
1136 write!(f, "{}: ", name)?;
1139 param_type.hir_fmt(f)?;
1141 if index != function_parameters.len() - 1 {
1146 write!(f, "{}...", if parameters.len() == 1 { "" } else { ", " })?;
1149 match &return_type {
1150 TypeRef::Tuple(tup) if tup.is_empty() => {}
1153 return_type.hir_fmt(f)?;
1158 TypeRef::ImplTrait(bounds) => {
1159 write!(f, "impl ")?;
1160 f.write_joined(bounds, " + ")?;
1162 TypeRef::DynTrait(bounds) => {
1164 f.write_joined(bounds, " + ")?;
1166 TypeRef::Macro(macro_call) => {
1167 let macro_call = macro_call.to_node(f.db.upcast());
1168 let ctx = body::LowerCtx::with_hygiene(f.db.upcast(), &Hygiene::new_unhygienic());
1169 match macro_call.path() {
1170 Some(path) => match Path::from_src(path, &ctx) {
1171 Some(path) => path.hir_fmt(f)?,
1172 None => write!(f, "{{macro}}")?,
1174 None => write!(f, "{{macro}}")?,
1176 write!(f, "!(..)")?;
1178 TypeRef::Error => write!(f, "{{error}}")?,
1184 impl HirDisplay for TypeBound {
1185 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
1187 TypeBound::Path(path, modifier) => {
1189 TraitBoundModifier::None => (),
1190 TraitBoundModifier::Maybe => write!(f, "?")?,
1194 TypeBound::Lifetime(lifetime) => write!(f, "{}", lifetime.name),
1195 TypeBound::ForLifetime(lifetimes, path) => {
1196 write!(f, "for<{}> ", lifetimes.iter().format(", "))?;
1199 TypeBound::Error => write!(f, "{{error}}"),
1204 impl HirDisplay for Path {
1205 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
1206 match (self.type_anchor(), self.kind()) {
1207 (Some(anchor), _) => {
1212 (_, PathKind::Plain) => {}
1213 (_, PathKind::Abs) => {}
1214 (_, PathKind::Crate) => write!(f, "crate")?,
1215 (_, PathKind::Super(0)) => write!(f, "self")?,
1216 (_, PathKind::Super(n)) => {
1221 write!(f, "super")?;
1224 (_, PathKind::DollarCrate(id)) => {
1225 // Resolve `$crate` to the crate's display name.
1226 // FIXME: should use the dependency name instead if available, but that depends on
1227 // the crate invoking `HirDisplay`
1228 let crate_graph = f.db.crate_graph();
1229 let name = crate_graph[*id]
1232 .map(|name| name.canonical_name())
1233 .unwrap_or("$crate");
1234 write!(f, "{name}")?
1238 for (seg_idx, segment) in self.segments().iter().enumerate() {
1239 if !matches!(self.kind(), PathKind::Plain) || seg_idx > 0 {
1242 write!(f, "{}", segment.name)?;
1243 if let Some(generic_args) = segment.args_and_bindings {
1244 // We should be in type context, so format as `Foo<Bar>` instead of `Foo::<Bar>`.
1245 // Do we actually format expressions?
1246 if generic_args.desugared_from_fn {
1247 // First argument will be a tuple, which already includes the parentheses.
1248 // If the tuple only contains 1 item, write it manually to avoid the trailing `,`.
1249 if let hir_def::path::GenericArg::Type(TypeRef::Tuple(v)) =
1250 &generic_args.args[0]
1257 generic_args.args[0].hir_fmt(f)?;
1260 if let Some(ret) = &generic_args.bindings[0].type_ref {
1261 if !matches!(ret, TypeRef::Tuple(v) if v.is_empty()) {
1270 let mut first = true;
1271 for arg in &generic_args.args {
1274 if generic_args.has_self_type {
1275 // FIXME: Convert to `<Ty as Trait>` form.
1276 write!(f, "Self = ")?;
1283 for binding in &generic_args.bindings {
1289 write!(f, "{}", binding.name)?;
1290 match &binding.type_ref {
1297 f.write_joined(&binding.bounds, " + ")?;
1308 impl HirDisplay for hir_def::path::GenericArg {
1309 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
1311 hir_def::path::GenericArg::Type(ty) => ty.hir_fmt(f),
1312 hir_def::path::GenericArg::Const(c) => write!(f, "{}", c),
1313 hir_def::path::GenericArg::Lifetime(lifetime) => write!(f, "{}", lifetime.name),