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,
17 path::{Path, PathKind},
18 type_ref::{TypeBound, TypeRef},
19 visibility::Visibility,
20 AssocContainerId, Lookup, ModuleId, TraitId,
22 use hir_expand::{hygiene::Hygiene, name::Name};
25 const_from_placeholder_idx, db::HirDatabase, from_assoc_type_id, from_foreign_def_id,
26 from_placeholder_idx, lt_from_placeholder_idx, mapping::from_chalk, primitive, subst_prefix,
27 to_assoc_type_id, utils::generics, AdtId, AliasEq, AliasTy, CallableDefId, CallableSig, Const,
28 ConstValue, DomainGoal, GenericArg, ImplTraitId, Interner, Lifetime, LifetimeData,
29 LifetimeOutlives, Mutability, OpaqueTy, ProjectionTy, ProjectionTyExt, QuantifiedWhereClause,
30 Scalar, TraitRef, TraitRefExt, Ty, TyExt, TyKind, WhereClause,
33 pub struct HirFormatter<'a> {
34 pub db: &'a dyn HirDatabase,
35 fmt: &'a mut dyn fmt::Write,
38 pub(crate) max_size: Option<usize>,
39 omit_verbose_types: bool,
40 display_target: DisplayTarget,
43 pub trait HirDisplay {
44 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError>;
46 /// Returns a `Display`able type that is human-readable.
47 fn into_displayable<'a>(
49 db: &'a dyn HirDatabase,
50 max_size: Option<usize>,
51 omit_verbose_types: bool,
52 display_target: DisplayTarget,
53 ) -> HirDisplayWrapper<'a, Self>
58 !matches!(display_target, DisplayTarget::SourceCode { .. }),
59 "HirDisplayWrapper cannot fail with DisplaySourceCodeError, use HirDisplay::hir_fmt directly instead"
61 HirDisplayWrapper { db, t: self, max_size, omit_verbose_types, display_target }
64 /// Returns a `Display`able type that is human-readable.
65 /// Use this for showing types to the user (e.g. diagnostics)
66 fn display<'a>(&'a self, db: &'a dyn HirDatabase) -> HirDisplayWrapper<'a, Self>
74 omit_verbose_types: false,
75 display_target: DisplayTarget::Diagnostics,
79 /// Returns a `Display`able type that is human-readable and tries to be succinct.
80 /// Use this for showing types to the user where space is constrained (e.g. doc popups)
81 fn display_truncated<'a>(
83 db: &'a dyn HirDatabase,
84 max_size: Option<usize>,
85 ) -> HirDisplayWrapper<'a, Self>
93 omit_verbose_types: true,
94 display_target: DisplayTarget::Diagnostics,
98 /// Returns a String representation of `self` that can be inserted into the given module.
99 /// Use this when generating code (e.g. assists)
100 fn display_source_code<'a>(
102 db: &'a dyn HirDatabase,
104 ) -> Result<String, DisplaySourceCodeError> {
105 let mut result = String::new();
106 match self.hir_fmt(&mut HirFormatter {
109 buf: String::with_capacity(20),
112 omit_verbose_types: false,
113 display_target: DisplayTarget::SourceCode { module_id },
116 Err(HirDisplayError::FmtError) => panic!("Writing to String can't fail!"),
117 Err(HirDisplayError::DisplaySourceCodeError(e)) => return Err(e),
122 /// Returns a String representation of `self` for test purposes
123 fn display_test<'a>(&'a self, db: &'a dyn HirDatabase) -> HirDisplayWrapper<'a, Self>
131 omit_verbose_types: false,
132 display_target: DisplayTarget::Test,
137 impl<'a> HirFormatter<'a> {
138 pub fn write_joined<T: HirDisplay>(
140 iter: impl IntoIterator<Item = T>,
142 ) -> Result<(), HirDisplayError> {
143 let mut first = true;
146 write!(self, "{}", sep)?;
154 /// This allows using the `write!` macro directly with a `HirFormatter`.
155 pub fn write_fmt(&mut self, args: fmt::Arguments) -> Result<(), HirDisplayError> {
156 // We write to a buffer first to track output size
158 fmt::write(&mut self.buf, args)?;
159 self.curr_size += self.buf.len();
161 // Then we write to the internal formatter from the buffer
162 self.fmt.write_str(&self.buf).map_err(HirDisplayError::from)
165 pub fn should_truncate(&self) -> bool {
166 if let Some(max_size) = self.max_size {
167 self.curr_size >= max_size
173 pub fn omit_verbose_types(&self) -> bool {
174 self.omit_verbose_types
178 #[derive(Clone, Copy)]
179 pub enum DisplayTarget {
180 /// Display types for inlays, doc popups, autocompletion, etc...
181 /// Showing `{unknown}` or not qualifying paths is fine here.
182 /// There's no reason for this to fail.
184 /// Display types for inserting them in source files.
185 /// The generated code should compile, so paths need to be qualified.
186 SourceCode { module_id: ModuleId },
187 /// Only for test purpose to keep real types
192 fn is_source_code(&self) -> bool {
193 matches!(self, Self::SourceCode { .. })
195 fn is_test(&self) -> bool {
196 matches!(self, Self::Test)
201 pub enum DisplaySourceCodeError {
207 pub enum HirDisplayError {
208 /// Errors that can occur when generating source code
209 DisplaySourceCodeError(DisplaySourceCodeError),
210 /// `FmtError` is required to be compatible with std::fmt::Display
213 impl From<fmt::Error> for HirDisplayError {
214 fn from(_: fmt::Error) -> Self {
219 pub struct HirDisplayWrapper<'a, T> {
220 db: &'a dyn HirDatabase,
222 max_size: Option<usize>,
223 omit_verbose_types: bool,
224 display_target: DisplayTarget,
227 impl<'a, T> fmt::Display for HirDisplayWrapper<'a, T>
231 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
232 match self.t.hir_fmt(&mut HirFormatter {
235 buf: String::with_capacity(20),
237 max_size: self.max_size,
238 omit_verbose_types: self.omit_verbose_types,
239 display_target: self.display_target,
242 Err(HirDisplayError::FmtError) => Err(fmt::Error),
243 Err(HirDisplayError::DisplaySourceCodeError(_)) => {
244 // This should never happen
245 panic!("HirDisplay::hir_fmt failed with DisplaySourceCodeError when calling Display::fmt!")
251 const TYPE_HINT_TRUNCATION: &str = "…";
253 impl<T: HirDisplay> HirDisplay for &'_ T {
254 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
255 HirDisplay::hir_fmt(*self, f)
259 impl HirDisplay for ProjectionTy {
260 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
261 if f.should_truncate() {
262 return write!(f, "{}", TYPE_HINT_TRUNCATION);
265 let trait_ = f.db.trait_data(self.trait_(f.db));
267 self.self_type_parameter(&Interner).hir_fmt(f)?;
268 write!(f, " as {}", trait_.name)?;
269 if self.substitution.len(&Interner) > 1 {
271 f.write_joined(&self.substitution.as_slice(&Interner)[1..], ", ")?;
274 write!(f, ">::{}", f.db.type_alias_data(from_assoc_type_id(self.associated_ty_id)).name)?;
279 impl HirDisplay for OpaqueTy {
280 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
281 if f.should_truncate() {
282 return write!(f, "{}", TYPE_HINT_TRUNCATION);
285 self.substitution.at(&Interner, 0).hir_fmt(f)
289 impl HirDisplay for GenericArg {
290 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
291 match self.interned() {
292 crate::GenericArgData::Ty(ty) => ty.hir_fmt(f),
293 crate::GenericArgData::Lifetime(lt) => lt.hir_fmt(f),
294 crate::GenericArgData::Const(c) => c.hir_fmt(f),
299 impl HirDisplay for Const {
300 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
301 let data = self.interned();
303 ConstValue::BoundVar(idx) => idx.hir_fmt(f),
304 ConstValue::InferenceVar(..) => write!(f, "_"),
305 ConstValue::Placeholder(idx) => {
306 let id = const_from_placeholder_idx(f.db, idx);
307 let generics = generics(f.db.upcast(), id.parent);
308 let param_data = &generics.params.consts[id.local_id];
309 write!(f, "{}", param_data.name)
311 ConstValue::Concrete(_) => write!(f, "_"),
316 impl HirDisplay for BoundVar {
317 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
318 write!(f, "?{}.{}", self.debruijn.depth(), self.index)
322 impl HirDisplay for Ty {
323 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
324 if f.should_truncate() {
325 return write!(f, "{}", TYPE_HINT_TRUNCATION);
328 match self.kind(&Interner) {
329 TyKind::Never => write!(f, "!")?,
330 TyKind::Str => write!(f, "str")?,
331 TyKind::Scalar(Scalar::Bool) => write!(f, "bool")?,
332 TyKind::Scalar(Scalar::Char) => write!(f, "char")?,
333 &TyKind::Scalar(Scalar::Float(t)) => write!(f, "{}", primitive::float_ty_to_string(t))?,
334 &TyKind::Scalar(Scalar::Int(t)) => write!(f, "{}", primitive::int_ty_to_string(t))?,
335 &TyKind::Scalar(Scalar::Uint(t)) => write!(f, "{}", primitive::uint_ty_to_string(t))?,
336 TyKind::Slice(t) => {
341 TyKind::Array(t, c) => {
348 TyKind::Raw(m, t) | TyKind::Ref(m, _, t) => {
349 if matches!(self.kind(&Interner), TyKind::Raw(..)) {
354 Mutability::Not => "const ",
355 Mutability::Mut => "mut ",
363 Mutability::Not => "",
364 Mutability::Mut => "mut ",
369 // FIXME: all this just to decide whether to use parentheses...
371 let predicates: Vec<_> = match t.kind(&Interner) {
372 TyKind::Dyn(dyn_ty) if dyn_ty.bounds.skip_binders().interned().len() > 1 => {
373 dyn_ty.bounds.skip_binders().interned().iter().cloned().collect()
375 &TyKind::Alias(AliasTy::Opaque(OpaqueTy {
377 substitution: ref parameters,
379 let impl_trait_id = f.db.lookup_intern_impl_trait_id(opaque_ty_id.into());
380 if let ImplTraitId::ReturnTypeImplTrait(func, idx) = impl_trait_id {
382 f.db.return_type_impl_traits(func)
383 .expect("impl trait id without data");
386 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
387 let bounds = data.substitute(&Interner, parameters);
388 bounds.into_value_and_skipped_binders().0
396 if let Some(WhereClause::Implemented(trait_ref)) =
397 predicates.get(0).map(|b| b.skip_binders())
399 let trait_ = trait_ref.hir_trait_id();
400 if fn_traits(f.db.upcast(), trait_).any(|it| it == trait_)
401 && predicates.len() <= 2
407 if predicates.len() > 1 {
415 TyKind::Tuple(_, substs) => {
416 if substs.len(&Interner) == 1 {
418 substs.at(&Interner, 0).hir_fmt(f)?;
422 f.write_joined(&*substs.as_slice(&Interner), ", ")?;
426 TyKind::Function(fn_ptr) => {
427 let sig = CallableSig::from_fn_ptr(fn_ptr);
430 TyKind::FnDef(def, parameters) => {
431 let def = from_chalk(f.db, *def);
432 let sig = f.db.callable_item_signature(def).substitute(&Interner, parameters);
434 CallableDefId::FunctionId(ff) => {
435 write!(f, "fn {}", f.db.function_data(ff).name)?
437 CallableDefId::StructId(s) => write!(f, "{}", f.db.struct_data(s).name)?,
438 CallableDefId::EnumVariantId(e) => {
439 write!(f, "{}", f.db.enum_data(e.parent).variants[e.local_id].name)?
442 if parameters.len(&Interner) > 0 {
443 let generics = generics(f.db.upcast(), def.into());
444 let (parent_params, self_param, type_params, _impl_trait_params) =
445 generics.provenance_split();
446 let total_len = parent_params + self_param + type_params;
447 // We print all params except implicit impl Trait params. Still a bit weird; should we leave out parent and self?
450 f.write_joined(¶meters.as_slice(&Interner)[..total_len], ", ")?;
455 f.write_joined(sig.params(), ", ")?;
463 TyKind::Adt(AdtId(def_id), parameters) => {
464 match f.display_target {
465 DisplayTarget::Diagnostics | DisplayTarget::Test => {
466 let name = match *def_id {
467 hir_def::AdtId::StructId(it) => f.db.struct_data(it).name.clone(),
468 hir_def::AdtId::UnionId(it) => f.db.union_data(it).name.clone(),
469 hir_def::AdtId::EnumId(it) => f.db.enum_data(it).name.clone(),
471 write!(f, "{}", name)?;
473 DisplayTarget::SourceCode { module_id } => {
474 if let Some(path) = find_path::find_path(
476 ItemInNs::Types((*def_id).into()),
479 write!(f, "{}", path)?;
481 return Err(HirDisplayError::DisplaySourceCodeError(
482 DisplaySourceCodeError::PathNotFound,
488 if parameters.len(&Interner) > 0 {
489 let parameters_to_write = if f.display_target.is_source_code()
490 || f.omit_verbose_types()
493 .as_generic_def(f.db)
494 .map(|generic_def_id| f.db.generic_defaults(generic_def_id))
495 .filter(|defaults| !defaults.is_empty())
497 None => parameters.as_slice(&Interner),
498 Some(default_parameters) => {
499 let mut default_from = 0;
500 for (i, parameter) in parameters.iter(&Interner).enumerate() {
502 parameter.assert_ty_ref(&Interner).kind(&Interner),
503 default_parameters.get(i),
505 (&TyKind::Error, _) | (_, None) => {
506 default_from = i + 1;
508 (_, Some(default_parameter)) => {
510 default_parameter.clone().substitute(
512 &subst_prefix(parameters, i),
514 if parameter.assert_ty_ref(&Interner) != &actual_default
516 default_from = i + 1;
521 ¶meters.as_slice(&Interner)[0..default_from]
525 parameters.as_slice(&Interner)
527 if !parameters_to_write.is_empty() {
529 f.write_joined(parameters_to_write, ", ")?;
534 TyKind::AssociatedType(assoc_type_id, parameters) => {
535 let type_alias = from_assoc_type_id(*assoc_type_id);
536 let trait_ = match type_alias.lookup(f.db.upcast()).container {
537 AssocContainerId::TraitId(it) => it,
538 _ => panic!("not an associated type"),
540 let trait_ = f.db.trait_data(trait_);
541 let type_alias_data = f.db.type_alias_data(type_alias);
543 // Use placeholder associated types when the target is test (https://rust-lang.github.io/chalk/book/clauses/type_equality.html#placeholder-associated-types)
544 if f.display_target.is_test() {
545 write!(f, "{}::{}", trait_.name, type_alias_data.name)?;
546 if parameters.len(&Interner) > 0 {
548 f.write_joined(&*parameters.as_slice(&Interner), ", ")?;
552 let projection_ty = ProjectionTy {
553 associated_ty_id: to_assoc_type_id(type_alias),
554 substitution: parameters.clone(),
557 projection_ty.hir_fmt(f)?;
560 TyKind::Foreign(type_alias) => {
561 let type_alias = f.db.type_alias_data(from_foreign_def_id(*type_alias));
562 write!(f, "{}", type_alias.name)?;
564 TyKind::OpaqueType(opaque_ty_id, parameters) => {
565 let impl_trait_id = f.db.lookup_intern_impl_trait_id((*opaque_ty_id).into());
566 match impl_trait_id {
567 ImplTraitId::ReturnTypeImplTrait(func, idx) => {
569 f.db.return_type_impl_traits(func).expect("impl trait id without data");
572 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
573 let bounds = data.substitute(&Interner, ¶meters);
574 write_bounds_like_dyn_trait_with_prefix("impl", bounds.skip_binders(), f)?;
575 // FIXME: it would maybe be good to distinguish this from the alias type (when debug printing), and to show the substitution
577 ImplTraitId::AsyncBlockTypeImplTrait(..) => {
578 write!(f, "impl Future<Output = ")?;
579 parameters.at(&Interner, 0).hir_fmt(f)?;
584 TyKind::Closure(.., substs) => {
585 if f.display_target.is_source_code() {
586 return Err(HirDisplayError::DisplaySourceCodeError(
587 DisplaySourceCodeError::Closure,
590 let sig = substs.at(&Interner, 0).assert_ty_ref(&Interner).callable_sig(f.db);
591 if let Some(sig) = sig {
592 if sig.params().is_empty() {
594 } else if f.omit_verbose_types() {
595 write!(f, "|{}|", TYPE_HINT_TRUNCATION)?;
598 f.write_joined(sig.params(), ", ")?;
603 sig.ret().hir_fmt(f)?;
605 write!(f, "{{closure}}")?;
608 TyKind::Placeholder(idx) => {
609 let id = from_placeholder_idx(f.db, *idx);
610 let generics = generics(f.db.upcast(), id.parent);
611 let param_data = &generics.params.types[id.local_id];
612 match param_data.provenance {
613 TypeParamProvenance::TypeParamList | TypeParamProvenance::TraitSelf => {
614 write!(f, "{}", param_data.name.clone().unwrap_or_else(Name::missing))?
616 TypeParamProvenance::ArgumentImplTrait => {
617 let substs = generics.type_params_subst(f.db);
619 f.db.generic_predicates(id.parent)
621 .map(|pred| pred.clone().substitute(&Interner, &substs))
622 .filter(|wc| match &wc.skip_binders() {
623 WhereClause::Implemented(tr) => {
624 &tr.self_type_parameter(&Interner) == self
626 WhereClause::AliasEq(AliasEq {
627 alias: AliasTy::Projection(proj),
629 }) => &proj.self_type_parameter(&Interner) == self,
632 .collect::<Vec<_>>();
633 write_bounds_like_dyn_trait_with_prefix("impl", &bounds, f)?;
637 TyKind::BoundVar(idx) => idx.hir_fmt(f)?,
638 TyKind::Dyn(dyn_ty) => {
639 write_bounds_like_dyn_trait_with_prefix(
641 dyn_ty.bounds.skip_binders().interned(),
645 TyKind::Alias(AliasTy::Projection(p_ty)) => p_ty.hir_fmt(f)?,
646 TyKind::Alias(AliasTy::Opaque(opaque_ty)) => {
647 let impl_trait_id = f.db.lookup_intern_impl_trait_id(opaque_ty.opaque_ty_id.into());
648 match impl_trait_id {
649 ImplTraitId::ReturnTypeImplTrait(func, idx) => {
651 f.db.return_type_impl_traits(func).expect("impl trait id without data");
654 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
655 let bounds = data.substitute(&Interner, &opaque_ty.substitution);
656 write_bounds_like_dyn_trait_with_prefix("impl", bounds.skip_binders(), f)?;
658 ImplTraitId::AsyncBlockTypeImplTrait(..) => {
659 write!(f, "{{async block}}")?;
664 if f.display_target.is_source_code() {
665 return Err(HirDisplayError::DisplaySourceCodeError(
666 DisplaySourceCodeError::UnknownType,
669 write!(f, "{{unknown}}")?;
671 TyKind::InferenceVar(..) => write!(f, "_")?,
672 TyKind::Generator(..) => write!(f, "{{generator}}")?,
673 TyKind::GeneratorWitness(..) => write!(f, "{{generator witness}}")?,
679 impl HirDisplay for CallableSig {
680 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
682 f.write_joined(self.params(), ", ")?;
684 if self.params().is_empty() {
691 let ret = self.ret();
700 fn fn_traits(db: &dyn DefDatabase, trait_: TraitId) -> impl Iterator<Item = TraitId> {
701 let krate = trait_.lookup(db).container.krate();
703 db.lang_item(krate, "fn".into()),
704 db.lang_item(krate, "fn_mut".into()),
705 db.lang_item(krate, "fn_once".into()),
707 array::IntoIter::new(fn_traits).into_iter().flatten().flat_map(|it| it.as_trait())
710 pub fn write_bounds_like_dyn_trait_with_prefix(
712 predicates: &[QuantifiedWhereClause],
713 f: &mut HirFormatter,
714 ) -> Result<(), HirDisplayError> {
715 write!(f, "{}", prefix)?;
716 if !predicates.is_empty() {
718 write_bounds_like_dyn_trait(predicates, f)
724 fn write_bounds_like_dyn_trait(
725 predicates: &[QuantifiedWhereClause],
726 f: &mut HirFormatter,
727 ) -> Result<(), HirDisplayError> {
728 // Note: This code is written to produce nice results (i.e.
729 // corresponding to surface Rust) for types that can occur in
730 // actual Rust. It will have weird results if the predicates
731 // aren't as expected (i.e. self types = $0, projection
732 // predicates for a certain trait come after the Implemented
733 // predicate for that trait).
734 let mut first = true;
735 let mut angle_open = false;
736 let mut is_fn_trait = false;
737 for p in predicates.iter() {
738 match p.skip_binders() {
739 WhereClause::Implemented(trait_ref) => {
740 let trait_ = trait_ref.hir_trait_id();
742 is_fn_trait = fn_traits(f.db.upcast(), trait_).any(|it| it == trait_);
744 if !is_fn_trait && angle_open {
751 // We assume that the self type is ^0.0 (i.e. the
752 // existential) here, which is the only thing that's
753 // possible in actual Rust, and hence don't print it
754 write!(f, "{}", f.db.trait_data(trait_).name)?;
755 if let [_, params @ ..] = &*trait_ref.substitution.as_slice(&Interner) {
758 params.first().and_then(|it| it.assert_ty_ref(&Interner).as_tuple())
761 f.write_joined(args.as_slice(&Interner), ", ")?;
764 } else if !params.is_empty() {
766 f.write_joined(params, ", ")?;
767 // there might be assoc type bindings, so we leave the angle brackets open
772 WhereClause::AliasEq(alias_eq) if is_fn_trait => {
775 alias_eq.ty.hir_fmt(f)?;
777 WhereClause::AliasEq(AliasEq { ty, alias }) => {
778 // in types in actual Rust, these will always come
779 // after the corresponding Implemented predicate
786 if let AliasTy::Projection(proj) = alias {
788 f.db.type_alias_data(from_assoc_type_id(proj.associated_ty_id));
789 write!(f, "{} = ", type_alias.name)?;
794 // FIXME implement these
795 WhereClause::LifetimeOutlives(_) => {}
796 WhereClause::TypeOutlives(_) => {}
806 fn fmt_trait_ref(tr: &TraitRef, f: &mut HirFormatter, use_as: bool) -> Result<(), HirDisplayError> {
807 if f.should_truncate() {
808 return write!(f, "{}", TYPE_HINT_TRUNCATION);
811 tr.self_type_parameter(&Interner).hir_fmt(f)?;
817 write!(f, "{}", f.db.trait_data(tr.hir_trait_id()).name)?;
818 if tr.substitution.len(&Interner) > 1 {
820 f.write_joined(&tr.substitution.as_slice(&Interner)[1..], ", ")?;
826 impl HirDisplay for TraitRef {
827 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
828 fmt_trait_ref(self, f, false)
832 impl HirDisplay for WhereClause {
833 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
834 if f.should_truncate() {
835 return write!(f, "{}", TYPE_HINT_TRUNCATION);
839 WhereClause::Implemented(trait_ref) => trait_ref.hir_fmt(f)?,
840 WhereClause::AliasEq(AliasEq { alias: AliasTy::Projection(projection_ty), ty }) => {
842 fmt_trait_ref(&projection_ty.trait_ref(f.db), f, true)?;
846 f.db.type_alias_data(from_assoc_type_id(projection_ty.associated_ty_id)).name,
850 WhereClause::AliasEq(_) => write!(f, "{{error}}")?,
852 // FIXME implement these
853 WhereClause::TypeOutlives(..) => {}
854 WhereClause::LifetimeOutlives(..) => {}
860 impl HirDisplay for LifetimeOutlives {
861 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
868 impl HirDisplay for Lifetime {
869 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
870 self.interned().hir_fmt(f)
874 impl HirDisplay for LifetimeData {
875 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
877 LifetimeData::BoundVar(idx) => idx.hir_fmt(f),
878 LifetimeData::InferenceVar(_) => write!(f, "_"),
879 LifetimeData::Placeholder(idx) => {
880 let id = lt_from_placeholder_idx(f.db, *idx);
881 let generics = generics(f.db.upcast(), id.parent);
882 let param_data = &generics.params.lifetimes[id.local_id];
883 write!(f, "{}", param_data.name)
885 LifetimeData::Static => write!(f, "'static"),
886 LifetimeData::Empty(_) => Ok(()),
887 LifetimeData::Erased => Ok(()),
888 LifetimeData::Phantom(_, _) => Ok(()),
893 impl HirDisplay for DomainGoal {
894 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
896 DomainGoal::Holds(wc) => {
897 write!(f, "Holds(")?;
901 _ => write!(f, "?")?,
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::Macro(macro_call) => {
1002 let macro_call = macro_call.to_node(f.db.upcast());
1003 let ctx = body::LowerCtx::with_hygiene(f.db.upcast(), &Hygiene::new_unhygienic());
1004 match macro_call.path() {
1005 Some(path) => match Path::from_src(path, &ctx) {
1006 Some(path) => path.hir_fmt(f)?,
1007 None => write!(f, "{{macro}}")?,
1009 None => write!(f, "{{macro}}")?,
1011 write!(f, "!(..)")?;
1013 TypeRef::Error => write!(f, "{{error}}")?,
1019 impl HirDisplay for TypeBound {
1020 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1022 TypeBound::Path(path) => path.hir_fmt(f),
1023 TypeBound::Lifetime(lifetime) => write!(f, "{}", lifetime.name),
1024 TypeBound::Error => write!(f, "{{error}}"),
1029 impl HirDisplay for Path {
1030 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1031 match (self.type_anchor(), self.kind()) {
1032 (Some(anchor), _) => {
1037 (_, PathKind::Plain) => {}
1038 (_, PathKind::Abs) => write!(f, "::")?,
1039 (_, PathKind::Crate) => write!(f, "crate")?,
1040 (_, PathKind::Super(0)) => write!(f, "self")?,
1041 (_, PathKind::Super(n)) => {
1042 write!(f, "super")?;
1044 write!(f, "::super")?;
1047 (_, PathKind::DollarCrate(_)) => write!(f, "{{extern_crate}}")?,
1050 for (seg_idx, segment) in self.segments().iter().enumerate() {
1054 write!(f, "{}", segment.name)?;
1055 if let Some(generic_args) = segment.args_and_bindings {
1056 // We should be in type context, so format as `Foo<Bar>` instead of `Foo::<Bar>`.
1057 // Do we actually format expressions?
1059 let mut first = true;
1060 for arg in &generic_args.args {
1063 if generic_args.has_self_type {
1064 // FIXME: Convert to `<Ty as Trait>` form.
1065 write!(f, "Self = ")?;
1072 for binding in &generic_args.bindings {
1078 write!(f, "{}", binding.name)?;
1079 match &binding.type_ref {
1086 f.write_joined(&binding.bounds, " + ")?;
1097 impl HirDisplay for hir_def::path::GenericArg {
1098 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1100 hir_def::path::GenericArg::Type(ty) => ty.hir_fmt(f),
1101 hir_def::path::GenericArg::Lifetime(lifetime) => write!(f, "{}", lifetime.name),