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, subst_prefix, 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)) => {
488 default_parameter.clone().substitute(
490 &subst_prefix(parameters, i),
492 if parameter.assert_ty_ref(&Interner) != &actual_default
494 default_from = i + 1;
499 ¶meters.interned()[0..default_from]
503 parameters.interned().as_ref()
505 if !parameters_to_write.is_empty() {
507 f.write_joined(parameters_to_write, ", ")?;
512 TyKind::AssociatedType(assoc_type_id, parameters) => {
513 let type_alias = from_assoc_type_id(*assoc_type_id);
514 let trait_ = match type_alias.lookup(f.db.upcast()).container {
515 AssocContainerId::TraitId(it) => it,
516 _ => panic!("not an associated type"),
518 let trait_ = f.db.trait_data(trait_);
519 let type_alias_data = f.db.type_alias_data(type_alias);
521 // Use placeholder associated types when the target is test (https://rust-lang.github.io/chalk/book/clauses/type_equality.html#placeholder-associated-types)
522 if f.display_target.is_test() {
523 write!(f, "{}::{}", trait_.name, type_alias_data.name)?;
524 if parameters.len(&Interner) > 0 {
526 f.write_joined(&*parameters.interned(), ", ")?;
530 let projection_ty = ProjectionTy {
531 associated_ty_id: to_assoc_type_id(type_alias),
532 substitution: parameters.clone(),
535 projection_ty.hir_fmt(f)?;
538 TyKind::Foreign(type_alias) => {
539 let type_alias = f.db.type_alias_data(from_foreign_def_id(*type_alias));
540 write!(f, "{}", type_alias.name)?;
542 TyKind::OpaqueType(opaque_ty_id, parameters) => {
543 let impl_trait_id = f.db.lookup_intern_impl_trait_id((*opaque_ty_id).into());
544 match impl_trait_id {
545 ImplTraitId::ReturnTypeImplTrait(func, idx) => {
547 f.db.return_type_impl_traits(func).expect("impl trait id without data");
550 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
551 let bounds = data.substitute(&Interner, ¶meters);
552 write_bounds_like_dyn_trait_with_prefix("impl", bounds.skip_binders(), f)?;
553 // FIXME: it would maybe be good to distinguish this from the alias type (when debug printing), and to show the substitution
555 ImplTraitId::AsyncBlockTypeImplTrait(..) => {
556 write!(f, "impl Future<Output = ")?;
557 parameters.at(&Interner, 0).hir_fmt(f)?;
562 TyKind::Closure(.., substs) => {
563 if f.display_target.is_source_code() {
564 return Err(HirDisplayError::DisplaySourceCodeError(
565 DisplaySourceCodeError::Closure,
568 let sig = substs.at(&Interner, 0).assert_ty_ref(&Interner).callable_sig(f.db);
569 if let Some(sig) = sig {
570 if sig.params().is_empty() {
572 } else if f.omit_verbose_types() {
573 write!(f, "|{}|", TYPE_HINT_TRUNCATION)?;
576 f.write_joined(sig.params(), ", ")?;
580 let ret_display = sig.ret().into_displayable(
583 f.omit_verbose_types,
586 write!(f, " -> {}", ret_display)?;
588 write!(f, "{{closure}}")?;
591 TyKind::Placeholder(idx) => {
592 let id = from_placeholder_idx(f.db, *idx);
593 let generics = generics(f.db.upcast(), id.parent);
594 let param_data = &generics.params.types[id.local_id];
595 match param_data.provenance {
596 TypeParamProvenance::TypeParamList | TypeParamProvenance::TraitSelf => {
597 write!(f, "{}", param_data.name.clone().unwrap_or_else(Name::missing))?
599 TypeParamProvenance::ArgumentImplTrait => {
600 let substs = generics.type_params_subst(f.db);
602 f.db.generic_predicates(id.parent)
604 .map(|pred| pred.clone().substitute(&Interner, &substs))
605 .filter(|wc| match &wc.skip_binders() {
606 WhereClause::Implemented(tr) => {
607 tr.self_type_parameter(&Interner) == self
609 WhereClause::AliasEq(AliasEq {
610 alias: AliasTy::Projection(proj),
612 }) => proj.self_type_parameter(&Interner) == self,
615 .collect::<Vec<_>>();
616 write_bounds_like_dyn_trait_with_prefix("impl", &bounds, f)?;
620 TyKind::BoundVar(idx) => write!(f, "?{}.{}", idx.debruijn.depth(), idx.index)?,
621 TyKind::Dyn(dyn_ty) => {
622 write_bounds_like_dyn_trait_with_prefix(
624 dyn_ty.bounds.skip_binders().interned(),
628 TyKind::Alias(AliasTy::Projection(p_ty)) => p_ty.hir_fmt(f)?,
629 TyKind::Alias(AliasTy::Opaque(opaque_ty)) => {
630 let impl_trait_id = f.db.lookup_intern_impl_trait_id(opaque_ty.opaque_ty_id.into());
631 match impl_trait_id {
632 ImplTraitId::ReturnTypeImplTrait(func, idx) => {
634 f.db.return_type_impl_traits(func).expect("impl trait id without data");
637 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
638 let bounds = data.substitute(&Interner, &opaque_ty.substitution);
639 write_bounds_like_dyn_trait_with_prefix("impl", bounds.skip_binders(), f)?;
641 ImplTraitId::AsyncBlockTypeImplTrait(..) => {
642 write!(f, "{{async block}}")?;
647 if f.display_target.is_source_code() {
648 return Err(HirDisplayError::DisplaySourceCodeError(
649 DisplaySourceCodeError::UnknownType,
652 write!(f, "{{unknown}}")?;
654 TyKind::InferenceVar(..) => write!(f, "_")?,
660 impl HirDisplay for CallableSig {
661 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
663 f.write_joined(self.params(), ", ")?;
665 if self.params().is_empty() {
672 let ret = self.ret();
675 ret.into_displayable(f.db, f.max_size, f.omit_verbose_types, f.display_target);
676 write!(f, " -> {}", ret_display)?;
682 fn fn_traits(db: &dyn DefDatabase, trait_: TraitId) -> impl Iterator<Item = TraitId> {
683 let krate = trait_.lookup(db).container.krate();
685 db.lang_item(krate, "fn".into()),
686 db.lang_item(krate, "fn_mut".into()),
687 db.lang_item(krate, "fn_once".into()),
689 array::IntoIter::new(fn_traits).into_iter().flatten().flat_map(|it| it.as_trait())
692 pub fn write_bounds_like_dyn_trait_with_prefix(
694 predicates: &[QuantifiedWhereClause],
695 f: &mut HirFormatter,
696 ) -> Result<(), HirDisplayError> {
697 write!(f, "{}", prefix)?;
698 if !predicates.is_empty() {
700 write_bounds_like_dyn_trait(predicates, f)
706 fn write_bounds_like_dyn_trait(
707 predicates: &[QuantifiedWhereClause],
708 f: &mut HirFormatter,
709 ) -> Result<(), HirDisplayError> {
710 // Note: This code is written to produce nice results (i.e.
711 // corresponding to surface Rust) for types that can occur in
712 // actual Rust. It will have weird results if the predicates
713 // aren't as expected (i.e. self types = $0, projection
714 // predicates for a certain trait come after the Implemented
715 // predicate for that trait).
716 let mut first = true;
717 let mut angle_open = false;
718 let mut is_fn_trait = false;
719 for p in predicates.iter() {
720 match p.skip_binders() {
721 WhereClause::Implemented(trait_ref) => {
722 let trait_ = trait_ref.hir_trait_id();
724 is_fn_trait = fn_traits(f.db.upcast(), trait_).any(|it| it == trait_);
726 if !is_fn_trait && angle_open {
733 // We assume that the self type is $0 (i.e. the
734 // existential) here, which is the only thing that's
735 // possible in actual Rust, and hence don't print it
736 write!(f, "{}", f.db.trait_data(trait_).name)?;
737 if let [_, params @ ..] = &*trait_ref.substitution.interned() {
740 params.first().and_then(|it| it.assert_ty_ref(&Interner).as_tuple())
743 f.write_joined(&*args.interned(), ", ")?;
746 } else if !params.is_empty() {
748 f.write_joined(params, ", ")?;
749 // there might be assoc type bindings, so we leave the angle brackets open
754 WhereClause::AliasEq(alias_eq) if is_fn_trait => {
757 alias_eq.ty.hir_fmt(f)?;
759 WhereClause::AliasEq(AliasEq { ty, alias }) => {
760 // in types in actual Rust, these will always come
761 // after the corresponding Implemented predicate
768 if let AliasTy::Projection(proj) = alias {
770 f.db.type_alias_data(from_assoc_type_id(proj.associated_ty_id));
771 write!(f, "{} = ", type_alias.name)?;
785 fn hir_fmt_ext(&self, f: &mut HirFormatter, use_as: bool) -> Result<(), HirDisplayError> {
786 if f.should_truncate() {
787 return write!(f, "{}", TYPE_HINT_TRUNCATION);
790 self.self_type_parameter(&Interner).hir_fmt(f)?;
796 write!(f, "{}", f.db.trait_data(self.hir_trait_id()).name)?;
797 if self.substitution.len(&Interner) > 1 {
799 f.write_joined(&self.substitution.interned()[1..], ", ")?;
806 impl HirDisplay for TraitRef {
807 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
808 self.hir_fmt_ext(f, false)
812 impl HirDisplay for WhereClause {
813 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
814 if f.should_truncate() {
815 return write!(f, "{}", TYPE_HINT_TRUNCATION);
819 WhereClause::Implemented(trait_ref) => trait_ref.hir_fmt(f)?,
820 WhereClause::AliasEq(AliasEq { alias: AliasTy::Projection(projection_ty), ty }) => {
822 projection_ty.trait_ref(f.db).hir_fmt_ext(f, true)?;
826 f.db.type_alias_data(from_assoc_type_id(projection_ty.associated_ty_id)).name,
830 WhereClause::AliasEq(_) => write!(f, "{{error}}")?,
836 impl HirDisplay for LifetimeOutlives {
837 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
844 impl HirDisplay for Lifetime {
845 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
846 self.interned().hir_fmt(f)
850 impl HirDisplay for LifetimeData {
851 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
853 LifetimeData::BoundVar(idx) => write!(f, "?{}.{}", idx.debruijn.depth(), idx.index),
854 LifetimeData::InferenceVar(_) => write!(f, "_"),
855 LifetimeData::Placeholder(idx) => {
856 let id = lt_from_placeholder_idx(f.db, *idx);
857 let generics = generics(f.db.upcast(), id.parent);
858 let param_data = &generics.params.lifetimes[id.local_id];
859 write!(f, "{}", param_data.name)
861 LifetimeData::Static => write!(f, "'static"),
862 LifetimeData::Empty(_) => Ok(()),
863 LifetimeData::Erased => Ok(()),
864 LifetimeData::Phantom(_, _) => Ok(()),
869 impl HirDisplay for DomainGoal {
870 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
872 DomainGoal::Holds(wc) => {
873 write!(f, "Holds(")?;
881 pub fn write_visibility(
884 f: &mut HirFormatter,
885 ) -> Result<(), HirDisplayError> {
887 Visibility::Public => write!(f, "pub "),
888 Visibility::Module(vis_id) => {
889 let def_map = module_id.def_map(f.db.upcast());
890 let root_module_id = def_map.module_id(def_map.root());
891 if vis_id == module_id {
892 // pub(self) or omitted
894 } else if root_module_id == vis_id {
895 write!(f, "pub(crate) ")
896 } else if module_id.containing_module(f.db.upcast()) == Some(vis_id) {
897 write!(f, "pub(super) ")
899 write!(f, "pub(in ...) ")
905 impl HirDisplay for TypeRef {
906 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
908 TypeRef::Never => write!(f, "!")?,
909 TypeRef::Placeholder => write!(f, "_")?,
910 TypeRef::Tuple(elems) => {
912 f.write_joined(elems, ", ")?;
913 if elems.len() == 1 {
918 TypeRef::Path(path) => path.hir_fmt(f)?,
919 TypeRef::RawPtr(inner, mutability) => {
920 let mutability = match mutability {
921 hir_def::type_ref::Mutability::Shared => "*const ",
922 hir_def::type_ref::Mutability::Mut => "*mut ",
924 write!(f, "{}", mutability)?;
927 TypeRef::Reference(inner, lifetime, mutability) => {
928 let mutability = match mutability {
929 hir_def::type_ref::Mutability::Shared => "",
930 hir_def::type_ref::Mutability::Mut => "mut ",
933 if let Some(lifetime) = lifetime {
934 write!(f, "{} ", lifetime.name)?;
936 write!(f, "{}", mutability)?;
939 TypeRef::Array(inner) => {
942 // FIXME: Array length?
945 TypeRef::Slice(inner) => {
950 TypeRef::Fn(tys, is_varargs) => {
951 // FIXME: Function pointer qualifiers.
953 f.write_joined(&tys[..tys.len() - 1], ", ")?;
955 write!(f, "{}...", if tys.len() == 1 { "" } else { ", " })?;
958 let ret_ty = tys.last().unwrap();
960 TypeRef::Tuple(tup) if tup.is_empty() => {}
967 TypeRef::ImplTrait(bounds) => {
969 f.write_joined(bounds, " + ")?;
971 TypeRef::DynTrait(bounds) => {
973 f.write_joined(bounds, " + ")?;
975 TypeRef::Error => write!(f, "{{error}}")?,
981 impl HirDisplay for TypeBound {
982 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
984 TypeBound::Path(path) => path.hir_fmt(f),
985 TypeBound::Lifetime(lifetime) => write!(f, "{}", lifetime.name),
986 TypeBound::Error => write!(f, "{{error}}"),
991 impl HirDisplay for Path {
992 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
993 match (self.type_anchor(), self.kind()) {
994 (Some(anchor), _) => {
999 (_, PathKind::Plain) => {}
1000 (_, PathKind::Abs) => write!(f, "::")?,
1001 (_, PathKind::Crate) => write!(f, "crate")?,
1002 (_, PathKind::Super(0)) => write!(f, "self")?,
1003 (_, PathKind::Super(n)) => {
1004 write!(f, "super")?;
1006 write!(f, "::super")?;
1009 (_, PathKind::DollarCrate(_)) => write!(f, "{{extern_crate}}")?,
1012 for (seg_idx, segment) in self.segments().iter().enumerate() {
1016 write!(f, "{}", segment.name)?;
1017 if let Some(generic_args) = segment.args_and_bindings {
1018 // We should be in type context, so format as `Foo<Bar>` instead of `Foo::<Bar>`.
1019 // Do we actually format expressions?
1021 let mut first = true;
1022 for arg in &generic_args.args {
1025 if generic_args.has_self_type {
1026 // FIXME: Convert to `<Ty as Trait>` form.
1027 write!(f, "Self = ")?;
1034 for binding in &generic_args.bindings {
1040 write!(f, "{}", binding.name)?;
1041 match &binding.type_ref {
1048 f.write_joined(&binding.bounds, " + ")?;
1059 impl HirDisplay for hir_def::path::GenericArg {
1060 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1062 hir_def::path::GenericArg::Type(ty) => ty.hir_fmt(f),
1063 hir_def::path::GenericArg::Lifetime(lifetime) => write!(f, "{}", lifetime.name),