1 //! FIXME: write short doc here
8 use chalk_ir::BoundVar;
12 generics::TypeParamProvenance,
14 path::{Path, PathKind},
15 type_ref::{TypeBound, TypeRef},
16 visibility::Visibility,
17 AssocContainerId, Lookup, ModuleId, TraitId,
19 use hir_expand::name::Name;
22 const_from_placeholder_idx, db::HirDatabase, from_assoc_type_id, from_foreign_def_id,
23 from_placeholder_idx, lt_from_placeholder_idx, primitive, subst_prefix, to_assoc_type_id,
24 traits::chalk::from_chalk, utils::generics, AdtId, AliasEq, AliasTy, CallableDefId,
25 CallableSig, Const, ConstValue, DomainGoal, GenericArg, ImplTraitId, Interner, Lifetime,
26 LifetimeData, LifetimeOutlives, Mutability, OpaqueTy, ProjectionTy, ProjectionTyExt,
27 QuantifiedWhereClause, Scalar, TraitRef, TraitRefExt, Ty, TyExt, TyKind, WhereClause,
30 pub struct HirFormatter<'a> {
31 pub db: &'a dyn HirDatabase,
32 fmt: &'a mut dyn fmt::Write,
35 pub(crate) max_size: Option<usize>,
36 omit_verbose_types: bool,
37 display_target: DisplayTarget,
40 pub trait HirDisplay {
41 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError>;
43 /// Returns a `Display`able type that is human-readable.
44 fn into_displayable<'a>(
46 db: &'a dyn HirDatabase,
47 max_size: Option<usize>,
48 omit_verbose_types: bool,
49 display_target: DisplayTarget,
50 ) -> HirDisplayWrapper<'a, Self>
55 !matches!(display_target, DisplayTarget::SourceCode { .. }),
56 "HirDisplayWrapper cannot fail with DisplaySourceCodeError, use HirDisplay::hir_fmt directly instead"
58 HirDisplayWrapper { db, t: self, max_size, omit_verbose_types, display_target }
61 /// Returns a `Display`able type that is human-readable.
62 /// Use this for showing types to the user (e.g. diagnostics)
63 fn display<'a>(&'a self, db: &'a dyn HirDatabase) -> HirDisplayWrapper<'a, Self>
71 omit_verbose_types: false,
72 display_target: DisplayTarget::Diagnostics,
76 /// Returns a `Display`able type that is human-readable and tries to be succinct.
77 /// Use this for showing types to the user where space is constrained (e.g. doc popups)
78 fn display_truncated<'a>(
80 db: &'a dyn HirDatabase,
81 max_size: Option<usize>,
82 ) -> HirDisplayWrapper<'a, Self>
90 omit_verbose_types: true,
91 display_target: DisplayTarget::Diagnostics,
95 /// Returns a String representation of `self` that can be inserted into the given module.
96 /// Use this when generating code (e.g. assists)
97 fn display_source_code<'a>(
99 db: &'a dyn HirDatabase,
101 ) -> Result<String, DisplaySourceCodeError> {
102 let mut result = String::new();
103 match self.hir_fmt(&mut HirFormatter {
106 buf: String::with_capacity(20),
109 omit_verbose_types: false,
110 display_target: DisplayTarget::SourceCode { module_id },
113 Err(HirDisplayError::FmtError) => panic!("Writing to String can't fail!"),
114 Err(HirDisplayError::DisplaySourceCodeError(e)) => return Err(e),
119 /// Returns a String representation of `self` for test purposes
120 fn display_test<'a>(&'a self, db: &'a dyn HirDatabase) -> HirDisplayWrapper<'a, Self>
128 omit_verbose_types: false,
129 display_target: DisplayTarget::Test,
134 impl<'a> HirFormatter<'a> {
135 pub fn write_joined<T: HirDisplay>(
137 iter: impl IntoIterator<Item = T>,
139 ) -> Result<(), HirDisplayError> {
140 let mut first = true;
143 write!(self, "{}", sep)?;
151 /// This allows using the `write!` macro directly with a `HirFormatter`.
152 pub fn write_fmt(&mut self, args: fmt::Arguments) -> Result<(), HirDisplayError> {
153 // We write to a buffer first to track output size
155 fmt::write(&mut self.buf, args)?;
156 self.curr_size += self.buf.len();
158 // Then we write to the internal formatter from the buffer
159 self.fmt.write_str(&self.buf).map_err(HirDisplayError::from)
162 pub fn should_truncate(&self) -> bool {
163 if let Some(max_size) = self.max_size {
164 self.curr_size >= max_size
170 pub fn omit_verbose_types(&self) -> bool {
171 self.omit_verbose_types
175 #[derive(Clone, Copy)]
176 pub enum DisplayTarget {
177 /// Display types for inlays, doc popups, autocompletion, etc...
178 /// Showing `{unknown}` or not qualifying paths is fine here.
179 /// There's no reason for this to fail.
181 /// Display types for inserting them in source files.
182 /// The generated code should compile, so paths need to be qualified.
183 SourceCode { module_id: ModuleId },
184 /// Only for test purpose to keep real types
189 fn is_source_code(&self) -> bool {
190 matches!(self, Self::SourceCode { .. })
192 fn is_test(&self) -> bool {
193 matches!(self, Self::Test)
198 pub enum DisplaySourceCodeError {
204 pub enum HirDisplayError {
205 /// Errors that can occur when generating source code
206 DisplaySourceCodeError(DisplaySourceCodeError),
207 /// `FmtError` is required to be compatible with std::fmt::Display
210 impl From<fmt::Error> for HirDisplayError {
211 fn from(_: fmt::Error) -> Self {
216 pub struct HirDisplayWrapper<'a, T> {
217 db: &'a dyn HirDatabase,
219 max_size: Option<usize>,
220 omit_verbose_types: bool,
221 display_target: DisplayTarget,
224 impl<'a, T> fmt::Display for HirDisplayWrapper<'a, T>
228 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
229 match self.t.hir_fmt(&mut HirFormatter {
232 buf: String::with_capacity(20),
234 max_size: self.max_size,
235 omit_verbose_types: self.omit_verbose_types,
236 display_target: self.display_target,
239 Err(HirDisplayError::FmtError) => Err(fmt::Error),
240 Err(HirDisplayError::DisplaySourceCodeError(_)) => {
241 // This should never happen
242 panic!("HirDisplay::hir_fmt failed with DisplaySourceCodeError when calling Display::fmt!")
248 const TYPE_HINT_TRUNCATION: &str = "…";
250 impl<T: HirDisplay> HirDisplay for &'_ T {
251 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
252 HirDisplay::hir_fmt(*self, f)
256 impl HirDisplay for ProjectionTy {
257 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
258 if f.should_truncate() {
259 return write!(f, "{}", TYPE_HINT_TRUNCATION);
262 let trait_ = f.db.trait_data(self.trait_(f.db));
264 self.self_type_parameter(&Interner).hir_fmt(f)?;
265 write!(f, " as {}", trait_.name)?;
266 if self.substitution.len(&Interner) > 1 {
268 f.write_joined(&self.substitution.interned()[1..], ", ")?;
271 write!(f, ">::{}", f.db.type_alias_data(from_assoc_type_id(self.associated_ty_id)).name)?;
276 impl HirDisplay for OpaqueTy {
277 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
278 if f.should_truncate() {
279 return write!(f, "{}", TYPE_HINT_TRUNCATION);
282 self.substitution.at(&Interner, 0).hir_fmt(f)
286 impl HirDisplay for GenericArg {
287 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
288 match self.interned() {
289 crate::GenericArgData::Ty(ty) => ty.hir_fmt(f),
294 impl HirDisplay for Const {
295 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
296 let data = self.interned();
298 ConstValue::BoundVar(idx) => idx.hir_fmt(f),
299 ConstValue::InferenceVar(..) => write!(f, "_"),
300 ConstValue::Placeholder(idx) => {
301 let id = const_from_placeholder_idx(f.db, idx);
302 let generics = generics(f.db.upcast(), id.parent);
303 let param_data = &generics.params.consts[id.local_id];
304 write!(f, "{}", param_data.name)
306 ConstValue::Concrete(_) => write!(f, "_"),
311 impl HirDisplay for BoundVar {
312 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
313 write!(f, "?{}.{}", self.debruijn.depth(), self.index)
317 impl HirDisplay for Ty {
318 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
319 if f.should_truncate() {
320 return write!(f, "{}", TYPE_HINT_TRUNCATION);
323 match self.kind(&Interner) {
324 TyKind::Never => write!(f, "!")?,
325 TyKind::Str => write!(f, "str")?,
326 TyKind::Scalar(Scalar::Bool) => write!(f, "bool")?,
327 TyKind::Scalar(Scalar::Char) => write!(f, "char")?,
328 &TyKind::Scalar(Scalar::Float(t)) => write!(f, "{}", primitive::float_ty_to_string(t))?,
329 &TyKind::Scalar(Scalar::Int(t)) => write!(f, "{}", primitive::int_ty_to_string(t))?,
330 &TyKind::Scalar(Scalar::Uint(t)) => write!(f, "{}", primitive::uint_ty_to_string(t))?,
331 TyKind::Slice(t) => {
336 TyKind::Array(t, c) => {
343 TyKind::Raw(m, t) | TyKind::Ref(m, _, t) => {
344 if matches!(self.kind(&Interner), TyKind::Raw(..)) {
349 Mutability::Not => "const ",
350 Mutability::Mut => "mut ",
358 Mutability::Not => "",
359 Mutability::Mut => "mut ",
364 // FIXME: all this just to decide whether to use parentheses...
366 let predicates: Vec<_> = match t.kind(&Interner) {
367 TyKind::Dyn(dyn_ty) if dyn_ty.bounds.skip_binders().interned().len() > 1 => {
368 dyn_ty.bounds.skip_binders().interned().iter().cloned().collect()
370 &TyKind::Alias(AliasTy::Opaque(OpaqueTy {
372 substitution: ref parameters,
374 let impl_trait_id = f.db.lookup_intern_impl_trait_id(opaque_ty_id.into());
375 if let ImplTraitId::ReturnTypeImplTrait(func, idx) = impl_trait_id {
377 f.db.return_type_impl_traits(func)
378 .expect("impl trait id without data");
381 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
382 let bounds = data.substitute(&Interner, parameters);
383 bounds.into_value_and_skipped_binders().0
391 if let Some(WhereClause::Implemented(trait_ref)) =
392 predicates.get(0).map(|b| b.skip_binders())
394 let trait_ = trait_ref.hir_trait_id();
395 if fn_traits(f.db.upcast(), trait_).any(|it| it == trait_)
396 && predicates.len() <= 2
402 if predicates.len() > 1 {
410 TyKind::Tuple(_, substs) => {
411 if substs.len(&Interner) == 1 {
413 substs.at(&Interner, 0).hir_fmt(f)?;
417 f.write_joined(&*substs.interned(), ", ")?;
421 TyKind::Function(fn_ptr) => {
422 let sig = CallableSig::from_fn_ptr(fn_ptr);
425 TyKind::FnDef(def, parameters) => {
426 let def = from_chalk(f.db, *def);
427 let sig = f.db.callable_item_signature(def).substitute(&Interner, parameters);
429 CallableDefId::FunctionId(ff) => {
430 write!(f, "fn {}", f.db.function_data(ff).name)?
432 CallableDefId::StructId(s) => write!(f, "{}", f.db.struct_data(s).name)?,
433 CallableDefId::EnumVariantId(e) => {
434 write!(f, "{}", f.db.enum_data(e.parent).variants[e.local_id].name)?
437 if parameters.len(&Interner) > 0 {
438 let generics = generics(f.db.upcast(), def.into());
439 let (parent_params, self_param, type_params, _impl_trait_params) =
440 generics.provenance_split();
441 let total_len = parent_params + self_param + type_params;
442 // We print all params except implicit impl Trait params. Still a bit weird; should we leave out parent and self?
445 f.write_joined(¶meters.interned()[..total_len], ", ")?;
450 f.write_joined(sig.params(), ", ")?;
458 TyKind::Adt(AdtId(def_id), parameters) => {
459 match f.display_target {
460 DisplayTarget::Diagnostics | DisplayTarget::Test => {
461 let name = match *def_id {
462 hir_def::AdtId::StructId(it) => f.db.struct_data(it).name.clone(),
463 hir_def::AdtId::UnionId(it) => f.db.union_data(it).name.clone(),
464 hir_def::AdtId::EnumId(it) => f.db.enum_data(it).name.clone(),
466 write!(f, "{}", name)?;
468 DisplayTarget::SourceCode { module_id } => {
469 if let Some(path) = find_path::find_path(
471 ItemInNs::Types((*def_id).into()),
474 write!(f, "{}", path)?;
476 return Err(HirDisplayError::DisplaySourceCodeError(
477 DisplaySourceCodeError::PathNotFound,
483 if parameters.len(&Interner) > 0 {
484 let parameters_to_write = if f.display_target.is_source_code()
485 || f.omit_verbose_types()
488 .as_generic_def(f.db)
489 .map(|generic_def_id| f.db.generic_defaults(generic_def_id))
490 .filter(|defaults| !defaults.is_empty())
492 None => parameters.interned().as_ref(),
493 Some(default_parameters) => {
494 let mut default_from = 0;
495 for (i, parameter) in parameters.iter(&Interner).enumerate() {
497 parameter.assert_ty_ref(&Interner).kind(&Interner),
498 default_parameters.get(i),
500 (&TyKind::Error, _) | (_, None) => {
501 default_from = i + 1;
503 (_, Some(default_parameter)) => {
505 default_parameter.clone().substitute(
507 &subst_prefix(parameters, i),
509 if parameter.assert_ty_ref(&Interner) != &actual_default
511 default_from = i + 1;
516 ¶meters.interned()[0..default_from]
520 parameters.interned().as_ref()
522 if !parameters_to_write.is_empty() {
524 f.write_joined(parameters_to_write, ", ")?;
529 TyKind::AssociatedType(assoc_type_id, parameters) => {
530 let type_alias = from_assoc_type_id(*assoc_type_id);
531 let trait_ = match type_alias.lookup(f.db.upcast()).container {
532 AssocContainerId::TraitId(it) => it,
533 _ => panic!("not an associated type"),
535 let trait_ = f.db.trait_data(trait_);
536 let type_alias_data = f.db.type_alias_data(type_alias);
538 // Use placeholder associated types when the target is test (https://rust-lang.github.io/chalk/book/clauses/type_equality.html#placeholder-associated-types)
539 if f.display_target.is_test() {
540 write!(f, "{}::{}", trait_.name, type_alias_data.name)?;
541 if parameters.len(&Interner) > 0 {
543 f.write_joined(&*parameters.interned(), ", ")?;
547 let projection_ty = ProjectionTy {
548 associated_ty_id: to_assoc_type_id(type_alias),
549 substitution: parameters.clone(),
552 projection_ty.hir_fmt(f)?;
555 TyKind::Foreign(type_alias) => {
556 let type_alias = f.db.type_alias_data(from_foreign_def_id(*type_alias));
557 write!(f, "{}", type_alias.name)?;
559 TyKind::OpaqueType(opaque_ty_id, parameters) => {
560 let impl_trait_id = f.db.lookup_intern_impl_trait_id((*opaque_ty_id).into());
561 match impl_trait_id {
562 ImplTraitId::ReturnTypeImplTrait(func, idx) => {
564 f.db.return_type_impl_traits(func).expect("impl trait id without data");
567 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
568 let bounds = data.substitute(&Interner, ¶meters);
569 write_bounds_like_dyn_trait_with_prefix("impl", bounds.skip_binders(), f)?;
570 // FIXME: it would maybe be good to distinguish this from the alias type (when debug printing), and to show the substitution
572 ImplTraitId::AsyncBlockTypeImplTrait(..) => {
573 write!(f, "impl Future<Output = ")?;
574 parameters.at(&Interner, 0).hir_fmt(f)?;
579 TyKind::Closure(.., substs) => {
580 if f.display_target.is_source_code() {
581 return Err(HirDisplayError::DisplaySourceCodeError(
582 DisplaySourceCodeError::Closure,
585 let sig = substs.at(&Interner, 0).assert_ty_ref(&Interner).callable_sig(f.db);
586 if let Some(sig) = sig {
587 if sig.params().is_empty() {
589 } else if f.omit_verbose_types() {
590 write!(f, "|{}|", TYPE_HINT_TRUNCATION)?;
593 f.write_joined(sig.params(), ", ")?;
598 sig.ret().hir_fmt(f)?;
600 write!(f, "{{closure}}")?;
603 TyKind::Placeholder(idx) => {
604 let id = from_placeholder_idx(f.db, *idx);
605 let generics = generics(f.db.upcast(), id.parent);
606 let param_data = &generics.params.types[id.local_id];
607 match param_data.provenance {
608 TypeParamProvenance::TypeParamList | TypeParamProvenance::TraitSelf => {
609 write!(f, "{}", param_data.name.clone().unwrap_or_else(Name::missing))?
611 TypeParamProvenance::ArgumentImplTrait => {
612 let substs = generics.type_params_subst(f.db);
614 f.db.generic_predicates(id.parent)
616 .map(|pred| pred.clone().substitute(&Interner, &substs))
617 .filter(|wc| match &wc.skip_binders() {
618 WhereClause::Implemented(tr) => {
619 tr.self_type_parameter(&Interner) == self
621 WhereClause::AliasEq(AliasEq {
622 alias: AliasTy::Projection(proj),
624 }) => proj.self_type_parameter(&Interner) == self,
627 .collect::<Vec<_>>();
628 write_bounds_like_dyn_trait_with_prefix("impl", &bounds, f)?;
632 TyKind::BoundVar(idx) => idx.hir_fmt(f)?,
633 TyKind::Dyn(dyn_ty) => {
634 write_bounds_like_dyn_trait_with_prefix(
636 dyn_ty.bounds.skip_binders().interned(),
640 TyKind::Alias(AliasTy::Projection(p_ty)) => p_ty.hir_fmt(f)?,
641 TyKind::Alias(AliasTy::Opaque(opaque_ty)) => {
642 let impl_trait_id = f.db.lookup_intern_impl_trait_id(opaque_ty.opaque_ty_id.into());
643 match impl_trait_id {
644 ImplTraitId::ReturnTypeImplTrait(func, idx) => {
646 f.db.return_type_impl_traits(func).expect("impl trait id without data");
649 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
650 let bounds = data.substitute(&Interner, &opaque_ty.substitution);
651 write_bounds_like_dyn_trait_with_prefix("impl", bounds.skip_binders(), f)?;
653 ImplTraitId::AsyncBlockTypeImplTrait(..) => {
654 write!(f, "{{async block}}")?;
659 if f.display_target.is_source_code() {
660 return Err(HirDisplayError::DisplaySourceCodeError(
661 DisplaySourceCodeError::UnknownType,
664 write!(f, "{{unknown}}")?;
666 TyKind::InferenceVar(..) => write!(f, "_")?,
672 impl HirDisplay for CallableSig {
673 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
675 f.write_joined(self.params(), ", ")?;
677 if self.params().is_empty() {
684 let ret = self.ret();
693 fn fn_traits(db: &dyn DefDatabase, trait_: TraitId) -> impl Iterator<Item = TraitId> {
694 let krate = trait_.lookup(db).container.krate();
696 db.lang_item(krate, "fn".into()),
697 db.lang_item(krate, "fn_mut".into()),
698 db.lang_item(krate, "fn_once".into()),
700 array::IntoIter::new(fn_traits).into_iter().flatten().flat_map(|it| it.as_trait())
703 pub fn write_bounds_like_dyn_trait_with_prefix(
705 predicates: &[QuantifiedWhereClause],
706 f: &mut HirFormatter,
707 ) -> Result<(), HirDisplayError> {
708 write!(f, "{}", prefix)?;
709 if !predicates.is_empty() {
711 write_bounds_like_dyn_trait(predicates, f)
717 fn write_bounds_like_dyn_trait(
718 predicates: &[QuantifiedWhereClause],
719 f: &mut HirFormatter,
720 ) -> Result<(), HirDisplayError> {
721 // Note: This code is written to produce nice results (i.e.
722 // corresponding to surface Rust) for types that can occur in
723 // actual Rust. It will have weird results if the predicates
724 // aren't as expected (i.e. self types = $0, projection
725 // predicates for a certain trait come after the Implemented
726 // predicate for that trait).
727 let mut first = true;
728 let mut angle_open = false;
729 let mut is_fn_trait = false;
730 for p in predicates.iter() {
731 match p.skip_binders() {
732 WhereClause::Implemented(trait_ref) => {
733 let trait_ = trait_ref.hir_trait_id();
735 is_fn_trait = fn_traits(f.db.upcast(), trait_).any(|it| it == trait_);
737 if !is_fn_trait && angle_open {
744 // We assume that the self type is $0 (i.e. the
745 // existential) here, which is the only thing that's
746 // possible in actual Rust, and hence don't print it
747 write!(f, "{}", f.db.trait_data(trait_).name)?;
748 if let [_, params @ ..] = &*trait_ref.substitution.interned() {
751 params.first().and_then(|it| it.assert_ty_ref(&Interner).as_tuple())
754 f.write_joined(&*args.interned(), ", ")?;
757 } else if !params.is_empty() {
759 f.write_joined(params, ", ")?;
760 // there might be assoc type bindings, so we leave the angle brackets open
765 WhereClause::AliasEq(alias_eq) if is_fn_trait => {
768 alias_eq.ty.hir_fmt(f)?;
770 WhereClause::AliasEq(AliasEq { ty, alias }) => {
771 // in types in actual Rust, these will always come
772 // after the corresponding Implemented predicate
779 if let AliasTy::Projection(proj) = alias {
781 f.db.type_alias_data(from_assoc_type_id(proj.associated_ty_id));
782 write!(f, "{} = ", type_alias.name)?;
795 fn fmt_trait_ref(tr: &TraitRef, f: &mut HirFormatter, use_as: bool) -> Result<(), HirDisplayError> {
796 if f.should_truncate() {
797 return write!(f, "{}", TYPE_HINT_TRUNCATION);
800 tr.self_type_parameter(&Interner).hir_fmt(f)?;
806 write!(f, "{}", f.db.trait_data(tr.hir_trait_id()).name)?;
807 if tr.substitution.len(&Interner) > 1 {
809 f.write_joined(&tr.substitution.interned()[1..], ", ")?;
815 impl HirDisplay for TraitRef {
816 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
817 fmt_trait_ref(self, f, false)
821 impl HirDisplay for WhereClause {
822 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
823 if f.should_truncate() {
824 return write!(f, "{}", TYPE_HINT_TRUNCATION);
828 WhereClause::Implemented(trait_ref) => trait_ref.hir_fmt(f)?,
829 WhereClause::AliasEq(AliasEq { alias: AliasTy::Projection(projection_ty), ty }) => {
831 fmt_trait_ref(&projection_ty.trait_ref(f.db), f, true)?;
835 f.db.type_alias_data(from_assoc_type_id(projection_ty.associated_ty_id)).name,
839 WhereClause::AliasEq(_) => write!(f, "{{error}}")?,
845 impl HirDisplay for LifetimeOutlives {
846 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
853 impl HirDisplay for Lifetime {
854 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
855 self.interned().hir_fmt(f)
859 impl HirDisplay for LifetimeData {
860 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
862 LifetimeData::BoundVar(idx) => idx.hir_fmt(f),
863 LifetimeData::InferenceVar(_) => write!(f, "_"),
864 LifetimeData::Placeholder(idx) => {
865 let id = lt_from_placeholder_idx(f.db, *idx);
866 let generics = generics(f.db.upcast(), id.parent);
867 let param_data = &generics.params.lifetimes[id.local_id];
868 write!(f, "{}", param_data.name)
870 LifetimeData::Static => write!(f, "'static"),
871 LifetimeData::Empty(_) => Ok(()),
872 LifetimeData::Erased => Ok(()),
873 LifetimeData::Phantom(_, _) => Ok(()),
878 impl HirDisplay for DomainGoal {
879 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
881 DomainGoal::Holds(wc) => {
882 write!(f, "Holds(")?;
890 pub fn write_visibility(
893 f: &mut HirFormatter,
894 ) -> Result<(), HirDisplayError> {
896 Visibility::Public => write!(f, "pub "),
897 Visibility::Module(vis_id) => {
898 let def_map = module_id.def_map(f.db.upcast());
899 let root_module_id = def_map.module_id(def_map.root());
900 if vis_id == module_id {
901 // pub(self) or omitted
903 } else if root_module_id == vis_id {
904 write!(f, "pub(crate) ")
905 } else if module_id.containing_module(f.db.upcast()) == Some(vis_id) {
906 write!(f, "pub(super) ")
908 write!(f, "pub(in ...) ")
914 impl HirDisplay for TypeRef {
915 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
917 TypeRef::Never => write!(f, "!")?,
918 TypeRef::Placeholder => write!(f, "_")?,
919 TypeRef::Tuple(elems) => {
921 f.write_joined(elems, ", ")?;
922 if elems.len() == 1 {
927 TypeRef::Path(path) => path.hir_fmt(f)?,
928 TypeRef::RawPtr(inner, mutability) => {
929 let mutability = match mutability {
930 hir_def::type_ref::Mutability::Shared => "*const ",
931 hir_def::type_ref::Mutability::Mut => "*mut ",
933 write!(f, "{}", mutability)?;
936 TypeRef::Reference(inner, lifetime, mutability) => {
937 let mutability = match mutability {
938 hir_def::type_ref::Mutability::Shared => "",
939 hir_def::type_ref::Mutability::Mut => "mut ",
942 if let Some(lifetime) = lifetime {
943 write!(f, "{} ", lifetime.name)?;
945 write!(f, "{}", mutability)?;
948 TypeRef::Array(inner) => {
951 // FIXME: Array length?
954 TypeRef::Slice(inner) => {
959 TypeRef::Fn(tys, is_varargs) => {
960 // FIXME: Function pointer qualifiers.
962 f.write_joined(&tys[..tys.len() - 1], ", ")?;
964 write!(f, "{}...", if tys.len() == 1 { "" } else { ", " })?;
967 let ret_ty = tys.last().unwrap();
969 TypeRef::Tuple(tup) if tup.is_empty() => {}
976 TypeRef::ImplTrait(bounds) => {
978 f.write_joined(bounds, " + ")?;
980 TypeRef::DynTrait(bounds) => {
982 f.write_joined(bounds, " + ")?;
984 TypeRef::Error => write!(f, "{{error}}")?,
990 impl HirDisplay for TypeBound {
991 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
993 TypeBound::Path(path) => path.hir_fmt(f),
994 TypeBound::Lifetime(lifetime) => write!(f, "{}", lifetime.name),
995 TypeBound::Error => write!(f, "{{error}}"),
1000 impl HirDisplay for Path {
1001 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1002 match (self.type_anchor(), self.kind()) {
1003 (Some(anchor), _) => {
1008 (_, PathKind::Plain) => {}
1009 (_, PathKind::Abs) => write!(f, "::")?,
1010 (_, PathKind::Crate) => write!(f, "crate")?,
1011 (_, PathKind::Super(0)) => write!(f, "self")?,
1012 (_, PathKind::Super(n)) => {
1013 write!(f, "super")?;
1015 write!(f, "::super")?;
1018 (_, PathKind::DollarCrate(_)) => write!(f, "{{extern_crate}}")?,
1021 for (seg_idx, segment) in self.segments().iter().enumerate() {
1025 write!(f, "{}", segment.name)?;
1026 if let Some(generic_args) = segment.args_and_bindings {
1027 // We should be in type context, so format as `Foo<Bar>` instead of `Foo::<Bar>`.
1028 // Do we actually format expressions?
1030 let mut first = true;
1031 for arg in &generic_args.args {
1034 if generic_args.has_self_type {
1035 // FIXME: Convert to `<Ty as Trait>` form.
1036 write!(f, "Self = ")?;
1043 for binding in &generic_args.bindings {
1049 write!(f, "{}", binding.name)?;
1050 match &binding.type_ref {
1057 f.write_joined(&binding.bounds, " + ")?;
1068 impl HirDisplay for hir_def::path::GenericArg {
1069 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1071 hir_def::path::GenericArg::Type(ty) => ty.hir_fmt(f),
1072 hir_def::path::GenericArg::Lifetime(lifetime) => write!(f, "{}", lifetime.name),