1 //! The `HirDisplay` trait, which serves two purposes: Turning various bits from
2 //! HIR back into source code, and just displaying them for debugging/testing
10 use chalk_ir::BoundVar;
15 generics::TypeParamProvenance,
16 intern::{Internable, Interned},
18 path::{Path, PathKind},
19 type_ref::{TypeBound, TypeRef},
20 visibility::Visibility,
21 AssocContainerId, Lookup, ModuleId, TraitId,
23 use hir_expand::{hygiene::Hygiene, name::Name};
26 const_from_placeholder_idx, db::HirDatabase, from_assoc_type_id, from_foreign_def_id,
27 from_placeholder_idx, lt_from_placeholder_idx, mapping::from_chalk, primitive, subst_prefix,
28 to_assoc_type_id, utils::generics, AdtId, AliasEq, AliasTy, CallableDefId, CallableSig, Const,
29 ConstValue, DomainGoal, GenericArg, ImplTraitId, Interner, Lifetime, LifetimeData,
30 LifetimeOutlives, Mutability, OpaqueTy, ProjectionTy, ProjectionTyExt, QuantifiedWhereClause,
31 Scalar, TraitRef, TraitRefExt, Ty, TyExt, TyKind, WhereClause,
34 pub struct HirFormatter<'a> {
35 pub db: &'a dyn HirDatabase,
36 fmt: &'a mut dyn fmt::Write,
39 pub(crate) max_size: Option<usize>,
40 omit_verbose_types: bool,
41 display_target: DisplayTarget,
44 pub trait HirDisplay {
45 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError>;
47 /// Returns a `Display`able type that is human-readable.
48 fn into_displayable<'a>(
50 db: &'a dyn HirDatabase,
51 max_size: Option<usize>,
52 omit_verbose_types: bool,
53 display_target: DisplayTarget,
54 ) -> HirDisplayWrapper<'a, Self>
59 !matches!(display_target, DisplayTarget::SourceCode { .. }),
60 "HirDisplayWrapper cannot fail with DisplaySourceCodeError, use HirDisplay::hir_fmt directly instead"
62 HirDisplayWrapper { db, t: self, max_size, omit_verbose_types, display_target }
65 /// Returns a `Display`able type that is human-readable.
66 /// Use this for showing types to the user (e.g. diagnostics)
67 fn display<'a>(&'a self, db: &'a dyn HirDatabase) -> HirDisplayWrapper<'a, Self>
75 omit_verbose_types: false,
76 display_target: DisplayTarget::Diagnostics,
80 /// Returns a `Display`able type that is human-readable and tries to be succinct.
81 /// Use this for showing types to the user where space is constrained (e.g. doc popups)
82 fn display_truncated<'a>(
84 db: &'a dyn HirDatabase,
85 max_size: Option<usize>,
86 ) -> HirDisplayWrapper<'a, Self>
94 omit_verbose_types: true,
95 display_target: DisplayTarget::Diagnostics,
99 /// Returns a String representation of `self` that can be inserted into the given module.
100 /// Use this when generating code (e.g. assists)
101 fn display_source_code<'a>(
103 db: &'a dyn HirDatabase,
105 ) -> Result<String, DisplaySourceCodeError> {
106 let mut result = String::new();
107 match self.hir_fmt(&mut HirFormatter {
110 buf: String::with_capacity(20),
113 omit_verbose_types: false,
114 display_target: DisplayTarget::SourceCode { module_id },
117 Err(HirDisplayError::FmtError) => panic!("Writing to String can't fail!"),
118 Err(HirDisplayError::DisplaySourceCodeError(e)) => return Err(e),
123 /// Returns a String representation of `self` for test purposes
124 fn display_test<'a>(&'a self, db: &'a dyn HirDatabase) -> HirDisplayWrapper<'a, Self>
132 omit_verbose_types: false,
133 display_target: DisplayTarget::Test,
138 impl<'a> HirFormatter<'a> {
139 pub fn write_joined<T: HirDisplay>(
141 iter: impl IntoIterator<Item = T>,
143 ) -> Result<(), HirDisplayError> {
144 let mut first = true;
147 write!(self, "{}", sep)?;
155 /// This allows using the `write!` macro directly with a `HirFormatter`.
156 pub fn write_fmt(&mut self, args: fmt::Arguments) -> Result<(), HirDisplayError> {
157 // We write to a buffer first to track output size
159 fmt::write(&mut self.buf, args)?;
160 self.curr_size += self.buf.len();
162 // Then we write to the internal formatter from the buffer
163 self.fmt.write_str(&self.buf).map_err(HirDisplayError::from)
166 pub fn should_truncate(&self) -> bool {
167 if let Some(max_size) = self.max_size {
168 self.curr_size >= max_size
174 pub fn omit_verbose_types(&self) -> bool {
175 self.omit_verbose_types
179 #[derive(Clone, Copy)]
180 pub enum DisplayTarget {
181 /// Display types for inlays, doc popups, autocompletion, etc...
182 /// Showing `{unknown}` or not qualifying paths is fine here.
183 /// There's no reason for this to fail.
185 /// Display types for inserting them in source files.
186 /// The generated code should compile, so paths need to be qualified.
187 SourceCode { module_id: ModuleId },
188 /// Only for test purpose to keep real types
193 fn is_source_code(&self) -> bool {
194 matches!(self, Self::SourceCode { .. })
196 fn is_test(&self) -> bool {
197 matches!(self, Self::Test)
202 pub enum DisplaySourceCodeError {
208 pub enum HirDisplayError {
209 /// Errors that can occur when generating source code
210 DisplaySourceCodeError(DisplaySourceCodeError),
211 /// `FmtError` is required to be compatible with std::fmt::Display
214 impl From<fmt::Error> for HirDisplayError {
215 fn from(_: fmt::Error) -> Self {
220 pub struct HirDisplayWrapper<'a, T> {
221 db: &'a dyn HirDatabase,
223 max_size: Option<usize>,
224 omit_verbose_types: bool,
225 display_target: DisplayTarget,
228 impl<'a, T> fmt::Display for HirDisplayWrapper<'a, T>
232 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
233 match self.t.hir_fmt(&mut HirFormatter {
236 buf: String::with_capacity(20),
238 max_size: self.max_size,
239 omit_verbose_types: self.omit_verbose_types,
240 display_target: self.display_target,
243 Err(HirDisplayError::FmtError) => Err(fmt::Error),
244 Err(HirDisplayError::DisplaySourceCodeError(_)) => {
245 // This should never happen
246 panic!("HirDisplay::hir_fmt failed with DisplaySourceCodeError when calling Display::fmt!")
252 const TYPE_HINT_TRUNCATION: &str = "…";
254 impl<T: HirDisplay> HirDisplay for &'_ T {
255 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
256 HirDisplay::hir_fmt(*self, f)
260 impl<T: HirDisplay + Internable> HirDisplay for Interned<T> {
261 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
262 HirDisplay::hir_fmt(self.as_ref(), f)
266 impl HirDisplay for ProjectionTy {
267 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
268 if f.should_truncate() {
269 return write!(f, "{}", TYPE_HINT_TRUNCATION);
272 let trait_ = f.db.trait_data(self.trait_(f.db));
274 self.self_type_parameter(&Interner).hir_fmt(f)?;
275 write!(f, " as {}", trait_.name)?;
276 if self.substitution.len(&Interner) > 1 {
278 f.write_joined(&self.substitution.as_slice(&Interner)[1..], ", ")?;
281 write!(f, ">::{}", f.db.type_alias_data(from_assoc_type_id(self.associated_ty_id)).name)?;
286 impl HirDisplay for OpaqueTy {
287 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
288 if f.should_truncate() {
289 return write!(f, "{}", TYPE_HINT_TRUNCATION);
292 self.substitution.at(&Interner, 0).hir_fmt(f)
296 impl HirDisplay for GenericArg {
297 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
298 match self.interned() {
299 crate::GenericArgData::Ty(ty) => ty.hir_fmt(f),
300 crate::GenericArgData::Lifetime(lt) => lt.hir_fmt(f),
301 crate::GenericArgData::Const(c) => c.hir_fmt(f),
306 impl HirDisplay for Const {
307 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
308 let data = self.interned();
310 ConstValue::BoundVar(idx) => idx.hir_fmt(f),
311 ConstValue::InferenceVar(..) => write!(f, "_"),
312 ConstValue::Placeholder(idx) => {
313 let id = const_from_placeholder_idx(f.db, idx);
314 let generics = generics(f.db.upcast(), id.parent);
315 let param_data = &generics.params.consts[id.local_id];
316 write!(f, "{}", param_data.name)
318 ConstValue::Concrete(c) => write!(f, "{}", c.interned),
323 impl HirDisplay for BoundVar {
324 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
325 write!(f, "?{}.{}", self.debruijn.depth(), self.index)
329 impl HirDisplay for Ty {
330 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
331 if f.should_truncate() {
332 return write!(f, "{}", TYPE_HINT_TRUNCATION);
335 match self.kind(&Interner) {
336 TyKind::Never => write!(f, "!")?,
337 TyKind::Str => write!(f, "str")?,
338 TyKind::Scalar(Scalar::Bool) => write!(f, "bool")?,
339 TyKind::Scalar(Scalar::Char) => write!(f, "char")?,
340 &TyKind::Scalar(Scalar::Float(t)) => write!(f, "{}", primitive::float_ty_to_string(t))?,
341 &TyKind::Scalar(Scalar::Int(t)) => write!(f, "{}", primitive::int_ty_to_string(t))?,
342 &TyKind::Scalar(Scalar::Uint(t)) => write!(f, "{}", primitive::uint_ty_to_string(t))?,
343 TyKind::Slice(t) => {
348 TyKind::Array(t, c) => {
355 TyKind::Raw(m, t) | TyKind::Ref(m, _, t) => {
356 if matches!(self.kind(&Interner), TyKind::Raw(..)) {
361 Mutability::Not => "const ",
362 Mutability::Mut => "mut ",
370 Mutability::Not => "",
371 Mutability::Mut => "mut ",
376 // FIXME: all this just to decide whether to use parentheses...
378 let predicates: Vec<_> = match t.kind(&Interner) {
379 TyKind::Dyn(dyn_ty) if dyn_ty.bounds.skip_binders().interned().len() > 1 => {
380 dyn_ty.bounds.skip_binders().interned().iter().cloned().collect()
382 &TyKind::Alias(AliasTy::Opaque(OpaqueTy {
384 substitution: ref parameters,
386 let impl_trait_id = f.db.lookup_intern_impl_trait_id(opaque_ty_id.into());
387 if let ImplTraitId::ReturnTypeImplTrait(func, idx) = impl_trait_id {
389 f.db.return_type_impl_traits(func)
390 .expect("impl trait id without data");
393 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
394 let bounds = data.substitute(&Interner, parameters);
395 bounds.into_value_and_skipped_binders().0
403 if let Some(WhereClause::Implemented(trait_ref)) =
404 predicates.get(0).map(|b| b.skip_binders())
406 let trait_ = trait_ref.hir_trait_id();
407 if fn_traits(f.db.upcast(), trait_).any(|it| it == trait_)
408 && predicates.len() <= 2
414 if predicates.len() > 1 {
422 TyKind::Tuple(_, substs) => {
423 if substs.len(&Interner) == 1 {
425 substs.at(&Interner, 0).hir_fmt(f)?;
429 f.write_joined(&*substs.as_slice(&Interner), ", ")?;
433 TyKind::Function(fn_ptr) => {
434 let sig = CallableSig::from_fn_ptr(fn_ptr);
437 TyKind::FnDef(def, parameters) => {
438 let def = from_chalk(f.db, *def);
439 let sig = f.db.callable_item_signature(def).substitute(&Interner, parameters);
441 CallableDefId::FunctionId(ff) => {
442 write!(f, "fn {}", f.db.function_data(ff).name)?
444 CallableDefId::StructId(s) => write!(f, "{}", f.db.struct_data(s).name)?,
445 CallableDefId::EnumVariantId(e) => {
446 write!(f, "{}", f.db.enum_data(e.parent).variants[e.local_id].name)?
449 if parameters.len(&Interner) > 0 {
450 let generics = generics(f.db.upcast(), def.into());
451 let (parent_params, self_param, type_params, _impl_trait_params) =
452 generics.provenance_split();
453 let total_len = parent_params + self_param + type_params;
454 // We print all params except implicit impl Trait params. Still a bit weird; should we leave out parent and self?
457 f.write_joined(¶meters.as_slice(&Interner)[..total_len], ", ")?;
462 f.write_joined(sig.params(), ", ")?;
470 TyKind::Adt(AdtId(def_id), parameters) => {
471 match f.display_target {
472 DisplayTarget::Diagnostics | DisplayTarget::Test => {
473 let name = match *def_id {
474 hir_def::AdtId::StructId(it) => f.db.struct_data(it).name.clone(),
475 hir_def::AdtId::UnionId(it) => f.db.union_data(it).name.clone(),
476 hir_def::AdtId::EnumId(it) => f.db.enum_data(it).name.clone(),
478 write!(f, "{}", name)?;
480 DisplayTarget::SourceCode { module_id } => {
481 if let Some(path) = find_path::find_path(
483 ItemInNs::Types((*def_id).into()),
486 write!(f, "{}", path)?;
488 return Err(HirDisplayError::DisplaySourceCodeError(
489 DisplaySourceCodeError::PathNotFound,
495 if parameters.len(&Interner) > 0 {
496 let parameters_to_write = if f.display_target.is_source_code()
497 || f.omit_verbose_types()
500 .as_generic_def(f.db)
501 .map(|generic_def_id| f.db.generic_defaults(generic_def_id))
502 .filter(|defaults| !defaults.is_empty())
504 None => parameters.as_slice(&Interner),
505 Some(default_parameters) => {
506 let mut default_from = 0;
507 for (i, parameter) in parameters.iter(&Interner).enumerate() {
509 parameter.assert_ty_ref(&Interner).kind(&Interner),
510 default_parameters.get(i),
512 (&TyKind::Error, _) | (_, None) => {
513 default_from = i + 1;
515 (_, Some(default_parameter)) => {
517 default_parameter.clone().substitute(
519 &subst_prefix(parameters, i),
521 if parameter.assert_ty_ref(&Interner) != &actual_default
523 default_from = i + 1;
528 ¶meters.as_slice(&Interner)[0..default_from]
532 parameters.as_slice(&Interner)
534 if !parameters_to_write.is_empty() {
536 f.write_joined(parameters_to_write, ", ")?;
541 TyKind::AssociatedType(assoc_type_id, parameters) => {
542 let type_alias = from_assoc_type_id(*assoc_type_id);
543 let trait_ = match type_alias.lookup(f.db.upcast()).container {
544 AssocContainerId::TraitId(it) => it,
545 _ => panic!("not an associated type"),
547 let trait_ = f.db.trait_data(trait_);
548 let type_alias_data = f.db.type_alias_data(type_alias);
550 // Use placeholder associated types when the target is test (https://rust-lang.github.io/chalk/book/clauses/type_equality.html#placeholder-associated-types)
551 if f.display_target.is_test() {
552 write!(f, "{}::{}", trait_.name, type_alias_data.name)?;
553 if parameters.len(&Interner) > 0 {
555 f.write_joined(&*parameters.as_slice(&Interner), ", ")?;
559 let projection_ty = ProjectionTy {
560 associated_ty_id: to_assoc_type_id(type_alias),
561 substitution: parameters.clone(),
564 projection_ty.hir_fmt(f)?;
567 TyKind::Foreign(type_alias) => {
568 let type_alias = f.db.type_alias_data(from_foreign_def_id(*type_alias));
569 write!(f, "{}", type_alias.name)?;
571 TyKind::OpaqueType(opaque_ty_id, parameters) => {
572 let impl_trait_id = f.db.lookup_intern_impl_trait_id((*opaque_ty_id).into());
573 match impl_trait_id {
574 ImplTraitId::ReturnTypeImplTrait(func, idx) => {
576 f.db.return_type_impl_traits(func).expect("impl trait id without data");
579 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
580 let bounds = data.substitute(&Interner, ¶meters);
581 write_bounds_like_dyn_trait_with_prefix("impl", bounds.skip_binders(), f)?;
582 // FIXME: it would maybe be good to distinguish this from the alias type (when debug printing), and to show the substitution
584 ImplTraitId::AsyncBlockTypeImplTrait(..) => {
585 write!(f, "impl Future<Output = ")?;
586 parameters.at(&Interner, 0).hir_fmt(f)?;
591 TyKind::Closure(.., substs) => {
592 if f.display_target.is_source_code() {
593 return Err(HirDisplayError::DisplaySourceCodeError(
594 DisplaySourceCodeError::Closure,
597 let sig = substs.at(&Interner, 0).assert_ty_ref(&Interner).callable_sig(f.db);
598 if let Some(sig) = sig {
599 if sig.params().is_empty() {
601 } else if f.omit_verbose_types() {
602 write!(f, "|{}|", TYPE_HINT_TRUNCATION)?;
605 f.write_joined(sig.params(), ", ")?;
610 sig.ret().hir_fmt(f)?;
612 write!(f, "{{closure}}")?;
615 TyKind::Placeholder(idx) => {
616 let id = from_placeholder_idx(f.db, *idx);
617 let generics = generics(f.db.upcast(), id.parent);
618 let param_data = &generics.params.types[id.local_id];
619 match param_data.provenance {
620 TypeParamProvenance::TypeParamList | TypeParamProvenance::TraitSelf => {
621 write!(f, "{}", param_data.name.clone().unwrap_or_else(Name::missing))?
623 TypeParamProvenance::ArgumentImplTrait => {
624 let substs = generics.type_params_subst(f.db);
626 f.db.generic_predicates(id.parent)
628 .map(|pred| pred.clone().substitute(&Interner, &substs))
629 .filter(|wc| match &wc.skip_binders() {
630 WhereClause::Implemented(tr) => {
631 &tr.self_type_parameter(&Interner) == self
633 WhereClause::AliasEq(AliasEq {
634 alias: AliasTy::Projection(proj),
636 }) => &proj.self_type_parameter(&Interner) == self,
639 .collect::<Vec<_>>();
640 write_bounds_like_dyn_trait_with_prefix("impl", &bounds, f)?;
644 TyKind::BoundVar(idx) => idx.hir_fmt(f)?,
645 TyKind::Dyn(dyn_ty) => {
646 write_bounds_like_dyn_trait_with_prefix(
648 dyn_ty.bounds.skip_binders().interned(),
652 TyKind::Alias(AliasTy::Projection(p_ty)) => p_ty.hir_fmt(f)?,
653 TyKind::Alias(AliasTy::Opaque(opaque_ty)) => {
654 let impl_trait_id = f.db.lookup_intern_impl_trait_id(opaque_ty.opaque_ty_id.into());
655 match impl_trait_id {
656 ImplTraitId::ReturnTypeImplTrait(func, idx) => {
658 f.db.return_type_impl_traits(func).expect("impl trait id without data");
661 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
662 let bounds = data.substitute(&Interner, &opaque_ty.substitution);
663 write_bounds_like_dyn_trait_with_prefix("impl", bounds.skip_binders(), f)?;
665 ImplTraitId::AsyncBlockTypeImplTrait(..) => {
666 write!(f, "{{async block}}")?;
671 if f.display_target.is_source_code() {
672 return Err(HirDisplayError::DisplaySourceCodeError(
673 DisplaySourceCodeError::UnknownType,
676 write!(f, "{{unknown}}")?;
678 TyKind::InferenceVar(..) => write!(f, "_")?,
679 TyKind::Generator(..) => write!(f, "{{generator}}")?,
680 TyKind::GeneratorWitness(..) => write!(f, "{{generator witness}}")?,
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();
707 fn fn_traits(db: &dyn DefDatabase, trait_: TraitId) -> impl Iterator<Item = TraitId> {
708 let krate = trait_.lookup(db).container.krate();
710 db.lang_item(krate, "fn".into()),
711 db.lang_item(krate, "fn_mut".into()),
712 db.lang_item(krate, "fn_once".into()),
714 array::IntoIter::new(fn_traits).into_iter().flatten().flat_map(|it| it.as_trait())
717 pub fn write_bounds_like_dyn_trait_with_prefix(
719 predicates: &[QuantifiedWhereClause],
720 f: &mut HirFormatter,
721 ) -> Result<(), HirDisplayError> {
722 write!(f, "{}", prefix)?;
723 if !predicates.is_empty() {
725 write_bounds_like_dyn_trait(predicates, f)
731 fn write_bounds_like_dyn_trait(
732 predicates: &[QuantifiedWhereClause],
733 f: &mut HirFormatter,
734 ) -> Result<(), HirDisplayError> {
735 // Note: This code is written to produce nice results (i.e.
736 // corresponding to surface Rust) for types that can occur in
737 // actual Rust. It will have weird results if the predicates
738 // aren't as expected (i.e. self types = $0, projection
739 // predicates for a certain trait come after the Implemented
740 // predicate for that trait).
741 let mut first = true;
742 let mut angle_open = false;
743 let mut is_fn_trait = false;
744 for p in predicates.iter() {
745 match p.skip_binders() {
746 WhereClause::Implemented(trait_ref) => {
747 let trait_ = trait_ref.hir_trait_id();
749 is_fn_trait = fn_traits(f.db.upcast(), trait_).any(|it| it == trait_);
751 if !is_fn_trait && angle_open {
758 // We assume that the self type is ^0.0 (i.e. the
759 // existential) here, which is the only thing that's
760 // possible in actual Rust, and hence don't print it
761 write!(f, "{}", f.db.trait_data(trait_).name)?;
762 if let [_, params @ ..] = &*trait_ref.substitution.as_slice(&Interner) {
765 params.first().and_then(|it| it.assert_ty_ref(&Interner).as_tuple())
768 f.write_joined(args.as_slice(&Interner), ", ")?;
771 } else if !params.is_empty() {
773 f.write_joined(params, ", ")?;
774 // there might be assoc type bindings, so we leave the angle brackets open
779 WhereClause::AliasEq(alias_eq) if is_fn_trait => {
782 alias_eq.ty.hir_fmt(f)?;
784 WhereClause::AliasEq(AliasEq { ty, alias }) => {
785 // in types in actual Rust, these will always come
786 // after the corresponding Implemented predicate
793 if let AliasTy::Projection(proj) = alias {
795 f.db.type_alias_data(from_assoc_type_id(proj.associated_ty_id));
796 write!(f, "{} = ", type_alias.name)?;
801 // FIXME implement these
802 WhereClause::LifetimeOutlives(_) => {}
803 WhereClause::TypeOutlives(_) => {}
813 fn fmt_trait_ref(tr: &TraitRef, f: &mut HirFormatter, use_as: bool) -> Result<(), HirDisplayError> {
814 if f.should_truncate() {
815 return write!(f, "{}", TYPE_HINT_TRUNCATION);
818 tr.self_type_parameter(&Interner).hir_fmt(f)?;
824 write!(f, "{}", f.db.trait_data(tr.hir_trait_id()).name)?;
825 if tr.substitution.len(&Interner) > 1 {
827 f.write_joined(&tr.substitution.as_slice(&Interner)[1..], ", ")?;
833 impl HirDisplay for TraitRef {
834 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
835 fmt_trait_ref(self, f, false)
839 impl HirDisplay for WhereClause {
840 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
841 if f.should_truncate() {
842 return write!(f, "{}", TYPE_HINT_TRUNCATION);
846 WhereClause::Implemented(trait_ref) => trait_ref.hir_fmt(f)?,
847 WhereClause::AliasEq(AliasEq { alias: AliasTy::Projection(projection_ty), ty }) => {
849 fmt_trait_ref(&projection_ty.trait_ref(f.db), f, true)?;
853 f.db.type_alias_data(from_assoc_type_id(projection_ty.associated_ty_id)).name,
857 WhereClause::AliasEq(_) => write!(f, "{{error}}")?,
859 // FIXME implement these
860 WhereClause::TypeOutlives(..) => {}
861 WhereClause::LifetimeOutlives(..) => {}
867 impl HirDisplay for LifetimeOutlives {
868 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
875 impl HirDisplay for Lifetime {
876 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
877 self.interned().hir_fmt(f)
881 impl HirDisplay for LifetimeData {
882 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
884 LifetimeData::BoundVar(idx) => idx.hir_fmt(f),
885 LifetimeData::InferenceVar(_) => write!(f, "_"),
886 LifetimeData::Placeholder(idx) => {
887 let id = lt_from_placeholder_idx(f.db, *idx);
888 let generics = generics(f.db.upcast(), id.parent);
889 let param_data = &generics.params.lifetimes[id.local_id];
890 write!(f, "{}", param_data.name)
892 LifetimeData::Static => write!(f, "'static"),
893 LifetimeData::Empty(_) => Ok(()),
894 LifetimeData::Erased => Ok(()),
895 LifetimeData::Phantom(_, _) => Ok(()),
900 impl HirDisplay for DomainGoal {
901 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
903 DomainGoal::Holds(wc) => {
904 write!(f, "Holds(")?;
908 _ => write!(f, "?")?,
914 pub fn write_visibility(
917 f: &mut HirFormatter,
918 ) -> Result<(), HirDisplayError> {
920 Visibility::Public => write!(f, "pub "),
921 Visibility::Module(vis_id) => {
922 let def_map = module_id.def_map(f.db.upcast());
923 let root_module_id = def_map.module_id(def_map.root());
924 if vis_id == module_id {
925 // pub(self) or omitted
927 } else if root_module_id == vis_id {
928 write!(f, "pub(crate) ")
929 } else if module_id.containing_module(f.db.upcast()) == Some(vis_id) {
930 write!(f, "pub(super) ")
932 write!(f, "pub(in ...) ")
938 impl HirDisplay for TypeRef {
939 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
941 TypeRef::Never => write!(f, "!")?,
942 TypeRef::Placeholder => write!(f, "_")?,
943 TypeRef::Tuple(elems) => {
945 f.write_joined(elems, ", ")?;
946 if elems.len() == 1 {
951 TypeRef::Path(path) => path.hir_fmt(f)?,
952 TypeRef::RawPtr(inner, mutability) => {
953 let mutability = match mutability {
954 hir_def::type_ref::Mutability::Shared => "*const ",
955 hir_def::type_ref::Mutability::Mut => "*mut ",
957 write!(f, "{}", mutability)?;
960 TypeRef::Reference(inner, lifetime, mutability) => {
961 let mutability = match mutability {
962 hir_def::type_ref::Mutability::Shared => "",
963 hir_def::type_ref::Mutability::Mut => "mut ",
966 if let Some(lifetime) = lifetime {
967 write!(f, "{} ", lifetime.name)?;
969 write!(f, "{}", mutability)?;
972 TypeRef::Array(inner, len) => {
975 write!(f, "; {}]", len)?;
977 TypeRef::Slice(inner) => {
982 TypeRef::Fn(tys, is_varargs) => {
983 // FIXME: Function pointer qualifiers.
985 f.write_joined(&tys[..tys.len() - 1], ", ")?;
987 write!(f, "{}...", if tys.len() == 1 { "" } else { ", " })?;
990 let ret_ty = tys.last().unwrap();
992 TypeRef::Tuple(tup) if tup.is_empty() => {}
999 TypeRef::ImplTrait(bounds) => {
1000 write!(f, "impl ")?;
1001 f.write_joined(bounds, " + ")?;
1003 TypeRef::DynTrait(bounds) => {
1005 f.write_joined(bounds, " + ")?;
1007 TypeRef::Macro(macro_call) => {
1008 let macro_call = macro_call.to_node(f.db.upcast());
1009 let ctx = body::LowerCtx::with_hygiene(f.db.upcast(), &Hygiene::new_unhygienic());
1010 match macro_call.path() {
1011 Some(path) => match Path::from_src(path, &ctx) {
1012 Some(path) => path.hir_fmt(f)?,
1013 None => write!(f, "{{macro}}")?,
1015 None => write!(f, "{{macro}}")?,
1017 write!(f, "!(..)")?;
1019 TypeRef::Error => write!(f, "{{error}}")?,
1025 impl HirDisplay for TypeBound {
1026 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1028 TypeBound::Path(path) => path.hir_fmt(f),
1029 TypeBound::Lifetime(lifetime) => write!(f, "{}", lifetime.name),
1030 TypeBound::Error => write!(f, "{{error}}"),
1035 impl HirDisplay for Path {
1036 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1037 match (self.type_anchor(), self.kind()) {
1038 (Some(anchor), _) => {
1043 (_, PathKind::Plain) => {}
1044 (_, PathKind::Abs) => write!(f, "::")?,
1045 (_, PathKind::Crate) => write!(f, "crate")?,
1046 (_, PathKind::Super(0)) => write!(f, "self")?,
1047 (_, PathKind::Super(n)) => {
1048 write!(f, "super")?;
1050 write!(f, "::super")?;
1053 (_, PathKind::DollarCrate(_)) => write!(f, "{{extern_crate}}")?,
1056 for (seg_idx, segment) in self.segments().iter().enumerate() {
1060 write!(f, "{}", segment.name)?;
1061 if let Some(generic_args) = segment.args_and_bindings {
1062 // We should be in type context, so format as `Foo<Bar>` instead of `Foo::<Bar>`.
1063 // Do we actually format expressions?
1065 let mut first = true;
1066 for arg in &generic_args.args {
1069 if generic_args.has_self_type {
1070 // FIXME: Convert to `<Ty as Trait>` form.
1071 write!(f, "Self = ")?;
1078 for binding in &generic_args.bindings {
1084 write!(f, "{}", binding.name)?;
1085 match &binding.type_ref {
1092 f.write_joined(&binding.bounds, " + ")?;
1103 impl HirDisplay for hir_def::path::GenericArg {
1104 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1106 hir_def::path::GenericArg::Type(ty) => ty.hir_fmt(f),
1107 hir_def::path::GenericArg::Lifetime(lifetime) => write!(f, "{}", lifetime.name),