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;
23 use smallvec::SmallVec;
28 from_assoc_type_id, from_foreign_def_id, from_placeholder_idx, lt_from_placeholder_idx,
30 primitive, to_assoc_type_id,
31 utils::{self, generics},
32 AdtId, AliasEq, AliasTy, Binders, CallableDefId, CallableSig, Const, ConstValue, DomainGoal,
33 GenericArg, ImplTraitId, Interner, Lifetime, LifetimeData, LifetimeOutlives, Mutability,
34 OpaqueTy, ProjectionTy, ProjectionTyExt, QuantifiedWhereClause, Scalar, Substitution, TraitRef,
35 TraitRefExt, Ty, TyExt, TyKind, WhereClause,
38 pub struct HirFormatter<'a> {
39 pub db: &'a dyn HirDatabase,
40 fmt: &'a mut dyn fmt::Write,
43 pub(crate) max_size: Option<usize>,
44 omit_verbose_types: bool,
45 display_target: DisplayTarget,
48 pub trait HirDisplay {
49 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError>;
51 /// Returns a `Display`able type that is human-readable.
52 fn into_displayable<'a>(
54 db: &'a dyn HirDatabase,
55 max_size: Option<usize>,
56 omit_verbose_types: bool,
57 display_target: DisplayTarget,
58 ) -> HirDisplayWrapper<'a, Self>
63 !matches!(display_target, DisplayTarget::SourceCode { .. }),
64 "HirDisplayWrapper cannot fail with DisplaySourceCodeError, use HirDisplay::hir_fmt directly instead"
66 HirDisplayWrapper { db, t: self, max_size, omit_verbose_types, display_target }
69 /// Returns a `Display`able type that is human-readable.
70 /// Use this for showing types to the user (e.g. diagnostics)
71 fn display<'a>(&'a self, db: &'a dyn HirDatabase) -> HirDisplayWrapper<'a, Self>
79 omit_verbose_types: false,
80 display_target: DisplayTarget::Diagnostics,
84 /// Returns a `Display`able type that is human-readable and tries to be succinct.
85 /// Use this for showing types to the user where space is constrained (e.g. doc popups)
86 fn display_truncated<'a>(
88 db: &'a dyn HirDatabase,
89 max_size: Option<usize>,
90 ) -> HirDisplayWrapper<'a, Self>
98 omit_verbose_types: true,
99 display_target: DisplayTarget::Diagnostics,
103 /// Returns a String representation of `self` that can be inserted into the given module.
104 /// Use this when generating code (e.g. assists)
105 fn display_source_code<'a>(
107 db: &'a dyn HirDatabase,
109 ) -> Result<String, DisplaySourceCodeError> {
110 let mut result = String::new();
111 match self.hir_fmt(&mut HirFormatter {
114 buf: String::with_capacity(20),
117 omit_verbose_types: false,
118 display_target: DisplayTarget::SourceCode { module_id },
121 Err(HirDisplayError::FmtError) => panic!("Writing to String can't fail!"),
122 Err(HirDisplayError::DisplaySourceCodeError(e)) => return Err(e),
127 /// Returns a String representation of `self` for test purposes
128 fn display_test<'a>(&'a self, db: &'a dyn HirDatabase) -> HirDisplayWrapper<'a, Self>
136 omit_verbose_types: false,
137 display_target: DisplayTarget::Test,
142 impl<'a> HirFormatter<'a> {
143 pub fn write_joined<T: HirDisplay>(
145 iter: impl IntoIterator<Item = T>,
147 ) -> Result<(), HirDisplayError> {
148 let mut first = true;
151 write!(self, "{}", sep)?;
155 // Abbreviate multiple omitted types with a single ellipsis.
156 if self.should_truncate() {
157 return write!(self, "{}", TYPE_HINT_TRUNCATION);
165 /// This allows using the `write!` macro directly with a `HirFormatter`.
166 pub fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> Result<(), HirDisplayError> {
167 // We write to a buffer first to track output size
169 fmt::write(&mut self.buf, args)?;
170 self.curr_size += self.buf.len();
172 // Then we write to the internal formatter from the buffer
173 self.fmt.write_str(&self.buf).map_err(HirDisplayError::from)
176 pub fn write_str(&mut self, s: &str) -> Result<(), HirDisplayError> {
177 self.fmt.write_str(s)?;
181 pub fn write_char(&mut self, c: char) -> Result<(), HirDisplayError> {
182 self.fmt.write_char(c)?;
186 pub fn should_truncate(&self) -> bool {
187 match self.max_size {
188 Some(max_size) => self.curr_size >= max_size,
193 pub fn omit_verbose_types(&self) -> bool {
194 self.omit_verbose_types
198 #[derive(Clone, Copy)]
199 pub enum DisplayTarget {
200 /// Display types for inlays, doc popups, autocompletion, etc...
201 /// Showing `{unknown}` or not qualifying paths is fine here.
202 /// There's no reason for this to fail.
204 /// Display types for inserting them in source files.
205 /// The generated code should compile, so paths need to be qualified.
206 SourceCode { module_id: ModuleId },
207 /// Only for test purpose to keep real types
212 fn is_source_code(&self) -> bool {
213 matches!(self, Self::SourceCode { .. })
215 fn is_test(&self) -> bool {
216 matches!(self, Self::Test)
221 pub enum DisplaySourceCodeError {
228 pub enum HirDisplayError {
229 /// Errors that can occur when generating source code
230 DisplaySourceCodeError(DisplaySourceCodeError),
231 /// `FmtError` is required to be compatible with std::fmt::Display
234 impl From<fmt::Error> for HirDisplayError {
235 fn from(_: fmt::Error) -> Self {
240 pub struct HirDisplayWrapper<'a, T> {
241 db: &'a dyn HirDatabase,
243 max_size: Option<usize>,
244 omit_verbose_types: bool,
245 display_target: DisplayTarget,
248 impl<'a, T> fmt::Display for HirDisplayWrapper<'a, T>
252 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
253 match self.t.hir_fmt(&mut HirFormatter {
256 buf: String::with_capacity(20),
258 max_size: self.max_size,
259 omit_verbose_types: self.omit_verbose_types,
260 display_target: self.display_target,
263 Err(HirDisplayError::FmtError) => Err(fmt::Error),
264 Err(HirDisplayError::DisplaySourceCodeError(_)) => {
265 // This should never happen
266 panic!("HirDisplay::hir_fmt failed with DisplaySourceCodeError when calling Display::fmt!")
272 const TYPE_HINT_TRUNCATION: &str = "…";
274 impl<T: HirDisplay> HirDisplay for &'_ T {
275 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
276 HirDisplay::hir_fmt(*self, f)
280 impl<T: HirDisplay + Internable> HirDisplay for Interned<T> {
281 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
282 HirDisplay::hir_fmt(self.as_ref(), f)
286 impl HirDisplay for ProjectionTy {
287 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
288 if f.should_truncate() {
289 return write!(f, "{}", TYPE_HINT_TRUNCATION);
292 let trait_ref = self.trait_ref(f.db);
294 fmt_trait_ref(&trait_ref, f, true)?;
295 write!(f, ">::{}", f.db.type_alias_data(from_assoc_type_id(self.associated_ty_id)).name)?;
296 let proj_params_count =
297 self.substitution.len(Interner) - trait_ref.substitution.len(Interner);
298 let proj_params = &self.substitution.as_slice(Interner)[..proj_params_count];
299 if !proj_params.is_empty() {
301 f.write_joined(proj_params, ", ")?;
308 impl HirDisplay for OpaqueTy {
309 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
310 if f.should_truncate() {
311 return write!(f, "{}", TYPE_HINT_TRUNCATION);
314 self.substitution.at(Interner, 0).hir_fmt(f)
318 impl HirDisplay for GenericArg {
319 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
320 match self.interned() {
321 crate::GenericArgData::Ty(ty) => ty.hir_fmt(f),
322 crate::GenericArgData::Lifetime(lt) => lt.hir_fmt(f),
323 crate::GenericArgData::Const(c) => c.hir_fmt(f),
328 impl HirDisplay for Const {
329 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
330 let data = self.interned();
332 ConstValue::BoundVar(idx) => idx.hir_fmt(f),
333 ConstValue::InferenceVar(..) => write!(f, "#c#"),
334 ConstValue::Placeholder(idx) => {
335 let id = from_placeholder_idx(f.db, idx);
336 let generics = generics(f.db.upcast(), id.parent);
337 let param_data = &generics.params.type_or_consts[id.local_id];
338 write!(f, "{}", param_data.name().unwrap())
340 ConstValue::Concrete(c) => write!(f, "{}", c.interned),
345 impl HirDisplay for BoundVar {
346 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
347 write!(f, "?{}.{}", self.debruijn.depth(), self.index)
351 impl HirDisplay for Ty {
352 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
353 if f.should_truncate() {
354 return write!(f, "{}", TYPE_HINT_TRUNCATION);
357 match self.kind(Interner) {
358 TyKind::Never => write!(f, "!")?,
359 TyKind::Str => write!(f, "str")?,
360 TyKind::Scalar(Scalar::Bool) => write!(f, "bool")?,
361 TyKind::Scalar(Scalar::Char) => write!(f, "char")?,
362 &TyKind::Scalar(Scalar::Float(t)) => write!(f, "{}", primitive::float_ty_to_string(t))?,
363 &TyKind::Scalar(Scalar::Int(t)) => write!(f, "{}", primitive::int_ty_to_string(t))?,
364 &TyKind::Scalar(Scalar::Uint(t)) => write!(f, "{}", primitive::uint_ty_to_string(t))?,
365 TyKind::Slice(t) => {
370 TyKind::Array(t, c) => {
377 TyKind::Raw(m, t) | TyKind::Ref(m, _, t) => {
378 if matches!(self.kind(Interner), TyKind::Raw(..)) {
383 Mutability::Not => "const ",
384 Mutability::Mut => "mut ",
392 Mutability::Not => "",
393 Mutability::Mut => "mut ",
398 // FIXME: all this just to decide whether to use parentheses...
399 let contains_impl_fn = |bounds: &[QuantifiedWhereClause]| {
400 bounds.iter().any(|bound| {
401 if let WhereClause::Implemented(trait_ref) = bound.skip_binders() {
402 let trait_ = trait_ref.hir_trait_id();
403 fn_traits(f.db.upcast(), trait_).any(|it| it == trait_)
409 let (preds_to_print, has_impl_fn_pred) = match t.kind(Interner) {
410 TyKind::Dyn(dyn_ty) if dyn_ty.bounds.skip_binders().interned().len() > 1 => {
411 let bounds = dyn_ty.bounds.skip_binders().interned();
412 (bounds.len(), contains_impl_fn(bounds))
414 TyKind::Alias(AliasTy::Opaque(OpaqueTy {
416 substitution: parameters,
418 | TyKind::OpaqueType(opaque_ty_id, parameters) => {
420 f.db.lookup_intern_impl_trait_id((*opaque_ty_id).into());
421 if let ImplTraitId::ReturnTypeImplTrait(func, idx) = impl_trait_id {
423 f.db.return_type_impl_traits(func)
424 .expect("impl trait id without data");
427 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
428 let bounds = data.substitute(Interner, parameters);
429 let mut len = bounds.skip_binders().len();
431 // Don't count Sized but count when it absent
432 // (i.e. when explicit ?Sized bound is set).
433 let default_sized = SizedByDefault::Sized {
434 anchor: func.lookup(f.db.upcast()).module(f.db.upcast()).krate(),
436 let sized_bounds = bounds
442 WhereClause::Implemented(trait_ref)
443 if default_sized.is_sized_trait(
444 trait_ref.hir_trait_id(),
453 len = len.saturating_sub(sized_bounds);
457 (len, contains_impl_fn(bounds.skip_binders()))
465 if has_impl_fn_pred && preds_to_print <= 2 {
469 if preds_to_print > 1 {
477 TyKind::Tuple(_, substs) => {
478 if substs.len(Interner) == 1 {
480 substs.at(Interner, 0).hir_fmt(f)?;
484 f.write_joined(&*substs.as_slice(Interner), ", ")?;
488 TyKind::Function(fn_ptr) => {
489 let sig = CallableSig::from_fn_ptr(fn_ptr);
492 TyKind::FnDef(def, parameters) => {
493 let def = from_chalk(f.db, *def);
494 let sig = f.db.callable_item_signature(def).substitute(Interner, parameters);
496 CallableDefId::FunctionId(ff) => {
497 write!(f, "fn {}", f.db.function_data(ff).name)?
499 CallableDefId::StructId(s) => write!(f, "{}", f.db.struct_data(s).name)?,
500 CallableDefId::EnumVariantId(e) => {
501 write!(f, "{}", f.db.enum_data(e.parent).variants[e.local_id].name)?
504 if parameters.len(Interner) > 0 {
505 let generics = generics(f.db.upcast(), def.into());
506 let (parent_params, self_param, type_params, const_params, _impl_trait_params) =
507 generics.provenance_split();
508 let total_len = parent_params + self_param + type_params + const_params;
509 // We print all params except implicit impl Trait params. Still a bit weird; should we leave out parent and self?
511 // `parameters` are in the order of fn's params (including impl traits),
512 // parent's params (those from enclosing impl or trait, if any).
513 let parameters = parameters.as_slice(Interner);
514 let fn_params_len = self_param + type_params + const_params;
515 let fn_params = parameters.get(..fn_params_len);
516 let parent_params = parameters.get(parameters.len() - parent_params..);
517 let params = parent_params.into_iter().chain(fn_params).flatten();
519 f.write_joined(params, ", ")?;
524 f.write_joined(sig.params(), ", ")?;
532 TyKind::Adt(AdtId(def_id), parameters) => {
533 match f.display_target {
534 DisplayTarget::Diagnostics | DisplayTarget::Test => {
535 let name = match *def_id {
536 hir_def::AdtId::StructId(it) => f.db.struct_data(it).name.clone(),
537 hir_def::AdtId::UnionId(it) => f.db.union_data(it).name.clone(),
538 hir_def::AdtId::EnumId(it) => f.db.enum_data(it).name.clone(),
540 write!(f, "{}", name)?;
542 DisplayTarget::SourceCode { module_id } => {
543 if let Some(path) = find_path::find_path(
545 ItemInNs::Types((*def_id).into()),
549 write!(f, "{}", path)?;
551 return Err(HirDisplayError::DisplaySourceCodeError(
552 DisplaySourceCodeError::PathNotFound,
558 if parameters.len(Interner) > 0 {
559 let parameters_to_write = if f.display_target.is_source_code()
560 || f.omit_verbose_types()
563 .as_generic_def(f.db)
564 .map(|generic_def_id| f.db.generic_defaults(generic_def_id))
565 .filter(|defaults| !defaults.is_empty())
567 None => parameters.as_slice(Interner),
568 Some(default_parameters) => {
570 parameter: &GenericArg,
571 default_parameters: &[Binders<GenericArg>],
573 parameters: &Substitution,
575 if parameter.ty(Interner).map(|x| x.kind(Interner))
576 == Some(&TyKind::Error)
580 if let Some(ConstValue::Concrete(c)) =
581 parameter.constant(Interner).map(|x| x.data(Interner).value)
583 if c.interned == ConstScalar::Unknown {
587 let default_parameter = match default_parameters.get(i) {
592 default_parameter.clone().substitute(Interner, ¶meters);
593 parameter != &actual_default
595 let mut default_from = 0;
596 for (i, parameter) in parameters.iter(Interner).enumerate() {
597 if should_show(parameter, &default_parameters, i, parameters) {
598 default_from = i + 1;
601 ¶meters.as_slice(Interner)[0..default_from]
605 parameters.as_slice(Interner)
607 if !parameters_to_write.is_empty() {
610 if f.display_target.is_source_code() {
611 let mut first = true;
612 for generic_arg in parameters_to_write {
618 if generic_arg.ty(Interner).map(|ty| ty.kind(Interner))
619 == Some(&TyKind::Error)
623 generic_arg.hir_fmt(f)?;
627 f.write_joined(parameters_to_write, ", ")?;
634 TyKind::AssociatedType(assoc_type_id, parameters) => {
635 let type_alias = from_assoc_type_id(*assoc_type_id);
636 let trait_ = match type_alias.lookup(f.db.upcast()).container {
637 ItemContainerId::TraitId(it) => it,
638 _ => panic!("not an associated type"),
640 let trait_ = f.db.trait_data(trait_);
641 let type_alias_data = f.db.type_alias_data(type_alias);
643 // Use placeholder associated types when the target is test (https://rust-lang.github.io/chalk/book/clauses/type_equality.html#placeholder-associated-types)
644 if f.display_target.is_test() {
645 write!(f, "{}::{}", trait_.name, type_alias_data.name)?;
646 // Note that the generic args for the associated type come before those for the
647 // trait (including the self type).
648 // FIXME: reconsider the generic args order upon formatting?
649 if parameters.len(Interner) > 0 {
651 f.write_joined(parameters.as_slice(Interner), ", ")?;
655 let projection_ty = ProjectionTy {
656 associated_ty_id: to_assoc_type_id(type_alias),
657 substitution: parameters.clone(),
660 projection_ty.hir_fmt(f)?;
663 TyKind::Foreign(type_alias) => {
664 let type_alias = f.db.type_alias_data(from_foreign_def_id(*type_alias));
665 write!(f, "{}", type_alias.name)?;
667 TyKind::OpaqueType(opaque_ty_id, parameters) => {
668 let impl_trait_id = f.db.lookup_intern_impl_trait_id((*opaque_ty_id).into());
669 match impl_trait_id {
670 ImplTraitId::ReturnTypeImplTrait(func, idx) => {
672 f.db.return_type_impl_traits(func).expect("impl trait id without data");
675 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
676 let bounds = data.substitute(Interner, ¶meters);
677 let krate = func.lookup(f.db.upcast()).module(f.db.upcast()).krate();
678 write_bounds_like_dyn_trait_with_prefix(
680 bounds.skip_binders(),
681 SizedByDefault::Sized { anchor: krate },
684 // FIXME: it would maybe be good to distinguish this from the alias type (when debug printing), and to show the substitution
686 ImplTraitId::AsyncBlockTypeImplTrait(..) => {
687 write!(f, "impl Future<Output = ")?;
688 parameters.at(Interner, 0).hir_fmt(f)?;
693 TyKind::Closure(.., substs) => {
694 if f.display_target.is_source_code() {
695 return Err(HirDisplayError::DisplaySourceCodeError(
696 DisplaySourceCodeError::Closure,
699 let sig = substs.at(Interner, 0).assert_ty_ref(Interner).callable_sig(f.db);
700 if let Some(sig) = sig {
701 if sig.params().is_empty() {
703 } else if f.should_truncate() {
704 write!(f, "|{}|", TYPE_HINT_TRUNCATION)?;
707 f.write_joined(sig.params(), ", ")?;
712 sig.ret().hir_fmt(f)?;
714 write!(f, "{{closure}}")?;
717 TyKind::Placeholder(idx) => {
718 let id = from_placeholder_idx(f.db, *idx);
719 let generics = generics(f.db.upcast(), id.parent);
720 let param_data = &generics.params.type_or_consts[id.local_id];
722 TypeOrConstParamData::TypeParamData(p) => match p.provenance {
723 TypeParamProvenance::TypeParamList | TypeParamProvenance::TraitSelf => {
724 write!(f, "{}", p.name.clone().unwrap_or_else(Name::missing))?
726 TypeParamProvenance::ArgumentImplTrait => {
727 let substs = generics.placeholder_subst(f.db);
729 f.db.generic_predicates(id.parent)
731 .map(|pred| pred.clone().substitute(Interner, &substs))
732 .filter(|wc| match &wc.skip_binders() {
733 WhereClause::Implemented(tr) => {
734 &tr.self_type_parameter(Interner) == self
736 WhereClause::AliasEq(AliasEq {
737 alias: AliasTy::Projection(proj),
739 }) => &proj.self_type_parameter(f.db) == self,
742 .collect::<Vec<_>>();
743 let krate = id.parent.module(f.db.upcast()).krate();
744 write_bounds_like_dyn_trait_with_prefix(
747 SizedByDefault::Sized { anchor: krate },
752 TypeOrConstParamData::ConstParamData(p) => {
753 write!(f, "{}", p.name)?;
757 TyKind::BoundVar(idx) => idx.hir_fmt(f)?,
758 TyKind::Dyn(dyn_ty) => {
759 // Reorder bounds to satisfy `write_bounds_like_dyn_trait()`'s expectation.
760 // FIXME: `Iterator::partition_in_place()` or `Vec::drain_filter()` may make it
761 // more efficient when either of them hits stable.
762 let mut bounds: SmallVec<[_; 4]> =
763 dyn_ty.bounds.skip_binders().iter(Interner).cloned().collect();
764 let (auto_traits, others): (SmallVec<[_; 4]>, _) =
765 bounds.drain(1..).partition(|b| b.skip_binders().trait_id().is_some());
766 bounds.extend(others);
767 bounds.extend(auto_traits);
769 write_bounds_like_dyn_trait_with_prefix(
772 SizedByDefault::NotSized,
776 TyKind::Alias(AliasTy::Projection(p_ty)) => p_ty.hir_fmt(f)?,
777 TyKind::Alias(AliasTy::Opaque(opaque_ty)) => {
778 let impl_trait_id = f.db.lookup_intern_impl_trait_id(opaque_ty.opaque_ty_id.into());
779 match impl_trait_id {
780 ImplTraitId::ReturnTypeImplTrait(func, idx) => {
782 f.db.return_type_impl_traits(func).expect("impl trait id without data");
785 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
786 let bounds = data.substitute(Interner, &opaque_ty.substitution);
787 let krate = func.lookup(f.db.upcast()).module(f.db.upcast()).krate();
788 write_bounds_like_dyn_trait_with_prefix(
790 bounds.skip_binders(),
791 SizedByDefault::Sized { anchor: krate },
795 ImplTraitId::AsyncBlockTypeImplTrait(..) => {
796 write!(f, "{{async block}}")?;
801 if f.display_target.is_source_code() {
802 return Err(HirDisplayError::DisplaySourceCodeError(
803 DisplaySourceCodeError::UnknownType,
806 write!(f, "{{unknown}}")?;
808 TyKind::InferenceVar(..) => write!(f, "_")?,
809 TyKind::Generator(_, subst) => {
810 if f.display_target.is_source_code() {
811 return Err(HirDisplayError::DisplaySourceCodeError(
812 DisplaySourceCodeError::Generator,
816 let subst = subst.as_slice(Interner);
817 let a: Option<SmallVec<[&Ty; 3]>> = subst
818 .get(subst.len() - 3..)
819 .map(|args| args.iter().map(|arg| arg.ty(Interner)).collect())
822 if let Some([resume_ty, yield_ty, ret_ty]) = a.as_deref() {
824 resume_ty.hir_fmt(f)?;
827 write!(f, " yields ")?;
828 yield_ty.hir_fmt(f)?;
833 // This *should* be unreachable, but fallback just in case.
834 write!(f, "{{generator}}")?;
837 TyKind::GeneratorWitness(..) => write!(f, "{{generator witness}}")?,
843 impl HirDisplay for CallableSig {
844 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
846 f.write_joined(self.params(), ", ")?;
848 if self.params().is_empty() {
855 let ret = self.ret();
864 fn fn_traits(db: &dyn DefDatabase, trait_: TraitId) -> impl Iterator<Item = TraitId> {
865 let krate = trait_.lookup(db).container.krate();
866 utils::fn_traits(db, krate)
869 #[derive(Clone, Copy, PartialEq, Eq)]
870 pub enum SizedByDefault {
872 Sized { anchor: CrateId },
875 impl SizedByDefault {
876 fn is_sized_trait(self, trait_: TraitId, db: &dyn DefDatabase) -> bool {
878 Self::NotSized => false,
879 Self::Sized { anchor } => {
881 .lang_item(anchor, SmolStr::new_inline("sized"))
882 .and_then(|lang_item| lang_item.as_trait());
883 Some(trait_) == sized_trait
889 pub fn write_bounds_like_dyn_trait_with_prefix(
891 predicates: &[QuantifiedWhereClause],
892 default_sized: SizedByDefault,
893 f: &mut HirFormatter<'_>,
894 ) -> Result<(), HirDisplayError> {
895 write!(f, "{}", prefix)?;
896 if !predicates.is_empty()
897 || predicates.is_empty() && matches!(default_sized, SizedByDefault::Sized { .. })
900 write_bounds_like_dyn_trait(predicates, default_sized, f)
906 fn write_bounds_like_dyn_trait(
907 predicates: &[QuantifiedWhereClause],
908 default_sized: SizedByDefault,
909 f: &mut HirFormatter<'_>,
910 ) -> Result<(), HirDisplayError> {
911 // Note: This code is written to produce nice results (i.e.
912 // corresponding to surface Rust) for types that can occur in
913 // actual Rust. It will have weird results if the predicates
914 // aren't as expected (i.e. self types = $0, projection
915 // predicates for a certain trait come after the Implemented
916 // predicate for that trait).
917 let mut first = true;
918 let mut angle_open = false;
919 let mut is_fn_trait = false;
920 let mut is_sized = false;
921 for p in predicates.iter() {
922 match p.skip_binders() {
923 WhereClause::Implemented(trait_ref) => {
924 let trait_ = trait_ref.hir_trait_id();
925 if default_sized.is_sized_trait(trait_, f.db.upcast()) {
927 if matches!(default_sized, SizedByDefault::Sized { .. }) {
928 // Don't print +Sized, but rather +?Sized if absent.
933 is_fn_trait = fn_traits(f.db.upcast(), trait_).any(|it| it == trait_);
935 if !is_fn_trait && angle_open {
942 // We assume that the self type is ^0.0 (i.e. the
943 // existential) here, which is the only thing that's
944 // possible in actual Rust, and hence don't print it
945 write!(f, "{}", f.db.trait_data(trait_).name)?;
946 if let [_, params @ ..] = &*trait_ref.substitution.as_slice(Interner) {
949 params.first().and_then(|it| it.assert_ty_ref(Interner).as_tuple())
952 f.write_joined(args.as_slice(Interner), ", ")?;
955 } else if !params.is_empty() {
957 f.write_joined(params, ", ")?;
958 // there might be assoc type bindings, so we leave the angle brackets open
963 WhereClause::AliasEq(alias_eq) if is_fn_trait => {
965 if !alias_eq.ty.is_unit() {
967 alias_eq.ty.hir_fmt(f)?;
970 WhereClause::AliasEq(AliasEq { ty, alias }) => {
971 // in types in actual Rust, these will always come
972 // after the corresponding Implemented predicate
979 if let AliasTy::Projection(proj) = alias {
980 let assoc_ty_id = from_assoc_type_id(proj.associated_ty_id);
981 let type_alias = f.db.type_alias_data(assoc_ty_id);
982 write!(f, "{}", type_alias.name)?;
984 let proj_arg_count = generics(f.db.upcast(), assoc_ty_id.into()).len_self();
985 if proj_arg_count > 0 {
988 &proj.substitution.as_slice(Interner)[..proj_arg_count],
998 // FIXME implement these
999 WhereClause::LifetimeOutlives(_) => {}
1000 WhereClause::TypeOutlives(_) => {}
1007 if matches!(default_sized, SizedByDefault::Sized { .. }) {
1009 write!(f, "{}?Sized", if first { "" } else { " + " })?;
1011 write!(f, "Sized")?;
1019 f: &mut HirFormatter<'_>,
1021 ) -> Result<(), HirDisplayError> {
1022 if f.should_truncate() {
1023 return write!(f, "{}", TYPE_HINT_TRUNCATION);
1026 tr.self_type_parameter(Interner).hir_fmt(f)?;
1032 write!(f, "{}", f.db.trait_data(tr.hir_trait_id()).name)?;
1033 if tr.substitution.len(Interner) > 1 {
1035 f.write_joined(&tr.substitution.as_slice(Interner)[1..], ", ")?;
1041 impl HirDisplay for TraitRef {
1042 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
1043 fmt_trait_ref(self, f, false)
1047 impl HirDisplay for WhereClause {
1048 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
1049 if f.should_truncate() {
1050 return write!(f, "{}", TYPE_HINT_TRUNCATION);
1054 WhereClause::Implemented(trait_ref) => trait_ref.hir_fmt(f)?,
1055 WhereClause::AliasEq(AliasEq { alias: AliasTy::Projection(projection_ty), ty }) => {
1057 fmt_trait_ref(&projection_ty.trait_ref(f.db), f, true)?;
1061 f.db.type_alias_data(from_assoc_type_id(projection_ty.associated_ty_id)).name,
1065 WhereClause::AliasEq(_) => write!(f, "{{error}}")?,
1067 // FIXME implement these
1068 WhereClause::TypeOutlives(..) => {}
1069 WhereClause::LifetimeOutlives(..) => {}
1075 impl HirDisplay for LifetimeOutlives {
1076 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
1083 impl HirDisplay for Lifetime {
1084 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
1085 self.interned().hir_fmt(f)
1089 impl HirDisplay for LifetimeData {
1090 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
1092 LifetimeData::BoundVar(idx) => idx.hir_fmt(f),
1093 LifetimeData::InferenceVar(_) => write!(f, "_"),
1094 LifetimeData::Placeholder(idx) => {
1095 let id = lt_from_placeholder_idx(f.db, *idx);
1096 let generics = generics(f.db.upcast(), id.parent);
1097 let param_data = &generics.params.lifetimes[id.local_id];
1098 write!(f, "{}", param_data.name)
1100 LifetimeData::Static => write!(f, "'static"),
1101 LifetimeData::Empty(_) => Ok(()),
1102 LifetimeData::Erased => Ok(()),
1103 LifetimeData::Phantom(_, _) => Ok(()),
1108 impl HirDisplay for DomainGoal {
1109 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
1111 DomainGoal::Holds(wc) => {
1112 write!(f, "Holds(")?;
1116 _ => write!(f, "?")?,
1122 pub fn write_visibility(
1123 module_id: ModuleId,
1125 f: &mut HirFormatter<'_>,
1126 ) -> Result<(), HirDisplayError> {
1128 Visibility::Public => write!(f, "pub "),
1129 Visibility::Module(vis_id) => {
1130 let def_map = module_id.def_map(f.db.upcast());
1131 let root_module_id = def_map.module_id(def_map.root());
1132 if vis_id == module_id {
1133 // pub(self) or omitted
1135 } else if root_module_id == vis_id {
1136 write!(f, "pub(crate) ")
1137 } else if module_id.containing_module(f.db.upcast()) == Some(vis_id) {
1138 write!(f, "pub(super) ")
1140 write!(f, "pub(in ...) ")
1146 impl HirDisplay for TypeRef {
1147 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
1149 TypeRef::Never => write!(f, "!")?,
1150 TypeRef::Placeholder => write!(f, "_")?,
1151 TypeRef::Tuple(elems) => {
1153 f.write_joined(elems, ", ")?;
1154 if elems.len() == 1 {
1159 TypeRef::Path(path) => path.hir_fmt(f)?,
1160 TypeRef::RawPtr(inner, mutability) => {
1161 let mutability = match mutability {
1162 hir_def::type_ref::Mutability::Shared => "*const ",
1163 hir_def::type_ref::Mutability::Mut => "*mut ",
1165 write!(f, "{}", mutability)?;
1168 TypeRef::Reference(inner, lifetime, mutability) => {
1169 let mutability = match mutability {
1170 hir_def::type_ref::Mutability::Shared => "",
1171 hir_def::type_ref::Mutability::Mut => "mut ",
1174 if let Some(lifetime) = lifetime {
1175 write!(f, "{} ", lifetime.name)?;
1177 write!(f, "{}", mutability)?;
1180 TypeRef::Array(inner, len) => {
1183 write!(f, "; {}]", len)?;
1185 TypeRef::Slice(inner) => {
1190 &TypeRef::Fn(ref parameters, is_varargs, is_unsafe) => {
1191 // FIXME: Function pointer qualifiers.
1193 write!(f, "unsafe ")?;
1196 if let Some(((_, return_type), function_parameters)) = parameters.split_last() {
1197 for index in 0..function_parameters.len() {
1198 let (param_name, param_type) = &function_parameters[index];
1199 if let Some(name) = param_name {
1200 write!(f, "{}: ", name)?;
1203 param_type.hir_fmt(f)?;
1205 if index != function_parameters.len() - 1 {
1210 write!(f, "{}...", if parameters.len() == 1 { "" } else { ", " })?;
1213 match &return_type {
1214 TypeRef::Tuple(tup) if tup.is_empty() => {}
1217 return_type.hir_fmt(f)?;
1222 TypeRef::ImplTrait(bounds) => {
1223 write!(f, "impl ")?;
1224 f.write_joined(bounds, " + ")?;
1226 TypeRef::DynTrait(bounds) => {
1228 f.write_joined(bounds, " + ")?;
1230 TypeRef::Macro(macro_call) => {
1231 let macro_call = macro_call.to_node(f.db.upcast());
1232 let ctx = body::LowerCtx::with_hygiene(f.db.upcast(), &Hygiene::new_unhygienic());
1233 match macro_call.path() {
1234 Some(path) => match Path::from_src(path, &ctx) {
1235 Some(path) => path.hir_fmt(f)?,
1236 None => write!(f, "{{macro}}")?,
1238 None => write!(f, "{{macro}}")?,
1240 write!(f, "!(..)")?;
1242 TypeRef::Error => write!(f, "{{error}}")?,
1248 impl HirDisplay for TypeBound {
1249 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
1251 TypeBound::Path(path, modifier) => {
1253 TraitBoundModifier::None => (),
1254 TraitBoundModifier::Maybe => write!(f, "?")?,
1258 TypeBound::Lifetime(lifetime) => write!(f, "{}", lifetime.name),
1259 TypeBound::ForLifetime(lifetimes, path) => {
1260 write!(f, "for<{}> ", lifetimes.iter().format(", "))?;
1263 TypeBound::Error => write!(f, "{{error}}"),
1268 impl HirDisplay for Path {
1269 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
1270 match (self.type_anchor(), self.kind()) {
1271 (Some(anchor), _) => {
1276 (_, PathKind::Plain) => {}
1277 (_, PathKind::Abs) => {}
1278 (_, PathKind::Crate) => write!(f, "crate")?,
1279 (_, PathKind::Super(0)) => write!(f, "self")?,
1280 (_, PathKind::Super(n)) => {
1285 write!(f, "super")?;
1288 (_, PathKind::DollarCrate(id)) => {
1289 // Resolve `$crate` to the crate's display name.
1290 // FIXME: should use the dependency name instead if available, but that depends on
1291 // the crate invoking `HirDisplay`
1292 let crate_graph = f.db.crate_graph();
1293 let name = crate_graph[*id]
1296 .map(|name| name.canonical_name())
1297 .unwrap_or("$crate");
1298 write!(f, "{name}")?
1302 for (seg_idx, segment) in self.segments().iter().enumerate() {
1303 if !matches!(self.kind(), PathKind::Plain) || seg_idx > 0 {
1306 write!(f, "{}", segment.name)?;
1307 if let Some(generic_args) = segment.args_and_bindings {
1308 // We should be in type context, so format as `Foo<Bar>` instead of `Foo::<Bar>`.
1309 // Do we actually format expressions?
1310 if generic_args.desugared_from_fn {
1311 // First argument will be a tuple, which already includes the parentheses.
1312 // If the tuple only contains 1 item, write it manually to avoid the trailing `,`.
1313 if let hir_def::path::GenericArg::Type(TypeRef::Tuple(v)) =
1314 &generic_args.args[0]
1321 generic_args.args[0].hir_fmt(f)?;
1324 if let Some(ret) = &generic_args.bindings[0].type_ref {
1325 if !matches!(ret, TypeRef::Tuple(v) if v.is_empty()) {
1334 let mut first = true;
1335 for arg in &generic_args.args {
1338 if generic_args.has_self_type {
1339 // FIXME: Convert to `<Ty as Trait>` form.
1340 write!(f, "Self = ")?;
1347 for binding in &generic_args.bindings {
1353 write!(f, "{}", binding.name)?;
1354 match &binding.type_ref {
1361 f.write_joined(&binding.bounds, " + ")?;
1372 impl HirDisplay for hir_def::path::GenericArg {
1373 fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
1375 hir_def::path::GenericArg::Type(ty) => ty.hir_fmt(f),
1376 hir_def::path::GenericArg::Const(c) => write!(f, "{}", c),
1377 hir_def::path::GenericArg::Lifetime(lifetime) => write!(f, "{}", lifetime.name),