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, 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>
54 HirDisplayWrapper { db, t: self, max_size, omit_verbose_types, display_target }
57 /// Returns a `Display`able type that is human-readable.
58 /// Use this for showing types to the user (e.g. diagnostics)
59 fn display<'a>(&'a self, db: &'a dyn HirDatabase) -> HirDisplayWrapper<'a, Self>
67 omit_verbose_types: false,
68 display_target: DisplayTarget::Diagnostics,
72 /// Returns a `Display`able type that is human-readable and tries to be succinct.
73 /// Use this for showing types to the user where space is constrained (e.g. doc popups)
74 fn display_truncated<'a>(
76 db: &'a dyn HirDatabase,
77 max_size: Option<usize>,
78 ) -> HirDisplayWrapper<'a, Self>
86 omit_verbose_types: true,
87 display_target: DisplayTarget::Diagnostics,
91 /// Returns a String representation of `self` that can be inserted into the given module.
92 /// Use this when generating code (e.g. assists)
93 fn display_source_code<'a>(
95 db: &'a dyn HirDatabase,
97 ) -> Result<String, DisplaySourceCodeError> {
98 let mut result = String::new();
99 match self.hir_fmt(&mut HirFormatter {
102 buf: String::with_capacity(20),
105 omit_verbose_types: false,
106 display_target: DisplayTarget::SourceCode { module_id },
109 Err(HirDisplayError::FmtError) => panic!("Writing to String can't fail!"),
110 Err(HirDisplayError::DisplaySourceCodeError(e)) => return Err(e),
115 /// Returns a String representation of `self` for test purposes
116 fn display_test<'a>(&'a self, db: &'a dyn HirDatabase) -> HirDisplayWrapper<'a, Self>
124 omit_verbose_types: false,
125 display_target: DisplayTarget::Test,
130 impl<'a> HirFormatter<'a> {
131 pub fn write_joined<T: HirDisplay>(
133 iter: impl IntoIterator<Item = T>,
135 ) -> Result<(), HirDisplayError> {
136 let mut first = true;
139 write!(self, "{}", sep)?;
147 /// This allows using the `write!` macro directly with a `HirFormatter`.
148 pub fn write_fmt(&mut self, args: fmt::Arguments) -> Result<(), HirDisplayError> {
149 // We write to a buffer first to track output size
151 fmt::write(&mut self.buf, args)?;
152 self.curr_size += self.buf.len();
154 // Then we write to the internal formatter from the buffer
155 self.fmt.write_str(&self.buf).map_err(HirDisplayError::from)
158 pub fn should_truncate(&self) -> bool {
159 if let Some(max_size) = self.max_size {
160 self.curr_size >= max_size
166 pub fn omit_verbose_types(&self) -> bool {
167 self.omit_verbose_types
171 #[derive(Clone, Copy)]
172 pub enum DisplayTarget {
173 /// Display types for inlays, doc popups, autocompletion, etc...
174 /// Showing `{unknown}` or not qualifying paths is fine here.
175 /// There's no reason for this to fail.
177 /// Display types for inserting them in source files.
178 /// The generated code should compile, so paths need to be qualified.
179 SourceCode { module_id: ModuleId },
180 /// Only for test purpose to keep real types
185 fn is_source_code(&self) -> bool {
186 matches!(self, Self::SourceCode { .. })
188 fn is_test(&self) -> bool {
189 matches!(self, Self::Test)
194 pub enum DisplaySourceCodeError {
200 pub enum HirDisplayError {
201 /// Errors that can occur when generating source code
202 DisplaySourceCodeError(DisplaySourceCodeError),
203 /// `FmtError` is required to be compatible with std::fmt::Display
206 impl From<fmt::Error> for HirDisplayError {
207 fn from(_: fmt::Error) -> Self {
212 pub struct HirDisplayWrapper<'a, T> {
213 db: &'a dyn HirDatabase,
215 max_size: Option<usize>,
216 omit_verbose_types: bool,
217 display_target: DisplayTarget,
220 impl<'a, T> fmt::Display for HirDisplayWrapper<'a, T>
224 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
225 match self.t.hir_fmt(&mut HirFormatter {
228 buf: String::with_capacity(20),
230 max_size: self.max_size,
231 omit_verbose_types: self.omit_verbose_types,
232 display_target: self.display_target,
235 Err(HirDisplayError::FmtError) => Err(fmt::Error),
236 Err(HirDisplayError::DisplaySourceCodeError(_)) => {
237 // This should never happen
238 panic!("HirDisplay failed when calling Display::fmt!")
244 const TYPE_HINT_TRUNCATION: &str = "…";
246 impl<T: HirDisplay> HirDisplay for &'_ T {
247 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
248 HirDisplay::hir_fmt(*self, f)
252 impl HirDisplay for ProjectionTy {
253 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
254 if f.should_truncate() {
255 return write!(f, "{}", TYPE_HINT_TRUNCATION);
258 let trait_ = f.db.trait_data(self.trait_(f.db));
259 let first_parameter = self.self_type_parameter(&Interner).into_displayable(
262 f.omit_verbose_types,
265 write!(f, "<{} as {}", first_parameter, 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) => {
345 t.into_displayable(f.db, f.max_size, f.omit_verbose_types, f.display_target);
347 if matches!(self.kind(&Interner), TyKind::Raw(..)) {
352 Mutability::Not => "const ",
353 Mutability::Mut => "mut ",
361 Mutability::Not => "",
362 Mutability::Mut => "mut ",
367 // FIXME: all this just to decide whether to use parentheses...
369 let predicates: Vec<_> = match t.kind(&Interner) {
370 TyKind::Dyn(dyn_ty) if dyn_ty.bounds.skip_binders().interned().len() > 1 => {
371 dyn_ty.bounds.skip_binders().interned().iter().cloned().collect()
373 &TyKind::Alias(AliasTy::Opaque(OpaqueTy {
375 substitution: ref parameters,
377 let impl_trait_id = f.db.lookup_intern_impl_trait_id(opaque_ty_id.into());
378 if let ImplTraitId::ReturnTypeImplTrait(func, idx) = impl_trait_id {
380 f.db.return_type_impl_traits(func)
381 .expect("impl trait id without data");
384 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
385 let bounds = data.substitute(&Interner, parameters);
386 bounds.into_value_and_skipped_binders().0
394 if let Some(WhereClause::Implemented(trait_ref)) =
395 predicates.get(0).map(|b| b.skip_binders())
397 let trait_ = trait_ref.hir_trait_id();
398 if fn_traits(f.db.upcast(), trait_).any(|it| it == trait_)
399 && predicates.len() <= 2
401 return write!(f, "{}", ty_display);
405 if predicates.len() > 1 {
407 write!(f, "{}", ty_display)?;
410 write!(f, "{}", ty_display)?;
413 TyKind::Tuple(_, substs) => {
414 if substs.len(&Interner) == 1 {
416 substs.at(&Interner, 0).hir_fmt(f)?;
420 f.write_joined(&*substs.interned(), ", ")?;
424 TyKind::Function(fn_ptr) => {
425 let sig = CallableSig::from_fn_ptr(fn_ptr);
428 TyKind::FnDef(def, parameters) => {
429 let def = from_chalk(f.db, *def);
430 let sig = f.db.callable_item_signature(def).substitute(&Interner, parameters);
432 CallableDefId::FunctionId(ff) => {
433 write!(f, "fn {}", f.db.function_data(ff).name)?
435 CallableDefId::StructId(s) => write!(f, "{}", f.db.struct_data(s).name)?,
436 CallableDefId::EnumVariantId(e) => {
437 write!(f, "{}", f.db.enum_data(e.parent).variants[e.local_id].name)?
440 if parameters.len(&Interner) > 0 {
441 let generics = generics(f.db.upcast(), def.into());
442 let (parent_params, self_param, type_params, _impl_trait_params) =
443 generics.provenance_split();
444 let total_len = parent_params + self_param + type_params;
445 // We print all params except implicit impl Trait params. Still a bit weird; should we leave out parent and self?
448 f.write_joined(¶meters.interned()[..total_len], ", ")?;
453 f.write_joined(sig.params(), ", ")?;
457 let ret_display = ret.into_displayable(
460 f.omit_verbose_types,
464 write!(f, " -> {}", ret_display)?;
467 TyKind::Adt(AdtId(def_id), parameters) => {
468 match f.display_target {
469 DisplayTarget::Diagnostics | DisplayTarget::Test => {
470 let name = match *def_id {
471 hir_def::AdtId::StructId(it) => f.db.struct_data(it).name.clone(),
472 hir_def::AdtId::UnionId(it) => f.db.union_data(it).name.clone(),
473 hir_def::AdtId::EnumId(it) => f.db.enum_data(it).name.clone(),
475 write!(f, "{}", name)?;
477 DisplayTarget::SourceCode { module_id } => {
478 if let Some(path) = find_path::find_path(
480 ItemInNs::Types((*def_id).into()),
483 write!(f, "{}", path)?;
485 return Err(HirDisplayError::DisplaySourceCodeError(
486 DisplaySourceCodeError::PathNotFound,
492 if parameters.len(&Interner) > 0 {
493 let parameters_to_write = if f.display_target.is_source_code()
494 || f.omit_verbose_types()
497 .as_generic_def(f.db)
498 .map(|generic_def_id| f.db.generic_defaults(generic_def_id))
499 .filter(|defaults| !defaults.is_empty())
501 None => parameters.interned().as_ref(),
502 Some(default_parameters) => {
503 let mut default_from = 0;
504 for (i, parameter) in parameters.iter(&Interner).enumerate() {
506 parameter.assert_ty_ref(&Interner).kind(&Interner),
507 default_parameters.get(i),
509 (&TyKind::Error, _) | (_, None) => {
510 default_from = i + 1;
512 (_, Some(default_parameter)) => {
514 default_parameter.clone().substitute(
516 &subst_prefix(parameters, i),
518 if parameter.assert_ty_ref(&Interner) != &actual_default
520 default_from = i + 1;
525 ¶meters.interned()[0..default_from]
529 parameters.interned().as_ref()
531 if !parameters_to_write.is_empty() {
533 f.write_joined(parameters_to_write, ", ")?;
538 TyKind::AssociatedType(assoc_type_id, parameters) => {
539 let type_alias = from_assoc_type_id(*assoc_type_id);
540 let trait_ = match type_alias.lookup(f.db.upcast()).container {
541 AssocContainerId::TraitId(it) => it,
542 _ => panic!("not an associated type"),
544 let trait_ = f.db.trait_data(trait_);
545 let type_alias_data = f.db.type_alias_data(type_alias);
547 // Use placeholder associated types when the target is test (https://rust-lang.github.io/chalk/book/clauses/type_equality.html#placeholder-associated-types)
548 if f.display_target.is_test() {
549 write!(f, "{}::{}", trait_.name, type_alias_data.name)?;
550 if parameters.len(&Interner) > 0 {
552 f.write_joined(&*parameters.interned(), ", ")?;
556 let projection_ty = ProjectionTy {
557 associated_ty_id: to_assoc_type_id(type_alias),
558 substitution: parameters.clone(),
561 projection_ty.hir_fmt(f)?;
564 TyKind::Foreign(type_alias) => {
565 let type_alias = f.db.type_alias_data(from_foreign_def_id(*type_alias));
566 write!(f, "{}", type_alias.name)?;
568 TyKind::OpaqueType(opaque_ty_id, parameters) => {
569 let impl_trait_id = f.db.lookup_intern_impl_trait_id((*opaque_ty_id).into());
570 match impl_trait_id {
571 ImplTraitId::ReturnTypeImplTrait(func, idx) => {
573 f.db.return_type_impl_traits(func).expect("impl trait id without data");
576 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
577 let bounds = data.substitute(&Interner, ¶meters);
578 write_bounds_like_dyn_trait_with_prefix("impl", bounds.skip_binders(), f)?;
579 // FIXME: it would maybe be good to distinguish this from the alias type (when debug printing), and to show the substitution
581 ImplTraitId::AsyncBlockTypeImplTrait(..) => {
582 write!(f, "impl Future<Output = ")?;
583 parameters.at(&Interner, 0).hir_fmt(f)?;
588 TyKind::Closure(.., substs) => {
589 if f.display_target.is_source_code() {
590 return Err(HirDisplayError::DisplaySourceCodeError(
591 DisplaySourceCodeError::Closure,
594 let sig = substs.at(&Interner, 0).assert_ty_ref(&Interner).callable_sig(f.db);
595 if let Some(sig) = sig {
596 if sig.params().is_empty() {
598 } else if f.omit_verbose_types() {
599 write!(f, "|{}|", TYPE_HINT_TRUNCATION)?;
602 f.write_joined(sig.params(), ", ")?;
606 let ret_display = sig.ret().into_displayable(
609 f.omit_verbose_types,
612 write!(f, " -> {}", ret_display)?;
614 write!(f, "{{closure}}")?;
617 TyKind::Placeholder(idx) => {
618 let id = from_placeholder_idx(f.db, *idx);
619 let generics = generics(f.db.upcast(), id.parent);
620 let param_data = &generics.params.types[id.local_id];
621 match param_data.provenance {
622 TypeParamProvenance::TypeParamList | TypeParamProvenance::TraitSelf => {
623 write!(f, "{}", param_data.name.clone().unwrap_or_else(Name::missing))?
625 TypeParamProvenance::ArgumentImplTrait => {
626 let substs = generics.type_params_subst(f.db);
628 f.db.generic_predicates(id.parent)
630 .map(|pred| pred.clone().substitute(&Interner, &substs))
631 .filter(|wc| match &wc.skip_binders() {
632 WhereClause::Implemented(tr) => {
633 tr.self_type_parameter(&Interner) == self
635 WhereClause::AliasEq(AliasEq {
636 alias: AliasTy::Projection(proj),
638 }) => proj.self_type_parameter(&Interner) == self,
641 .collect::<Vec<_>>();
642 write_bounds_like_dyn_trait_with_prefix("impl", &bounds, f)?;
646 TyKind::BoundVar(idx) => idx.hir_fmt(f)?,
647 TyKind::Dyn(dyn_ty) => {
648 write_bounds_like_dyn_trait_with_prefix(
650 dyn_ty.bounds.skip_binders().interned(),
654 TyKind::Alias(AliasTy::Projection(p_ty)) => p_ty.hir_fmt(f)?,
655 TyKind::Alias(AliasTy::Opaque(opaque_ty)) => {
656 let impl_trait_id = f.db.lookup_intern_impl_trait_id(opaque_ty.opaque_ty_id.into());
657 match impl_trait_id {
658 ImplTraitId::ReturnTypeImplTrait(func, idx) => {
660 f.db.return_type_impl_traits(func).expect("impl trait id without data");
663 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
664 let bounds = data.substitute(&Interner, &opaque_ty.substitution);
665 write_bounds_like_dyn_trait_with_prefix("impl", bounds.skip_binders(), f)?;
667 ImplTraitId::AsyncBlockTypeImplTrait(..) => {
668 write!(f, "{{async block}}")?;
673 if f.display_target.is_source_code() {
674 return Err(HirDisplayError::DisplaySourceCodeError(
675 DisplaySourceCodeError::UnknownType,
678 write!(f, "{{unknown}}")?;
680 TyKind::InferenceVar(..) => write!(f, "_")?,
686 impl HirDisplay for CallableSig {
687 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
689 f.write_joined(self.params(), ", ")?;
691 if self.params().is_empty() {
698 let ret = self.ret();
701 ret.into_displayable(f.db, f.max_size, f.omit_verbose_types, f.display_target);
702 write!(f, " -> {}", ret_display)?;
708 fn fn_traits(db: &dyn DefDatabase, trait_: TraitId) -> impl Iterator<Item = TraitId> {
709 let krate = trait_.lookup(db).container.krate();
711 db.lang_item(krate, "fn".into()),
712 db.lang_item(krate, "fn_mut".into()),
713 db.lang_item(krate, "fn_once".into()),
715 array::IntoIter::new(fn_traits).into_iter().flatten().flat_map(|it| it.as_trait())
718 pub fn write_bounds_like_dyn_trait_with_prefix(
720 predicates: &[QuantifiedWhereClause],
721 f: &mut HirFormatter,
722 ) -> Result<(), HirDisplayError> {
723 write!(f, "{}", prefix)?;
724 if !predicates.is_empty() {
726 write_bounds_like_dyn_trait(predicates, f)
732 fn write_bounds_like_dyn_trait(
733 predicates: &[QuantifiedWhereClause],
734 f: &mut HirFormatter,
735 ) -> Result<(), HirDisplayError> {
736 // Note: This code is written to produce nice results (i.e.
737 // corresponding to surface Rust) for types that can occur in
738 // actual Rust. It will have weird results if the predicates
739 // aren't as expected (i.e. self types = $0, projection
740 // predicates for a certain trait come after the Implemented
741 // predicate for that trait).
742 let mut first = true;
743 let mut angle_open = false;
744 let mut is_fn_trait = false;
745 for p in predicates.iter() {
746 match p.skip_binders() {
747 WhereClause::Implemented(trait_ref) => {
748 let trait_ = trait_ref.hir_trait_id();
750 is_fn_trait = fn_traits(f.db.upcast(), trait_).any(|it| it == trait_);
752 if !is_fn_trait && angle_open {
759 // We assume that the self type is $0 (i.e. the
760 // existential) here, which is the only thing that's
761 // possible in actual Rust, and hence don't print it
762 write!(f, "{}", f.db.trait_data(trait_).name)?;
763 if let [_, params @ ..] = &*trait_ref.substitution.interned() {
766 params.first().and_then(|it| it.assert_ty_ref(&Interner).as_tuple())
769 f.write_joined(&*args.interned(), ", ")?;
772 } else if !params.is_empty() {
774 f.write_joined(params, ", ")?;
775 // there might be assoc type bindings, so we leave the angle brackets open
780 WhereClause::AliasEq(alias_eq) if is_fn_trait => {
783 alias_eq.ty.hir_fmt(f)?;
785 WhereClause::AliasEq(AliasEq { ty, alias }) => {
786 // in types in actual Rust, these will always come
787 // after the corresponding Implemented predicate
794 if let AliasTy::Projection(proj) = alias {
796 f.db.type_alias_data(from_assoc_type_id(proj.associated_ty_id));
797 write!(f, "{} = ", type_alias.name)?;
811 fn hir_fmt_ext(&self, f: &mut HirFormatter, use_as: bool) -> Result<(), HirDisplayError> {
812 if f.should_truncate() {
813 return write!(f, "{}", TYPE_HINT_TRUNCATION);
816 self.self_type_parameter(&Interner).hir_fmt(f)?;
822 write!(f, "{}", f.db.trait_data(self.hir_trait_id()).name)?;
823 if self.substitution.len(&Interner) > 1 {
825 f.write_joined(&self.substitution.interned()[1..], ", ")?;
832 impl HirDisplay for TraitRef {
833 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
834 self.hir_fmt_ext(f, false)
838 impl HirDisplay for WhereClause {
839 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
840 if f.should_truncate() {
841 return write!(f, "{}", TYPE_HINT_TRUNCATION);
845 WhereClause::Implemented(trait_ref) => trait_ref.hir_fmt(f)?,
846 WhereClause::AliasEq(AliasEq { alias: AliasTy::Projection(projection_ty), ty }) => {
848 projection_ty.trait_ref(f.db).hir_fmt_ext(f, true)?;
852 f.db.type_alias_data(from_assoc_type_id(projection_ty.associated_ty_id)).name,
856 WhereClause::AliasEq(_) => write!(f, "{{error}}")?,
862 impl HirDisplay for LifetimeOutlives {
863 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
870 impl HirDisplay for Lifetime {
871 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
872 self.interned().hir_fmt(f)
876 impl HirDisplay for LifetimeData {
877 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
879 LifetimeData::BoundVar(idx) => idx.hir_fmt(f),
880 LifetimeData::InferenceVar(_) => write!(f, "_"),
881 LifetimeData::Placeholder(idx) => {
882 let id = lt_from_placeholder_idx(f.db, *idx);
883 let generics = generics(f.db.upcast(), id.parent);
884 let param_data = &generics.params.lifetimes[id.local_id];
885 write!(f, "{}", param_data.name)
887 LifetimeData::Static => write!(f, "'static"),
888 LifetimeData::Empty(_) => Ok(()),
889 LifetimeData::Erased => Ok(()),
890 LifetimeData::Phantom(_, _) => Ok(()),
895 impl HirDisplay for DomainGoal {
896 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
898 DomainGoal::Holds(wc) => {
899 write!(f, "Holds(")?;
907 pub fn write_visibility(
910 f: &mut HirFormatter,
911 ) -> Result<(), HirDisplayError> {
913 Visibility::Public => write!(f, "pub "),
914 Visibility::Module(vis_id) => {
915 let def_map = module_id.def_map(f.db.upcast());
916 let root_module_id = def_map.module_id(def_map.root());
917 if vis_id == module_id {
918 // pub(self) or omitted
920 } else if root_module_id == vis_id {
921 write!(f, "pub(crate) ")
922 } else if module_id.containing_module(f.db.upcast()) == Some(vis_id) {
923 write!(f, "pub(super) ")
925 write!(f, "pub(in ...) ")
931 impl HirDisplay for TypeRef {
932 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
934 TypeRef::Never => write!(f, "!")?,
935 TypeRef::Placeholder => write!(f, "_")?,
936 TypeRef::Tuple(elems) => {
938 f.write_joined(elems, ", ")?;
939 if elems.len() == 1 {
944 TypeRef::Path(path) => path.hir_fmt(f)?,
945 TypeRef::RawPtr(inner, mutability) => {
946 let mutability = match mutability {
947 hir_def::type_ref::Mutability::Shared => "*const ",
948 hir_def::type_ref::Mutability::Mut => "*mut ",
950 write!(f, "{}", mutability)?;
953 TypeRef::Reference(inner, lifetime, mutability) => {
954 let mutability = match mutability {
955 hir_def::type_ref::Mutability::Shared => "",
956 hir_def::type_ref::Mutability::Mut => "mut ",
959 if let Some(lifetime) = lifetime {
960 write!(f, "{} ", lifetime.name)?;
962 write!(f, "{}", mutability)?;
965 TypeRef::Array(inner) => {
968 // FIXME: Array length?
971 TypeRef::Slice(inner) => {
976 TypeRef::Fn(tys, is_varargs) => {
977 // FIXME: Function pointer qualifiers.
979 f.write_joined(&tys[..tys.len() - 1], ", ")?;
981 write!(f, "{}...", if tys.len() == 1 { "" } else { ", " })?;
984 let ret_ty = tys.last().unwrap();
986 TypeRef::Tuple(tup) if tup.is_empty() => {}
993 TypeRef::ImplTrait(bounds) => {
995 f.write_joined(bounds, " + ")?;
997 TypeRef::DynTrait(bounds) => {
999 f.write_joined(bounds, " + ")?;
1001 TypeRef::Error => write!(f, "{{error}}")?,
1007 impl HirDisplay for TypeBound {
1008 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1010 TypeBound::Path(path) => path.hir_fmt(f),
1011 TypeBound::Lifetime(lifetime) => write!(f, "{}", lifetime.name),
1012 TypeBound::Error => write!(f, "{{error}}"),
1017 impl HirDisplay for Path {
1018 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1019 match (self.type_anchor(), self.kind()) {
1020 (Some(anchor), _) => {
1025 (_, PathKind::Plain) => {}
1026 (_, PathKind::Abs) => write!(f, "::")?,
1027 (_, PathKind::Crate) => write!(f, "crate")?,
1028 (_, PathKind::Super(0)) => write!(f, "self")?,
1029 (_, PathKind::Super(n)) => {
1030 write!(f, "super")?;
1032 write!(f, "::super")?;
1035 (_, PathKind::DollarCrate(_)) => write!(f, "{{extern_crate}}")?,
1038 for (seg_idx, segment) in self.segments().iter().enumerate() {
1042 write!(f, "{}", segment.name)?;
1043 if let Some(generic_args) = segment.args_and_bindings {
1044 // We should be in type context, so format as `Foo<Bar>` instead of `Foo::<Bar>`.
1045 // Do we actually format expressions?
1047 let mut first = true;
1048 for arg in &generic_args.args {
1051 if generic_args.has_self_type {
1052 // FIXME: Convert to `<Ty as Trait>` form.
1053 write!(f, "Self = ")?;
1060 for binding in &generic_args.bindings {
1066 write!(f, "{}", binding.name)?;
1067 match &binding.type_ref {
1074 f.write_joined(&binding.bounds, " + ")?;
1085 impl HirDisplay for hir_def::path::GenericArg {
1086 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1088 hir_def::path::GenericArg::Type(ty) => ty.hir_fmt(f),
1089 hir_def::path::GenericArg::Lifetime(lifetime) => write!(f, "{}", lifetime.name),