1 //! FIXME: write short doc here
11 generics::TypeParamProvenance,
13 path::{Path, PathKind},
14 type_ref::{TypeBound, TypeRef},
15 visibility::Visibility,
16 AssocContainerId, Lookup, ModuleId, TraitId,
18 use hir_expand::name::Name;
21 db::HirDatabase, from_assoc_type_id, from_foreign_def_id, from_placeholder_idx,
22 lt_from_placeholder_idx, primitive, to_assoc_type_id, traits::chalk::from_chalk,
23 utils::generics, AdtId, AliasEq, AliasTy, CallableDefId, CallableSig, DomainGoal, GenericArg,
24 ImplTraitId, Interner, Lifetime, LifetimeData, LifetimeOutlives, Mutability, OpaqueTy,
25 ProjectionTy, ProjectionTyExt, QuantifiedWhereClause, Scalar, TraitRef, Ty, TyExt, TyKind,
29 pub struct HirFormatter<'a> {
30 pub db: &'a dyn HirDatabase,
31 fmt: &'a mut dyn fmt::Write,
34 pub(crate) max_size: Option<usize>,
35 omit_verbose_types: bool,
36 display_target: DisplayTarget,
39 pub trait HirDisplay {
40 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError>;
42 /// Returns a `Display`able type that is human-readable.
43 fn into_displayable<'a>(
45 db: &'a dyn HirDatabase,
46 max_size: Option<usize>,
47 omit_verbose_types: bool,
48 display_target: DisplayTarget,
49 ) -> HirDisplayWrapper<'a, Self>
53 HirDisplayWrapper { db, t: self, max_size, omit_verbose_types, display_target }
56 /// Returns a `Display`able type that is human-readable.
57 /// Use this for showing types to the user (e.g. diagnostics)
58 fn display<'a>(&'a self, db: &'a dyn HirDatabase) -> HirDisplayWrapper<'a, Self>
66 omit_verbose_types: false,
67 display_target: DisplayTarget::Diagnostics,
71 /// Returns a `Display`able type that is human-readable and tries to be succinct.
72 /// Use this for showing types to the user where space is constrained (e.g. doc popups)
73 fn display_truncated<'a>(
75 db: &'a dyn HirDatabase,
76 max_size: Option<usize>,
77 ) -> HirDisplayWrapper<'a, Self>
85 omit_verbose_types: true,
86 display_target: DisplayTarget::Diagnostics,
90 /// Returns a String representation of `self` that can be inserted into the given module.
91 /// Use this when generating code (e.g. assists)
92 fn display_source_code<'a>(
94 db: &'a dyn HirDatabase,
96 ) -> Result<String, DisplaySourceCodeError> {
97 let mut result = String::new();
98 match self.hir_fmt(&mut HirFormatter {
101 buf: String::with_capacity(20),
104 omit_verbose_types: false,
105 display_target: DisplayTarget::SourceCode { module_id },
108 Err(HirDisplayError::FmtError) => panic!("Writing to String can't fail!"),
109 Err(HirDisplayError::DisplaySourceCodeError(e)) => return Err(e),
114 /// Returns a String representation of `self` for test purposes
115 fn display_test<'a>(&'a self, db: &'a dyn HirDatabase) -> HirDisplayWrapper<'a, Self>
123 omit_verbose_types: false,
124 display_target: DisplayTarget::Test,
129 impl<'a> HirFormatter<'a> {
130 pub fn write_joined<T: HirDisplay>(
132 iter: impl IntoIterator<Item = T>,
134 ) -> Result<(), HirDisplayError> {
135 let mut first = true;
138 write!(self, "{}", sep)?;
146 /// This allows using the `write!` macro directly with a `HirFormatter`.
147 pub fn write_fmt(&mut self, args: fmt::Arguments) -> Result<(), HirDisplayError> {
148 // We write to a buffer first to track output size
150 fmt::write(&mut self.buf, args)?;
151 self.curr_size += self.buf.len();
153 // Then we write to the internal formatter from the buffer
154 self.fmt.write_str(&self.buf).map_err(HirDisplayError::from)
157 pub fn should_truncate(&self) -> bool {
158 if let Some(max_size) = self.max_size {
159 self.curr_size >= max_size
165 pub fn omit_verbose_types(&self) -> bool {
166 self.omit_verbose_types
170 #[derive(Clone, Copy)]
171 pub enum DisplayTarget {
172 /// Display types for inlays, doc popups, autocompletion, etc...
173 /// Showing `{unknown}` or not qualifying paths is fine here.
174 /// There's no reason for this to fail.
176 /// Display types for inserting them in source files.
177 /// The generated code should compile, so paths need to be qualified.
178 SourceCode { module_id: ModuleId },
179 /// Only for test purpose to keep real types
184 fn is_source_code(&self) -> bool {
185 matches!(self, Self::SourceCode { .. })
187 fn is_test(&self) -> bool {
188 matches!(self, Self::Test)
193 pub enum DisplaySourceCodeError {
199 pub enum HirDisplayError {
200 /// Errors that can occur when generating source code
201 DisplaySourceCodeError(DisplaySourceCodeError),
202 /// `FmtError` is required to be compatible with std::fmt::Display
205 impl From<fmt::Error> for HirDisplayError {
206 fn from(_: fmt::Error) -> Self {
211 pub struct HirDisplayWrapper<'a, T> {
212 db: &'a dyn HirDatabase,
214 max_size: Option<usize>,
215 omit_verbose_types: bool,
216 display_target: DisplayTarget,
219 impl<'a, T> fmt::Display for HirDisplayWrapper<'a, T>
223 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
224 match self.t.hir_fmt(&mut HirFormatter {
227 buf: String::with_capacity(20),
229 max_size: self.max_size,
230 omit_verbose_types: self.omit_verbose_types,
231 display_target: self.display_target,
234 Err(HirDisplayError::FmtError) => Err(fmt::Error),
235 Err(HirDisplayError::DisplaySourceCodeError(_)) => {
236 // This should never happen
237 panic!("HirDisplay failed when calling Display::fmt!")
243 const TYPE_HINT_TRUNCATION: &str = "…";
245 impl<T: HirDisplay> HirDisplay for &'_ T {
246 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
247 HirDisplay::hir_fmt(*self, f)
251 impl HirDisplay for ProjectionTy {
252 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
253 if f.should_truncate() {
254 return write!(f, "{}", TYPE_HINT_TRUNCATION);
257 let trait_ = f.db.trait_data(self.trait_(f.db));
258 let first_parameter = self.self_type_parameter(&Interner).into_displayable(
261 f.omit_verbose_types,
264 write!(f, "<{} as {}", first_parameter, trait_.name)?;
265 if self.substitution.len(&Interner) > 1 {
267 f.write_joined(&self.substitution.interned()[1..], ", ")?;
270 write!(f, ">::{}", f.db.type_alias_data(from_assoc_type_id(self.associated_ty_id)).name)?;
275 impl HirDisplay for OpaqueTy {
276 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
277 if f.should_truncate() {
278 return write!(f, "{}", TYPE_HINT_TRUNCATION);
281 self.substitution.at(&Interner, 0).hir_fmt(f)
285 impl HirDisplay for GenericArg {
286 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
287 match self.interned() {
288 crate::GenericArgData::Ty(ty) => ty.hir_fmt(f),
293 impl HirDisplay for Ty {
294 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
295 if f.should_truncate() {
296 return write!(f, "{}", TYPE_HINT_TRUNCATION);
299 match self.kind(&Interner) {
300 TyKind::Never => write!(f, "!")?,
301 TyKind::Str => write!(f, "str")?,
302 TyKind::Scalar(Scalar::Bool) => write!(f, "bool")?,
303 TyKind::Scalar(Scalar::Char) => write!(f, "char")?,
304 &TyKind::Scalar(Scalar::Float(t)) => write!(f, "{}", primitive::float_ty_to_string(t))?,
305 &TyKind::Scalar(Scalar::Int(t)) => write!(f, "{}", primitive::int_ty_to_string(t))?,
306 &TyKind::Scalar(Scalar::Uint(t)) => write!(f, "{}", primitive::uint_ty_to_string(t))?,
307 TyKind::Slice(t) => {
312 TyKind::Array(t) => {
317 TyKind::Raw(m, t) | TyKind::Ref(m, t) => {
319 t.into_displayable(f.db, f.max_size, f.omit_verbose_types, f.display_target);
321 if matches!(self.kind(&Interner), TyKind::Raw(..)) {
326 Mutability::Not => "const ",
327 Mutability::Mut => "mut ",
335 Mutability::Not => "",
336 Mutability::Mut => "mut ",
341 // FIXME: all this just to decide whether to use parentheses...
343 let predicates: Vec<_> = match t.kind(&Interner) {
344 TyKind::Dyn(dyn_ty) if dyn_ty.bounds.skip_binders().interned().len() > 1 => {
345 dyn_ty.bounds.skip_binders().interned().iter().cloned().collect()
347 &TyKind::Alias(AliasTy::Opaque(OpaqueTy {
349 substitution: ref parameters,
351 let impl_trait_id = f.db.lookup_intern_impl_trait_id(opaque_ty_id.into());
352 if let ImplTraitId::ReturnTypeImplTrait(func, idx) = impl_trait_id {
354 f.db.return_type_impl_traits(func)
355 .expect("impl trait id without data");
358 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
359 let bounds = data.substitute(&Interner, parameters);
360 bounds.into_value_and_skipped_binders().0
368 if let Some(WhereClause::Implemented(trait_ref)) =
369 predicates.get(0).map(|b| b.skip_binders())
371 let trait_ = trait_ref.hir_trait_id();
372 if fn_traits(f.db.upcast(), trait_).any(|it| it == trait_)
373 && predicates.len() <= 2
375 return write!(f, "{}", ty_display);
379 if predicates.len() > 1 {
381 write!(f, "{}", ty_display)?;
384 write!(f, "{}", ty_display)?;
387 TyKind::Tuple(_, substs) => {
388 if substs.len(&Interner) == 1 {
390 substs.at(&Interner, 0).hir_fmt(f)?;
394 f.write_joined(&*substs.interned(), ", ")?;
398 TyKind::Function(fn_ptr) => {
399 let sig = CallableSig::from_fn_ptr(fn_ptr);
402 TyKind::FnDef(def, parameters) => {
403 let def = from_chalk(f.db, *def);
404 let sig = f.db.callable_item_signature(def).substitute(&Interner, parameters);
406 CallableDefId::FunctionId(ff) => {
407 write!(f, "fn {}", f.db.function_data(ff).name)?
409 CallableDefId::StructId(s) => write!(f, "{}", f.db.struct_data(s).name)?,
410 CallableDefId::EnumVariantId(e) => {
411 write!(f, "{}", f.db.enum_data(e.parent).variants[e.local_id].name)?
414 if parameters.len(&Interner) > 0 {
415 let generics = generics(f.db.upcast(), def.into());
416 let (parent_params, self_param, type_params, _impl_trait_params) =
417 generics.provenance_split();
418 let total_len = parent_params + self_param + type_params;
419 // We print all params except implicit impl Trait params. Still a bit weird; should we leave out parent and self?
422 f.write_joined(¶meters.interned()[..total_len], ", ")?;
427 f.write_joined(sig.params(), ", ")?;
431 let ret_display = ret.into_displayable(
434 f.omit_verbose_types,
438 write!(f, " -> {}", ret_display)?;
441 TyKind::Adt(AdtId(def_id), parameters) => {
442 match f.display_target {
443 DisplayTarget::Diagnostics | DisplayTarget::Test => {
444 let name = match *def_id {
445 hir_def::AdtId::StructId(it) => f.db.struct_data(it).name.clone(),
446 hir_def::AdtId::UnionId(it) => f.db.union_data(it).name.clone(),
447 hir_def::AdtId::EnumId(it) => f.db.enum_data(it).name.clone(),
449 write!(f, "{}", name)?;
451 DisplayTarget::SourceCode { module_id } => {
452 if let Some(path) = find_path::find_path(
454 ItemInNs::Types((*def_id).into()),
457 write!(f, "{}", path)?;
459 return Err(HirDisplayError::DisplaySourceCodeError(
460 DisplaySourceCodeError::PathNotFound,
466 if parameters.len(&Interner) > 0 {
467 let parameters_to_write = if f.display_target.is_source_code()
468 || f.omit_verbose_types()
471 .as_generic_def(f.db)
472 .map(|generic_def_id| f.db.generic_defaults(generic_def_id))
473 .filter(|defaults| !defaults.is_empty())
475 None => parameters.interned().as_ref(),
476 Some(default_parameters) => {
477 let mut default_from = 0;
478 for (i, parameter) in parameters.iter(&Interner).enumerate() {
480 parameter.assert_ty_ref(&Interner).kind(&Interner),
481 default_parameters.get(i),
483 (&TyKind::Error, _) | (_, None) => {
484 default_from = i + 1;
486 (_, Some(default_parameter)) => {
487 let actual_default = default_parameter
489 .substitute(&Interner, ¶meters.prefix(i));
490 if parameter.assert_ty_ref(&Interner) != &actual_default
492 default_from = i + 1;
497 ¶meters.interned()[0..default_from]
501 parameters.interned().as_ref()
503 if !parameters_to_write.is_empty() {
505 f.write_joined(parameters_to_write, ", ")?;
510 TyKind::AssociatedType(assoc_type_id, parameters) => {
511 let type_alias = from_assoc_type_id(*assoc_type_id);
512 let trait_ = match type_alias.lookup(f.db.upcast()).container {
513 AssocContainerId::TraitId(it) => it,
514 _ => panic!("not an associated type"),
516 let trait_ = f.db.trait_data(trait_);
517 let type_alias_data = f.db.type_alias_data(type_alias);
519 // Use placeholder associated types when the target is test (https://rust-lang.github.io/chalk/book/clauses/type_equality.html#placeholder-associated-types)
520 if f.display_target.is_test() {
521 write!(f, "{}::{}", trait_.name, type_alias_data.name)?;
522 if parameters.len(&Interner) > 0 {
524 f.write_joined(&*parameters.interned(), ", ")?;
528 let projection_ty = ProjectionTy {
529 associated_ty_id: to_assoc_type_id(type_alias),
530 substitution: parameters.clone(),
533 projection_ty.hir_fmt(f)?;
536 TyKind::Foreign(type_alias) => {
537 let type_alias = f.db.type_alias_data(from_foreign_def_id(*type_alias));
538 write!(f, "{}", type_alias.name)?;
540 TyKind::OpaqueType(opaque_ty_id, parameters) => {
541 let impl_trait_id = f.db.lookup_intern_impl_trait_id((*opaque_ty_id).into());
542 match impl_trait_id {
543 ImplTraitId::ReturnTypeImplTrait(func, idx) => {
545 f.db.return_type_impl_traits(func).expect("impl trait id without data");
548 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
549 let bounds = data.substitute(&Interner, ¶meters);
550 write_bounds_like_dyn_trait_with_prefix("impl", bounds.skip_binders(), f)?;
551 // FIXME: it would maybe be good to distinguish this from the alias type (when debug printing), and to show the substitution
553 ImplTraitId::AsyncBlockTypeImplTrait(..) => {
554 write!(f, "impl Future<Output = ")?;
555 parameters.at(&Interner, 0).hir_fmt(f)?;
560 TyKind::Closure(.., substs) => {
561 if f.display_target.is_source_code() {
562 return Err(HirDisplayError::DisplaySourceCodeError(
563 DisplaySourceCodeError::Closure,
566 let sig = substs.at(&Interner, 0).assert_ty_ref(&Interner).callable_sig(f.db);
567 if let Some(sig) = sig {
568 if sig.params().is_empty() {
570 } else if f.omit_verbose_types() {
571 write!(f, "|{}|", TYPE_HINT_TRUNCATION)?;
574 f.write_joined(sig.params(), ", ")?;
578 let ret_display = sig.ret().into_displayable(
581 f.omit_verbose_types,
584 write!(f, " -> {}", ret_display)?;
586 write!(f, "{{closure}}")?;
589 TyKind::Placeholder(idx) => {
590 let id = from_placeholder_idx(f.db, *idx);
591 let generics = generics(f.db.upcast(), id.parent);
592 let param_data = &generics.params.types[id.local_id];
593 match param_data.provenance {
594 TypeParamProvenance::TypeParamList | TypeParamProvenance::TraitSelf => {
595 write!(f, "{}", param_data.name.clone().unwrap_or_else(Name::missing))?
597 TypeParamProvenance::ArgumentImplTrait => {
598 let substs = generics.type_params_subst(f.db);
600 f.db.generic_predicates(id.parent)
602 .map(|pred| pred.clone().substitute(&Interner, &substs))
603 .filter(|wc| match &wc.skip_binders() {
604 WhereClause::Implemented(tr) => {
605 tr.self_type_parameter(&Interner) == self
607 WhereClause::AliasEq(AliasEq {
608 alias: AliasTy::Projection(proj),
610 }) => proj.self_type_parameter(&Interner) == self,
613 .collect::<Vec<_>>();
614 write_bounds_like_dyn_trait_with_prefix("impl", &bounds, f)?;
618 TyKind::BoundVar(idx) => write!(f, "?{}.{}", idx.debruijn.depth(), idx.index)?,
619 TyKind::Dyn(dyn_ty) => {
620 write_bounds_like_dyn_trait_with_prefix(
622 dyn_ty.bounds.skip_binders().interned(),
626 TyKind::Alias(AliasTy::Projection(p_ty)) => p_ty.hir_fmt(f)?,
627 TyKind::Alias(AliasTy::Opaque(opaque_ty)) => {
628 let impl_trait_id = f.db.lookup_intern_impl_trait_id(opaque_ty.opaque_ty_id.into());
629 match impl_trait_id {
630 ImplTraitId::ReturnTypeImplTrait(func, idx) => {
632 f.db.return_type_impl_traits(func).expect("impl trait id without data");
635 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
636 let bounds = data.substitute(&Interner, &opaque_ty.substitution);
637 write_bounds_like_dyn_trait_with_prefix("impl", bounds.skip_binders(), f)?;
639 ImplTraitId::AsyncBlockTypeImplTrait(..) => {
640 write!(f, "{{async block}}")?;
645 if f.display_target.is_source_code() {
646 return Err(HirDisplayError::DisplaySourceCodeError(
647 DisplaySourceCodeError::UnknownType,
650 write!(f, "{{unknown}}")?;
652 TyKind::InferenceVar(..) => write!(f, "_")?,
658 impl HirDisplay for CallableSig {
659 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
661 f.write_joined(self.params(), ", ")?;
663 if self.params().is_empty() {
670 let ret = self.ret();
673 ret.into_displayable(f.db, f.max_size, f.omit_verbose_types, f.display_target);
674 write!(f, " -> {}", ret_display)?;
680 fn fn_traits(db: &dyn DefDatabase, trait_: TraitId) -> impl Iterator<Item = TraitId> {
681 let krate = trait_.lookup(db).container.krate();
683 db.lang_item(krate, "fn".into()),
684 db.lang_item(krate, "fn_mut".into()),
685 db.lang_item(krate, "fn_once".into()),
687 array::IntoIter::new(fn_traits).into_iter().flatten().flat_map(|it| it.as_trait())
690 pub fn write_bounds_like_dyn_trait_with_prefix(
692 predicates: &[QuantifiedWhereClause],
693 f: &mut HirFormatter,
694 ) -> Result<(), HirDisplayError> {
695 write!(f, "{}", prefix)?;
696 if !predicates.is_empty() {
698 write_bounds_like_dyn_trait(predicates, f)
704 fn write_bounds_like_dyn_trait(
705 predicates: &[QuantifiedWhereClause],
706 f: &mut HirFormatter,
707 ) -> Result<(), HirDisplayError> {
708 // Note: This code is written to produce nice results (i.e.
709 // corresponding to surface Rust) for types that can occur in
710 // actual Rust. It will have weird results if the predicates
711 // aren't as expected (i.e. self types = $0, projection
712 // predicates for a certain trait come after the Implemented
713 // predicate for that trait).
714 let mut first = true;
715 let mut angle_open = false;
716 let mut is_fn_trait = false;
717 for p in predicates.iter() {
718 match p.skip_binders() {
719 WhereClause::Implemented(trait_ref) => {
720 let trait_ = trait_ref.hir_trait_id();
722 is_fn_trait = fn_traits(f.db.upcast(), trait_).any(|it| it == trait_);
724 if !is_fn_trait && angle_open {
731 // We assume that the self type is $0 (i.e. the
732 // existential) here, which is the only thing that's
733 // possible in actual Rust, and hence don't print it
734 write!(f, "{}", f.db.trait_data(trait_).name)?;
735 if let [_, params @ ..] = &*trait_ref.substitution.interned() {
738 params.first().and_then(|it| it.assert_ty_ref(&Interner).as_tuple())
741 f.write_joined(&*args.interned(), ", ")?;
744 } else if !params.is_empty() {
746 f.write_joined(params, ", ")?;
747 // there might be assoc type bindings, so we leave the angle brackets open
752 WhereClause::AliasEq(alias_eq) if is_fn_trait => {
755 alias_eq.ty.hir_fmt(f)?;
757 WhereClause::AliasEq(AliasEq { ty, alias }) => {
758 // in types in actual Rust, these will always come
759 // after the corresponding Implemented predicate
766 if let AliasTy::Projection(proj) = alias {
768 f.db.type_alias_data(from_assoc_type_id(proj.associated_ty_id));
769 write!(f, "{} = ", type_alias.name)?;
783 fn hir_fmt_ext(&self, f: &mut HirFormatter, use_as: bool) -> Result<(), HirDisplayError> {
784 if f.should_truncate() {
785 return write!(f, "{}", TYPE_HINT_TRUNCATION);
788 self.self_type_parameter(&Interner).hir_fmt(f)?;
794 write!(f, "{}", f.db.trait_data(self.hir_trait_id()).name)?;
795 if self.substitution.len(&Interner) > 1 {
797 f.write_joined(&self.substitution.interned()[1..], ", ")?;
804 impl HirDisplay for TraitRef {
805 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
806 self.hir_fmt_ext(f, false)
810 impl HirDisplay for WhereClause {
811 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
812 if f.should_truncate() {
813 return write!(f, "{}", TYPE_HINT_TRUNCATION);
817 WhereClause::Implemented(trait_ref) => trait_ref.hir_fmt(f)?,
818 WhereClause::AliasEq(AliasEq { alias: AliasTy::Projection(projection_ty), ty }) => {
820 projection_ty.trait_ref(f.db).hir_fmt_ext(f, true)?;
824 f.db.type_alias_data(from_assoc_type_id(projection_ty.associated_ty_id)).name,
828 WhereClause::AliasEq(_) => write!(f, "{{error}}")?,
834 impl HirDisplay for LifetimeOutlives {
835 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
842 impl HirDisplay for Lifetime {
843 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
844 self.interned().hir_fmt(f)
848 impl HirDisplay for LifetimeData {
849 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
851 LifetimeData::BoundVar(idx) => write!(f, "?{}.{}", idx.debruijn.depth(), idx.index),
852 LifetimeData::InferenceVar(_) => write!(f, "_"),
853 LifetimeData::Placeholder(idx) => {
854 let id = lt_from_placeholder_idx(f.db, *idx);
855 let generics = generics(f.db.upcast(), id.parent);
856 let param_data = &generics.params.lifetimes[id.local_id];
857 write!(f, "{}", param_data.name)
859 LifetimeData::Static => write!(f, "'static"),
860 LifetimeData::Empty(_) => Ok(()),
861 LifetimeData::Erased => Ok(()),
862 LifetimeData::Phantom(_, _) => Ok(()),
867 impl HirDisplay for DomainGoal {
868 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
870 DomainGoal::Holds(wc) => {
871 write!(f, "Holds(")?;
879 pub fn write_visibility(
882 f: &mut HirFormatter,
883 ) -> Result<(), HirDisplayError> {
885 Visibility::Public => write!(f, "pub "),
886 Visibility::Module(vis_id) => {
887 let def_map = module_id.def_map(f.db.upcast());
888 let root_module_id = def_map.module_id(def_map.root());
889 if vis_id == module_id {
890 // pub(self) or omitted
892 } else if root_module_id == vis_id {
893 write!(f, "pub(crate) ")
894 } else if module_id.containing_module(f.db.upcast()) == Some(vis_id) {
895 write!(f, "pub(super) ")
897 write!(f, "pub(in ...) ")
903 impl HirDisplay for TypeRef {
904 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
906 TypeRef::Never => write!(f, "!")?,
907 TypeRef::Placeholder => write!(f, "_")?,
908 TypeRef::Tuple(elems) => {
910 f.write_joined(elems, ", ")?;
911 if elems.len() == 1 {
916 TypeRef::Path(path) => path.hir_fmt(f)?,
917 TypeRef::RawPtr(inner, mutability) => {
918 let mutability = match mutability {
919 hir_def::type_ref::Mutability::Shared => "*const ",
920 hir_def::type_ref::Mutability::Mut => "*mut ",
922 write!(f, "{}", mutability)?;
925 TypeRef::Reference(inner, lifetime, mutability) => {
926 let mutability = match mutability {
927 hir_def::type_ref::Mutability::Shared => "",
928 hir_def::type_ref::Mutability::Mut => "mut ",
931 if let Some(lifetime) = lifetime {
932 write!(f, "{} ", lifetime.name)?;
934 write!(f, "{}", mutability)?;
937 TypeRef::Array(inner) => {
940 // FIXME: Array length?
943 TypeRef::Slice(inner) => {
948 TypeRef::Fn(tys, is_varargs) => {
949 // FIXME: Function pointer qualifiers.
951 f.write_joined(&tys[..tys.len() - 1], ", ")?;
953 write!(f, "{}...", if tys.len() == 1 { "" } else { ", " })?;
956 let ret_ty = tys.last().unwrap();
958 TypeRef::Tuple(tup) if tup.is_empty() => {}
965 TypeRef::ImplTrait(bounds) => {
967 f.write_joined(bounds, " + ")?;
969 TypeRef::DynTrait(bounds) => {
971 f.write_joined(bounds, " + ")?;
973 TypeRef::Error => write!(f, "{{error}}")?,
979 impl HirDisplay for TypeBound {
980 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
982 TypeBound::Path(path) => path.hir_fmt(f),
983 TypeBound::Lifetime(lifetime) => write!(f, "{}", lifetime.name),
984 TypeBound::Error => write!(f, "{{error}}"),
989 impl HirDisplay for Path {
990 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
991 match (self.type_anchor(), self.kind()) {
992 (Some(anchor), _) => {
997 (_, PathKind::Plain) => {}
998 (_, PathKind::Abs) => write!(f, "::")?,
999 (_, PathKind::Crate) => write!(f, "crate")?,
1000 (_, PathKind::Super(0)) => write!(f, "self")?,
1001 (_, PathKind::Super(n)) => {
1002 write!(f, "super")?;
1004 write!(f, "::super")?;
1007 (_, PathKind::DollarCrate(_)) => write!(f, "{{extern_crate}}")?,
1010 for (seg_idx, segment) in self.segments().iter().enumerate() {
1014 write!(f, "{}", segment.name)?;
1015 if let Some(generic_args) = segment.args_and_bindings {
1016 // We should be in type context, so format as `Foo<Bar>` instead of `Foo::<Bar>`.
1017 // Do we actually format expressions?
1019 let mut first = true;
1020 for arg in &generic_args.args {
1023 if generic_args.has_self_type {
1024 // FIXME: Convert to `<Ty as Trait>` form.
1025 write!(f, "Self = ")?;
1032 for binding in &generic_args.bindings {
1038 write!(f, "{}", binding.name)?;
1039 match &binding.type_ref {
1046 f.write_joined(&binding.bounds, " + ")?;
1057 impl HirDisplay for hir_def::path::GenericArg {
1058 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1060 hir_def::path::GenericArg::Type(ty) => ty.hir_fmt(f),
1061 hir_def::path::GenericArg::Lifetime(lifetime) => write!(f, "{}", lifetime.name),