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::TypeParamProvenance,
14 intern::{Internable, Interned},
16 path::{Path, PathKind},
17 type_ref::{TraitBoundModifier, TypeBound, TypeRef},
18 visibility::Visibility,
19 HasModule, ItemContainerId, Lookup, ModuleId, TraitId,
21 use hir_expand::{hygiene::Hygiene, name::Name};
22 use itertools::Itertools;
25 const_from_placeholder_idx,
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, CallableDefId, CallableSig, Const, ConstValue, DomainGoal, GenericArg,
32 ImplTraitId, Interner, Lifetime, LifetimeData, LifetimeOutlives, Mutability, OpaqueTy,
33 ProjectionTy, ProjectionTyExt, QuantifiedWhereClause, Scalar, TraitRef, TraitRefExt, Ty, TyExt,
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)?;
158 /// This allows using the `write!` macro directly with a `HirFormatter`.
159 pub fn write_fmt(&mut self, args: fmt::Arguments) -> Result<(), HirDisplayError> {
160 // We write to a buffer first to track output size
162 fmt::write(&mut self.buf, args)?;
163 self.curr_size += self.buf.len();
165 // Then we write to the internal formatter from the buffer
166 self.fmt.write_str(&self.buf).map_err(HirDisplayError::from)
169 pub fn should_truncate(&self) -> bool {
170 match self.max_size {
171 Some(max_size) => 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...
379 let contains_impl_fn = |bounds: &[QuantifiedWhereClause]| {
380 bounds.iter().any(|bound| {
381 if let WhereClause::Implemented(trait_ref) = bound.skip_binders() {
382 let trait_ = trait_ref.hir_trait_id();
383 fn_traits(f.db.upcast(), trait_).any(|it| it == trait_)
389 let (preds_to_print, has_impl_fn_pred) = match t.kind(&Interner) {
390 TyKind::Dyn(dyn_ty) if dyn_ty.bounds.skip_binders().interned().len() > 1 => {
391 let bounds = dyn_ty.bounds.skip_binders().interned();
392 (bounds.len(), contains_impl_fn(bounds))
394 TyKind::Alias(AliasTy::Opaque(OpaqueTy {
396 substitution: parameters,
398 | TyKind::OpaqueType(opaque_ty_id, parameters) => {
400 f.db.lookup_intern_impl_trait_id((*opaque_ty_id).into());
401 if let ImplTraitId::ReturnTypeImplTrait(func, idx) = impl_trait_id {
403 f.db.return_type_impl_traits(func)
404 .expect("impl trait id without data");
407 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
408 let bounds = data.substitute(&Interner, parameters);
409 let mut len = bounds.skip_binders().len();
411 // Don't count Sized but count when it absent
412 // (i.e. when explicit ?Sized bound is set).
413 let default_sized = SizedByDefault::Sized {
414 anchor: func.lookup(f.db.upcast()).module(f.db.upcast()).krate(),
416 let sized_bounds = bounds
422 WhereClause::Implemented(trait_ref)
423 if default_sized.is_sized_trait(
424 trait_ref.hir_trait_id(),
433 len = len.saturating_sub(sized_bounds);
437 (len, contains_impl_fn(bounds.skip_binders()))
445 if has_impl_fn_pred && preds_to_print <= 2 {
449 if preds_to_print > 1 {
457 TyKind::Tuple(_, substs) => {
458 if substs.len(&Interner) == 1 {
460 substs.at(&Interner, 0).hir_fmt(f)?;
464 f.write_joined(&*substs.as_slice(&Interner), ", ")?;
468 TyKind::Function(fn_ptr) => {
469 let sig = CallableSig::from_fn_ptr(fn_ptr);
472 TyKind::FnDef(def, parameters) => {
473 let def = from_chalk(f.db, *def);
474 let sig = f.db.callable_item_signature(def).substitute(&Interner, parameters);
476 CallableDefId::FunctionId(ff) => {
477 write!(f, "fn {}", f.db.function_data(ff).name)?
479 CallableDefId::StructId(s) => write!(f, "{}", f.db.struct_data(s).name)?,
480 CallableDefId::EnumVariantId(e) => {
481 write!(f, "{}", f.db.enum_data(e.parent).variants[e.local_id].name)?
484 if parameters.len(&Interner) > 0 {
485 let generics = generics(f.db.upcast(), def.into());
486 let (parent_params, self_param, type_params, _impl_trait_params) =
487 generics.provenance_split();
488 let total_len = parent_params + self_param + type_params;
489 // We print all params except implicit impl Trait params. Still a bit weird; should we leave out parent and self?
492 f.write_joined(¶meters.as_slice(&Interner)[..total_len], ", ")?;
497 f.write_joined(sig.params(), ", ")?;
505 TyKind::Adt(AdtId(def_id), parameters) => {
506 match f.display_target {
507 DisplayTarget::Diagnostics | DisplayTarget::Test => {
508 let name = match *def_id {
509 hir_def::AdtId::StructId(it) => f.db.struct_data(it).name.clone(),
510 hir_def::AdtId::UnionId(it) => f.db.union_data(it).name.clone(),
511 hir_def::AdtId::EnumId(it) => f.db.enum_data(it).name.clone(),
513 write!(f, "{}", name)?;
515 DisplayTarget::SourceCode { module_id } => {
516 if let Some(path) = find_path::find_path(
518 ItemInNs::Types((*def_id).into()),
521 write!(f, "{}", path)?;
523 return Err(HirDisplayError::DisplaySourceCodeError(
524 DisplaySourceCodeError::PathNotFound,
530 if parameters.len(&Interner) > 0 {
531 let parameters_to_write = if f.display_target.is_source_code()
532 || f.omit_verbose_types()
535 .as_generic_def(f.db)
536 .map(|generic_def_id| f.db.generic_defaults(generic_def_id))
537 .filter(|defaults| !defaults.is_empty())
539 None => parameters.as_slice(&Interner),
540 Some(default_parameters) => {
541 let mut default_from = 0;
542 for (i, parameter) in parameters.iter(&Interner).enumerate() {
544 parameter.assert_ty_ref(&Interner).kind(&Interner),
545 default_parameters.get(i),
547 (&TyKind::Error, _) | (_, None) => {
548 default_from = i + 1;
550 (_, Some(default_parameter)) => {
552 default_parameter.clone().substitute(
554 &subst_prefix(parameters, i),
556 if parameter.assert_ty_ref(&Interner) != &actual_default
558 default_from = i + 1;
563 ¶meters.as_slice(&Interner)[0..default_from]
567 parameters.as_slice(&Interner)
569 if !parameters_to_write.is_empty() {
571 f.write_joined(parameters_to_write, ", ")?;
576 TyKind::AssociatedType(assoc_type_id, parameters) => {
577 let type_alias = from_assoc_type_id(*assoc_type_id);
578 let trait_ = match type_alias.lookup(f.db.upcast()).container {
579 ItemContainerId::TraitId(it) => it,
580 _ => panic!("not an associated type"),
582 let trait_ = f.db.trait_data(trait_);
583 let type_alias_data = f.db.type_alias_data(type_alias);
585 // Use placeholder associated types when the target is test (https://rust-lang.github.io/chalk/book/clauses/type_equality.html#placeholder-associated-types)
586 if f.display_target.is_test() {
587 write!(f, "{}::{}", trait_.name, type_alias_data.name)?;
588 if parameters.len(&Interner) > 0 {
590 f.write_joined(&*parameters.as_slice(&Interner), ", ")?;
594 let projection_ty = ProjectionTy {
595 associated_ty_id: to_assoc_type_id(type_alias),
596 substitution: parameters.clone(),
599 projection_ty.hir_fmt(f)?;
602 TyKind::Foreign(type_alias) => {
603 let type_alias = f.db.type_alias_data(from_foreign_def_id(*type_alias));
604 write!(f, "{}", type_alias.name)?;
606 TyKind::OpaqueType(opaque_ty_id, parameters) => {
607 let impl_trait_id = f.db.lookup_intern_impl_trait_id((*opaque_ty_id).into());
608 match impl_trait_id {
609 ImplTraitId::ReturnTypeImplTrait(func, idx) => {
611 f.db.return_type_impl_traits(func).expect("impl trait id without data");
614 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
615 let bounds = data.substitute(&Interner, ¶meters);
616 let krate = func.lookup(f.db.upcast()).module(f.db.upcast()).krate();
617 write_bounds_like_dyn_trait_with_prefix(
619 bounds.skip_binders(),
620 SizedByDefault::Sized { anchor: krate },
623 // FIXME: it would maybe be good to distinguish this from the alias type (when debug printing), and to show the substitution
625 ImplTraitId::AsyncBlockTypeImplTrait(..) => {
626 write!(f, "impl Future<Output = ")?;
627 parameters.at(&Interner, 0).hir_fmt(f)?;
632 TyKind::Closure(.., substs) => {
633 if f.display_target.is_source_code() {
634 return Err(HirDisplayError::DisplaySourceCodeError(
635 DisplaySourceCodeError::Closure,
638 let sig = substs.at(&Interner, 0).assert_ty_ref(&Interner).callable_sig(f.db);
639 if let Some(sig) = sig {
640 if sig.params().is_empty() {
642 } else if f.should_truncate() {
643 write!(f, "|{}|", TYPE_HINT_TRUNCATION)?;
646 f.write_joined(sig.params(), ", ")?;
651 sig.ret().hir_fmt(f)?;
653 write!(f, "{{closure}}")?;
656 TyKind::Placeholder(idx) => {
657 let id = from_placeholder_idx(f.db, *idx);
658 let generics = generics(f.db.upcast(), id.parent);
659 let param_data = &generics.params.types[id.local_id];
660 match param_data.provenance {
661 TypeParamProvenance::TypeParamList | TypeParamProvenance::TraitSelf => {
662 write!(f, "{}", param_data.name.clone().unwrap_or_else(Name::missing))?
664 TypeParamProvenance::ArgumentImplTrait => {
665 let substs = generics.type_params_subst(f.db);
667 f.db.generic_predicates(id.parent)
669 .map(|pred| pred.clone().substitute(&Interner, &substs))
670 .filter(|wc| match &wc.skip_binders() {
671 WhereClause::Implemented(tr) => {
672 &tr.self_type_parameter(&Interner) == self
674 WhereClause::AliasEq(AliasEq {
675 alias: AliasTy::Projection(proj),
677 }) => &proj.self_type_parameter(&Interner) == self,
680 .collect::<Vec<_>>();
681 let krate = id.parent.module(f.db.upcast()).krate();
682 write_bounds_like_dyn_trait_with_prefix(
685 SizedByDefault::Sized { anchor: krate },
691 TyKind::BoundVar(idx) => idx.hir_fmt(f)?,
692 TyKind::Dyn(dyn_ty) => {
693 write_bounds_like_dyn_trait_with_prefix(
695 dyn_ty.bounds.skip_binders().interned(),
696 SizedByDefault::NotSized,
700 TyKind::Alias(AliasTy::Projection(p_ty)) => p_ty.hir_fmt(f)?,
701 TyKind::Alias(AliasTy::Opaque(opaque_ty)) => {
702 let impl_trait_id = f.db.lookup_intern_impl_trait_id(opaque_ty.opaque_ty_id.into());
703 match impl_trait_id {
704 ImplTraitId::ReturnTypeImplTrait(func, idx) => {
706 f.db.return_type_impl_traits(func).expect("impl trait id without data");
709 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
710 let bounds = data.substitute(&Interner, &opaque_ty.substitution);
711 let krate = func.lookup(f.db.upcast()).module(f.db.upcast()).krate();
712 write_bounds_like_dyn_trait_with_prefix(
714 bounds.skip_binders(),
715 SizedByDefault::Sized { anchor: krate },
719 ImplTraitId::AsyncBlockTypeImplTrait(..) => {
720 write!(f, "{{async block}}")?;
725 if f.display_target.is_source_code() {
726 return Err(HirDisplayError::DisplaySourceCodeError(
727 DisplaySourceCodeError::UnknownType,
730 write!(f, "{{unknown}}")?;
732 TyKind::InferenceVar(..) => write!(f, "_")?,
733 TyKind::Generator(..) => write!(f, "{{generator}}")?,
734 TyKind::GeneratorWitness(..) => write!(f, "{{generator witness}}")?,
740 impl HirDisplay for CallableSig {
741 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
743 f.write_joined(self.params(), ", ")?;
745 if self.params().is_empty() {
752 let ret = self.ret();
761 fn fn_traits(db: &dyn DefDatabase, trait_: TraitId) -> impl Iterator<Item = TraitId> {
762 let krate = trait_.lookup(db).container.krate();
763 utils::fn_traits(db, krate)
766 #[derive(Clone, Copy, PartialEq, Eq)]
767 pub enum SizedByDefault {
769 Sized { anchor: CrateId },
772 impl SizedByDefault {
773 fn is_sized_trait(self, trait_: TraitId, db: &dyn DefDatabase) -> bool {
775 Self::NotSized => false,
776 Self::Sized { anchor } => {
778 db.lang_item(anchor, "sized".into()).and_then(|lang_item| lang_item.as_trait());
779 Some(trait_) == sized_trait
785 pub fn write_bounds_like_dyn_trait_with_prefix(
787 predicates: &[QuantifiedWhereClause],
788 default_sized: SizedByDefault,
789 f: &mut HirFormatter,
790 ) -> Result<(), HirDisplayError> {
791 write!(f, "{}", prefix)?;
792 if !predicates.is_empty()
793 || predicates.is_empty() && matches!(default_sized, SizedByDefault::Sized { .. })
796 write_bounds_like_dyn_trait(predicates, default_sized, f)
802 fn write_bounds_like_dyn_trait(
803 predicates: &[QuantifiedWhereClause],
804 default_sized: SizedByDefault,
805 f: &mut HirFormatter,
806 ) -> Result<(), HirDisplayError> {
807 // Note: This code is written to produce nice results (i.e.
808 // corresponding to surface Rust) for types that can occur in
809 // actual Rust. It will have weird results if the predicates
810 // aren't as expected (i.e. self types = $0, projection
811 // predicates for a certain trait come after the Implemented
812 // predicate for that trait).
813 let mut first = true;
814 let mut angle_open = false;
815 let mut is_fn_trait = false;
816 let mut is_sized = false;
817 for p in predicates.iter() {
818 match p.skip_binders() {
819 WhereClause::Implemented(trait_ref) => {
820 let trait_ = trait_ref.hir_trait_id();
821 if default_sized.is_sized_trait(trait_, f.db.upcast()) {
823 if matches!(default_sized, SizedByDefault::Sized { .. }) {
824 // Don't print +Sized, but rather +?Sized if absent.
829 is_fn_trait = fn_traits(f.db.upcast(), trait_).any(|it| it == trait_);
831 if !is_fn_trait && angle_open {
838 // We assume that the self type is ^0.0 (i.e. the
839 // existential) here, which is the only thing that's
840 // possible in actual Rust, and hence don't print it
841 write!(f, "{}", f.db.trait_data(trait_).name)?;
842 if let [_, params @ ..] = &*trait_ref.substitution.as_slice(&Interner) {
845 params.first().and_then(|it| it.assert_ty_ref(&Interner).as_tuple())
848 f.write_joined(args.as_slice(&Interner), ", ")?;
851 } else if !params.is_empty() {
853 f.write_joined(params, ", ")?;
854 // there might be assoc type bindings, so we leave the angle brackets open
859 WhereClause::AliasEq(alias_eq) if is_fn_trait => {
861 if !alias_eq.ty.is_unit() {
863 alias_eq.ty.hir_fmt(f)?;
866 WhereClause::AliasEq(AliasEq { ty, alias }) => {
867 // in types in actual Rust, these will always come
868 // after the corresponding Implemented predicate
875 if let AliasTy::Projection(proj) = alias {
877 f.db.type_alias_data(from_assoc_type_id(proj.associated_ty_id));
878 write!(f, "{} = ", type_alias.name)?;
883 // FIXME implement these
884 WhereClause::LifetimeOutlives(_) => {}
885 WhereClause::TypeOutlives(_) => {}
892 if matches!(default_sized, SizedByDefault::Sized { .. }) {
894 write!(f, "{}?Sized", if first { "" } else { " + " })?;
902 fn fmt_trait_ref(tr: &TraitRef, f: &mut HirFormatter, use_as: bool) -> Result<(), HirDisplayError> {
903 if f.should_truncate() {
904 return write!(f, "{}", TYPE_HINT_TRUNCATION);
907 tr.self_type_parameter(&Interner).hir_fmt(f)?;
913 write!(f, "{}", f.db.trait_data(tr.hir_trait_id()).name)?;
914 if tr.substitution.len(&Interner) > 1 {
916 f.write_joined(&tr.substitution.as_slice(&Interner)[1..], ", ")?;
922 impl HirDisplay for TraitRef {
923 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
924 fmt_trait_ref(self, f, false)
928 impl HirDisplay for WhereClause {
929 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
930 if f.should_truncate() {
931 return write!(f, "{}", TYPE_HINT_TRUNCATION);
935 WhereClause::Implemented(trait_ref) => trait_ref.hir_fmt(f)?,
936 WhereClause::AliasEq(AliasEq { alias: AliasTy::Projection(projection_ty), ty }) => {
938 fmt_trait_ref(&projection_ty.trait_ref(f.db), f, true)?;
942 f.db.type_alias_data(from_assoc_type_id(projection_ty.associated_ty_id)).name,
946 WhereClause::AliasEq(_) => write!(f, "{{error}}")?,
948 // FIXME implement these
949 WhereClause::TypeOutlives(..) => {}
950 WhereClause::LifetimeOutlives(..) => {}
956 impl HirDisplay for LifetimeOutlives {
957 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
964 impl HirDisplay for Lifetime {
965 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
966 self.interned().hir_fmt(f)
970 impl HirDisplay for LifetimeData {
971 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
973 LifetimeData::BoundVar(idx) => idx.hir_fmt(f),
974 LifetimeData::InferenceVar(_) => write!(f, "_"),
975 LifetimeData::Placeholder(idx) => {
976 let id = lt_from_placeholder_idx(f.db, *idx);
977 let generics = generics(f.db.upcast(), id.parent);
978 let param_data = &generics.params.lifetimes[id.local_id];
979 write!(f, "{}", param_data.name)
981 LifetimeData::Static => write!(f, "'static"),
982 LifetimeData::Empty(_) => Ok(()),
983 LifetimeData::Erased => Ok(()),
984 LifetimeData::Phantom(_, _) => Ok(()),
989 impl HirDisplay for DomainGoal {
990 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
992 DomainGoal::Holds(wc) => {
993 write!(f, "Holds(")?;
997 _ => write!(f, "?")?,
1003 pub fn write_visibility(
1004 module_id: ModuleId,
1006 f: &mut HirFormatter,
1007 ) -> Result<(), HirDisplayError> {
1009 Visibility::Public => write!(f, "pub "),
1010 Visibility::Module(vis_id) => {
1011 let def_map = module_id.def_map(f.db.upcast());
1012 let root_module_id = def_map.module_id(def_map.root());
1013 if vis_id == module_id {
1014 // pub(self) or omitted
1016 } else if root_module_id == vis_id {
1017 write!(f, "pub(crate) ")
1018 } else if module_id.containing_module(f.db.upcast()) == Some(vis_id) {
1019 write!(f, "pub(super) ")
1021 write!(f, "pub(in ...) ")
1027 impl HirDisplay for TypeRef {
1028 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1030 TypeRef::Never => write!(f, "!")?,
1031 TypeRef::Placeholder => write!(f, "_")?,
1032 TypeRef::Tuple(elems) => {
1034 f.write_joined(elems, ", ")?;
1035 if elems.len() == 1 {
1040 TypeRef::Path(path) => path.hir_fmt(f)?,
1041 TypeRef::RawPtr(inner, mutability) => {
1042 let mutability = match mutability {
1043 hir_def::type_ref::Mutability::Shared => "*const ",
1044 hir_def::type_ref::Mutability::Mut => "*mut ",
1046 write!(f, "{}", mutability)?;
1049 TypeRef::Reference(inner, lifetime, mutability) => {
1050 let mutability = match mutability {
1051 hir_def::type_ref::Mutability::Shared => "",
1052 hir_def::type_ref::Mutability::Mut => "mut ",
1055 if let Some(lifetime) = lifetime {
1056 write!(f, "{} ", lifetime.name)?;
1058 write!(f, "{}", mutability)?;
1061 TypeRef::Array(inner, len) => {
1064 write!(f, "; {}]", len)?;
1066 TypeRef::Slice(inner) => {
1071 TypeRef::Fn(tys, is_varargs) => {
1072 // FIXME: Function pointer qualifiers.
1074 f.write_joined(&tys[..tys.len() - 1], ", ")?;
1076 write!(f, "{}...", if tys.len() == 1 { "" } else { ", " })?;
1079 let ret_ty = tys.last().unwrap();
1081 TypeRef::Tuple(tup) if tup.is_empty() => {}
1088 TypeRef::ImplTrait(bounds) => {
1089 write!(f, "impl ")?;
1090 f.write_joined(bounds, " + ")?;
1092 TypeRef::DynTrait(bounds) => {
1094 f.write_joined(bounds, " + ")?;
1096 TypeRef::Macro(macro_call) => {
1097 let macro_call = macro_call.to_node(f.db.upcast());
1098 let ctx = body::LowerCtx::with_hygiene(f.db.upcast(), &Hygiene::new_unhygienic());
1099 match macro_call.path() {
1100 Some(path) => match Path::from_src(path, &ctx) {
1101 Some(path) => path.hir_fmt(f)?,
1102 None => write!(f, "{{macro}}")?,
1104 None => write!(f, "{{macro}}")?,
1106 write!(f, "!(..)")?;
1108 TypeRef::Error => write!(f, "{{error}}")?,
1114 impl HirDisplay for TypeBound {
1115 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1117 TypeBound::Path(path, modifier) => {
1119 TraitBoundModifier::None => (),
1120 TraitBoundModifier::Maybe => write!(f, "?")?,
1124 TypeBound::Lifetime(lifetime) => write!(f, "{}", lifetime.name),
1125 TypeBound::ForLifetime(lifetimes, path) => {
1126 write!(f, "for<{}> ", lifetimes.iter().format(", "))?;
1129 TypeBound::Error => write!(f, "{{error}}"),
1134 impl HirDisplay for Path {
1135 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1136 match (self.type_anchor(), self.kind()) {
1137 (Some(anchor), _) => {
1142 (_, PathKind::Plain) => {}
1143 (_, PathKind::Abs) => {}
1144 (_, PathKind::Crate) => write!(f, "crate")?,
1145 (_, PathKind::Super(0)) => write!(f, "self")?,
1146 (_, PathKind::Super(n)) => {
1151 write!(f, "super")?;
1154 (_, PathKind::DollarCrate(_)) => write!(f, "{{extern_crate}}")?,
1157 for (seg_idx, segment) in self.segments().iter().enumerate() {
1158 if !matches!(self.kind(), PathKind::Plain) || seg_idx > 0 {
1161 write!(f, "{}", segment.name)?;
1162 if let Some(generic_args) = segment.args_and_bindings {
1163 // We should be in type context, so format as `Foo<Bar>` instead of `Foo::<Bar>`.
1164 // Do we actually format expressions?
1165 if generic_args.desugared_from_fn {
1166 // First argument will be a tuple, which already includes the parentheses.
1167 // If the tuple only contains 1 item, write it manually to avoid the trailing `,`.
1168 if let hir_def::path::GenericArg::Type(TypeRef::Tuple(v)) =
1169 &generic_args.args[0]
1176 generic_args.args[0].hir_fmt(f)?;
1179 if let Some(ret) = &generic_args.bindings[0].type_ref {
1180 if !matches!(ret, TypeRef::Tuple(v) if v.is_empty()) {
1189 let mut first = true;
1190 for arg in &generic_args.args {
1193 if generic_args.has_self_type {
1194 // FIXME: Convert to `<Ty as Trait>` form.
1195 write!(f, "Self = ")?;
1202 for binding in &generic_args.bindings {
1208 write!(f, "{}", binding.name)?;
1209 match &binding.type_ref {
1216 f.write_joined(&binding.bounds, " + ")?;
1227 impl HirDisplay for hir_def::path::GenericArg {
1228 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1230 hir_def::path::GenericArg::Type(ty) => ty.hir_fmt(f),
1231 hir_def::path::GenericArg::Lifetime(lifetime) => write!(f, "{}", lifetime.name),