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;
14 generics::TypeParamProvenance,
16 path::{Path, PathKind},
17 type_ref::{TypeBound, TypeRef},
18 visibility::Visibility,
19 AssocContainerId, Lookup, ModuleId, TraitId,
21 use hir_expand::name::Name;
24 const_from_placeholder_idx, db::HirDatabase, from_assoc_type_id, from_foreign_def_id,
25 from_placeholder_idx, lt_from_placeholder_idx, mapping::from_chalk, primitive, subst_prefix,
26 to_assoc_type_id, utils::generics, AdtId, AliasEq, AliasTy, CallableDefId, CallableSig, Const,
27 ConstValue, DomainGoal, GenericArg, ImplTraitId, Interner, Lifetime, LifetimeData,
28 LifetimeOutlives, Mutability, OpaqueTy, ProjectionTy, ProjectionTyExt, QuantifiedWhereClause,
29 Scalar, TraitRef, TraitRefExt, Ty, TyExt, TyKind, WhereClause,
32 pub struct HirFormatter<'a> {
33 pub db: &'a dyn HirDatabase,
34 fmt: &'a mut dyn fmt::Write,
37 pub(crate) max_size: Option<usize>,
38 omit_verbose_types: bool,
39 display_target: DisplayTarget,
42 pub trait HirDisplay {
43 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError>;
45 /// Returns a `Display`able type that is human-readable.
46 fn into_displayable<'a>(
48 db: &'a dyn HirDatabase,
49 max_size: Option<usize>,
50 omit_verbose_types: bool,
51 display_target: DisplayTarget,
52 ) -> HirDisplayWrapper<'a, Self>
57 !matches!(display_target, DisplayTarget::SourceCode { .. }),
58 "HirDisplayWrapper cannot fail with DisplaySourceCodeError, use HirDisplay::hir_fmt directly instead"
60 HirDisplayWrapper { db, t: self, max_size, omit_verbose_types, display_target }
63 /// Returns a `Display`able type that is human-readable.
64 /// Use this for showing types to the user (e.g. diagnostics)
65 fn display<'a>(&'a self, db: &'a dyn HirDatabase) -> HirDisplayWrapper<'a, Self>
73 omit_verbose_types: false,
74 display_target: DisplayTarget::Diagnostics,
78 /// Returns a `Display`able type that is human-readable and tries to be succinct.
79 /// Use this for showing types to the user where space is constrained (e.g. doc popups)
80 fn display_truncated<'a>(
82 db: &'a dyn HirDatabase,
83 max_size: Option<usize>,
84 ) -> HirDisplayWrapper<'a, Self>
92 omit_verbose_types: true,
93 display_target: DisplayTarget::Diagnostics,
97 /// Returns a String representation of `self` that can be inserted into the given module.
98 /// Use this when generating code (e.g. assists)
99 fn display_source_code<'a>(
101 db: &'a dyn HirDatabase,
103 ) -> Result<String, DisplaySourceCodeError> {
104 let mut result = String::new();
105 match self.hir_fmt(&mut HirFormatter {
108 buf: String::with_capacity(20),
111 omit_verbose_types: false,
112 display_target: DisplayTarget::SourceCode { module_id },
115 Err(HirDisplayError::FmtError) => panic!("Writing to String can't fail!"),
116 Err(HirDisplayError::DisplaySourceCodeError(e)) => return Err(e),
121 /// Returns a String representation of `self` for test purposes
122 fn display_test<'a>(&'a self, db: &'a dyn HirDatabase) -> HirDisplayWrapper<'a, Self>
130 omit_verbose_types: false,
131 display_target: DisplayTarget::Test,
136 impl<'a> HirFormatter<'a> {
137 pub fn write_joined<T: HirDisplay>(
139 iter: impl IntoIterator<Item = T>,
141 ) -> Result<(), HirDisplayError> {
142 let mut first = true;
145 write!(self, "{}", sep)?;
153 /// This allows using the `write!` macro directly with a `HirFormatter`.
154 pub fn write_fmt(&mut self, args: fmt::Arguments) -> Result<(), HirDisplayError> {
155 // We write to a buffer first to track output size
157 fmt::write(&mut self.buf, args)?;
158 self.curr_size += self.buf.len();
160 // Then we write to the internal formatter from the buffer
161 self.fmt.write_str(&self.buf).map_err(HirDisplayError::from)
164 pub fn should_truncate(&self) -> bool {
165 if let Some(max_size) = self.max_size {
166 self.curr_size >= max_size
172 pub fn omit_verbose_types(&self) -> bool {
173 self.omit_verbose_types
177 #[derive(Clone, Copy)]
178 pub enum DisplayTarget {
179 /// Display types for inlays, doc popups, autocompletion, etc...
180 /// Showing `{unknown}` or not qualifying paths is fine here.
181 /// There's no reason for this to fail.
183 /// Display types for inserting them in source files.
184 /// The generated code should compile, so paths need to be qualified.
185 SourceCode { module_id: ModuleId },
186 /// Only for test purpose to keep real types
191 fn is_source_code(&self) -> bool {
192 matches!(self, Self::SourceCode { .. })
194 fn is_test(&self) -> bool {
195 matches!(self, Self::Test)
200 pub enum DisplaySourceCodeError {
206 pub enum HirDisplayError {
207 /// Errors that can occur when generating source code
208 DisplaySourceCodeError(DisplaySourceCodeError),
209 /// `FmtError` is required to be compatible with std::fmt::Display
212 impl From<fmt::Error> for HirDisplayError {
213 fn from(_: fmt::Error) -> Self {
218 pub struct HirDisplayWrapper<'a, T> {
219 db: &'a dyn HirDatabase,
221 max_size: Option<usize>,
222 omit_verbose_types: bool,
223 display_target: DisplayTarget,
226 impl<'a, T> fmt::Display for HirDisplayWrapper<'a, T>
230 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
231 match self.t.hir_fmt(&mut HirFormatter {
234 buf: String::with_capacity(20),
236 max_size: self.max_size,
237 omit_verbose_types: self.omit_verbose_types,
238 display_target: self.display_target,
241 Err(HirDisplayError::FmtError) => Err(fmt::Error),
242 Err(HirDisplayError::DisplaySourceCodeError(_)) => {
243 // This should never happen
244 panic!("HirDisplay::hir_fmt failed with DisplaySourceCodeError when calling Display::fmt!")
250 const TYPE_HINT_TRUNCATION: &str = "…";
252 impl<T: HirDisplay> HirDisplay for &'_ T {
253 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
254 HirDisplay::hir_fmt(*self, f)
258 impl HirDisplay for ProjectionTy {
259 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
260 if f.should_truncate() {
261 return write!(f, "{}", TYPE_HINT_TRUNCATION);
264 let trait_ = f.db.trait_data(self.trait_(f.db));
266 self.self_type_parameter(&Interner).hir_fmt(f)?;
267 write!(f, " as {}", trait_.name)?;
268 if self.substitution.len(&Interner) > 1 {
270 f.write_joined(&self.substitution.as_slice(&Interner)[1..], ", ")?;
273 write!(f, ">::{}", f.db.type_alias_data(from_assoc_type_id(self.associated_ty_id)).name)?;
278 impl HirDisplay for OpaqueTy {
279 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
280 if f.should_truncate() {
281 return write!(f, "{}", TYPE_HINT_TRUNCATION);
284 self.substitution.at(&Interner, 0).hir_fmt(f)
288 impl HirDisplay for GenericArg {
289 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
290 match self.interned() {
291 crate::GenericArgData::Ty(ty) => ty.hir_fmt(f),
292 crate::GenericArgData::Lifetime(lt) => lt.hir_fmt(f),
293 crate::GenericArgData::Const(c) => c.hir_fmt(f),
298 impl HirDisplay for Const {
299 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
300 let data = self.interned();
302 ConstValue::BoundVar(idx) => idx.hir_fmt(f),
303 ConstValue::InferenceVar(..) => write!(f, "_"),
304 ConstValue::Placeholder(idx) => {
305 let id = const_from_placeholder_idx(f.db, idx);
306 let generics = generics(f.db.upcast(), id.parent);
307 let param_data = &generics.params.consts[id.local_id];
308 write!(f, "{}", param_data.name)
310 ConstValue::Concrete(_) => write!(f, "_"),
315 impl HirDisplay for BoundVar {
316 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
317 write!(f, "?{}.{}", self.debruijn.depth(), self.index)
321 impl HirDisplay for Ty {
322 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
323 if f.should_truncate() {
324 return write!(f, "{}", TYPE_HINT_TRUNCATION);
327 match self.kind(&Interner) {
328 TyKind::Never => write!(f, "!")?,
329 TyKind::Str => write!(f, "str")?,
330 TyKind::Scalar(Scalar::Bool) => write!(f, "bool")?,
331 TyKind::Scalar(Scalar::Char) => write!(f, "char")?,
332 &TyKind::Scalar(Scalar::Float(t)) => write!(f, "{}", primitive::float_ty_to_string(t))?,
333 &TyKind::Scalar(Scalar::Int(t)) => write!(f, "{}", primitive::int_ty_to_string(t))?,
334 &TyKind::Scalar(Scalar::Uint(t)) => write!(f, "{}", primitive::uint_ty_to_string(t))?,
335 TyKind::Slice(t) => {
340 TyKind::Array(t, c) => {
347 TyKind::Raw(m, t) | TyKind::Ref(m, _, t) => {
348 if matches!(self.kind(&Interner), TyKind::Raw(..)) {
353 Mutability::Not => "const ",
354 Mutability::Mut => "mut ",
362 Mutability::Not => "",
363 Mutability::Mut => "mut ",
368 // FIXME: all this just to decide whether to use parentheses...
370 let predicates: Vec<_> = match t.kind(&Interner) {
371 TyKind::Dyn(dyn_ty) if dyn_ty.bounds.skip_binders().interned().len() > 1 => {
372 dyn_ty.bounds.skip_binders().interned().iter().cloned().collect()
374 &TyKind::Alias(AliasTy::Opaque(OpaqueTy {
376 substitution: ref parameters,
378 let impl_trait_id = f.db.lookup_intern_impl_trait_id(opaque_ty_id.into());
379 if let ImplTraitId::ReturnTypeImplTrait(func, idx) = impl_trait_id {
381 f.db.return_type_impl_traits(func)
382 .expect("impl trait id without data");
385 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
386 let bounds = data.substitute(&Interner, parameters);
387 bounds.into_value_and_skipped_binders().0
395 if let Some(WhereClause::Implemented(trait_ref)) =
396 predicates.get(0).map(|b| b.skip_binders())
398 let trait_ = trait_ref.hir_trait_id();
399 if fn_traits(f.db.upcast(), trait_).any(|it| it == trait_)
400 && predicates.len() <= 2
406 if predicates.len() > 1 {
414 TyKind::Tuple(_, substs) => {
415 if substs.len(&Interner) == 1 {
417 substs.at(&Interner, 0).hir_fmt(f)?;
421 f.write_joined(&*substs.as_slice(&Interner), ", ")?;
425 TyKind::Function(fn_ptr) => {
426 let sig = CallableSig::from_fn_ptr(fn_ptr);
429 TyKind::FnDef(def, parameters) => {
430 let def = from_chalk(f.db, *def);
431 let sig = f.db.callable_item_signature(def).substitute(&Interner, parameters);
433 CallableDefId::FunctionId(ff) => {
434 write!(f, "fn {}", f.db.function_data(ff).name)?
436 CallableDefId::StructId(s) => write!(f, "{}", f.db.struct_data(s).name)?,
437 CallableDefId::EnumVariantId(e) => {
438 write!(f, "{}", f.db.enum_data(e.parent).variants[e.local_id].name)?
441 if parameters.len(&Interner) > 0 {
442 let generics = generics(f.db.upcast(), def.into());
443 let (parent_params, self_param, type_params, _impl_trait_params) =
444 generics.provenance_split();
445 let total_len = parent_params + self_param + type_params;
446 // We print all params except implicit impl Trait params. Still a bit weird; should we leave out parent and self?
449 f.write_joined(¶meters.as_slice(&Interner)[..total_len], ", ")?;
454 f.write_joined(sig.params(), ", ")?;
462 TyKind::Adt(AdtId(def_id), parameters) => {
463 match f.display_target {
464 DisplayTarget::Diagnostics | DisplayTarget::Test => {
465 let name = match *def_id {
466 hir_def::AdtId::StructId(it) => f.db.struct_data(it).name.clone(),
467 hir_def::AdtId::UnionId(it) => f.db.union_data(it).name.clone(),
468 hir_def::AdtId::EnumId(it) => f.db.enum_data(it).name.clone(),
470 write!(f, "{}", name)?;
472 DisplayTarget::SourceCode { module_id } => {
473 if let Some(path) = find_path::find_path(
475 ItemInNs::Types((*def_id).into()),
478 write!(f, "{}", path)?;
480 return Err(HirDisplayError::DisplaySourceCodeError(
481 DisplaySourceCodeError::PathNotFound,
487 if parameters.len(&Interner) > 0 {
488 let parameters_to_write = if f.display_target.is_source_code()
489 || f.omit_verbose_types()
492 .as_generic_def(f.db)
493 .map(|generic_def_id| f.db.generic_defaults(generic_def_id))
494 .filter(|defaults| !defaults.is_empty())
496 None => parameters.as_slice(&Interner),
497 Some(default_parameters) => {
498 let mut default_from = 0;
499 for (i, parameter) in parameters.iter(&Interner).enumerate() {
501 parameter.assert_ty_ref(&Interner).kind(&Interner),
502 default_parameters.get(i),
504 (&TyKind::Error, _) | (_, None) => {
505 default_from = i + 1;
507 (_, Some(default_parameter)) => {
509 default_parameter.clone().substitute(
511 &subst_prefix(parameters, i),
513 if parameter.assert_ty_ref(&Interner) != &actual_default
515 default_from = i + 1;
520 ¶meters.as_slice(&Interner)[0..default_from]
524 parameters.as_slice(&Interner)
526 if !parameters_to_write.is_empty() {
528 f.write_joined(parameters_to_write, ", ")?;
533 TyKind::AssociatedType(assoc_type_id, parameters) => {
534 let type_alias = from_assoc_type_id(*assoc_type_id);
535 let trait_ = match type_alias.lookup(f.db.upcast()).container {
536 AssocContainerId::TraitId(it) => it,
537 _ => panic!("not an associated type"),
539 let trait_ = f.db.trait_data(trait_);
540 let type_alias_data = f.db.type_alias_data(type_alias);
542 // Use placeholder associated types when the target is test (https://rust-lang.github.io/chalk/book/clauses/type_equality.html#placeholder-associated-types)
543 if f.display_target.is_test() {
544 write!(f, "{}::{}", trait_.name, type_alias_data.name)?;
545 if parameters.len(&Interner) > 0 {
547 f.write_joined(&*parameters.as_slice(&Interner), ", ")?;
551 let projection_ty = ProjectionTy {
552 associated_ty_id: to_assoc_type_id(type_alias),
553 substitution: parameters.clone(),
556 projection_ty.hir_fmt(f)?;
559 TyKind::Foreign(type_alias) => {
560 let type_alias = f.db.type_alias_data(from_foreign_def_id(*type_alias));
561 write!(f, "{}", type_alias.name)?;
563 TyKind::OpaqueType(opaque_ty_id, parameters) => {
564 let impl_trait_id = f.db.lookup_intern_impl_trait_id((*opaque_ty_id).into());
565 match impl_trait_id {
566 ImplTraitId::ReturnTypeImplTrait(func, idx) => {
568 f.db.return_type_impl_traits(func).expect("impl trait id without data");
571 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
572 let bounds = data.substitute(&Interner, ¶meters);
573 write_bounds_like_dyn_trait_with_prefix("impl", bounds.skip_binders(), f)?;
574 // FIXME: it would maybe be good to distinguish this from the alias type (when debug printing), and to show the substitution
576 ImplTraitId::AsyncBlockTypeImplTrait(..) => {
577 write!(f, "impl Future<Output = ")?;
578 parameters.at(&Interner, 0).hir_fmt(f)?;
583 TyKind::Closure(.., substs) => {
584 if f.display_target.is_source_code() {
585 return Err(HirDisplayError::DisplaySourceCodeError(
586 DisplaySourceCodeError::Closure,
589 let sig = substs.at(&Interner, 0).assert_ty_ref(&Interner).callable_sig(f.db);
590 if let Some(sig) = sig {
591 if sig.params().is_empty() {
593 } else if f.omit_verbose_types() {
594 write!(f, "|{}|", TYPE_HINT_TRUNCATION)?;
597 f.write_joined(sig.params(), ", ")?;
602 sig.ret().hir_fmt(f)?;
604 write!(f, "{{closure}}")?;
607 TyKind::Placeholder(idx) => {
608 let id = from_placeholder_idx(f.db, *idx);
609 let generics = generics(f.db.upcast(), id.parent);
610 let param_data = &generics.params.types[id.local_id];
611 match param_data.provenance {
612 TypeParamProvenance::TypeParamList | TypeParamProvenance::TraitSelf => {
613 write!(f, "{}", param_data.name.clone().unwrap_or_else(Name::missing))?
615 TypeParamProvenance::ArgumentImplTrait => {
616 let substs = generics.type_params_subst(f.db);
618 f.db.generic_predicates(id.parent)
620 .map(|pred| pred.clone().substitute(&Interner, &substs))
621 .filter(|wc| match &wc.skip_binders() {
622 WhereClause::Implemented(tr) => {
623 &tr.self_type_parameter(&Interner) == self
625 WhereClause::AliasEq(AliasEq {
626 alias: AliasTy::Projection(proj),
628 }) => &proj.self_type_parameter(&Interner) == self,
631 .collect::<Vec<_>>();
632 write_bounds_like_dyn_trait_with_prefix("impl", &bounds, f)?;
636 TyKind::BoundVar(idx) => idx.hir_fmt(f)?,
637 TyKind::Dyn(dyn_ty) => {
638 write_bounds_like_dyn_trait_with_prefix(
640 dyn_ty.bounds.skip_binders().interned(),
644 TyKind::Alias(AliasTy::Projection(p_ty)) => p_ty.hir_fmt(f)?,
645 TyKind::Alias(AliasTy::Opaque(opaque_ty)) => {
646 let impl_trait_id = f.db.lookup_intern_impl_trait_id(opaque_ty.opaque_ty_id.into());
647 match impl_trait_id {
648 ImplTraitId::ReturnTypeImplTrait(func, idx) => {
650 f.db.return_type_impl_traits(func).expect("impl trait id without data");
653 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
654 let bounds = data.substitute(&Interner, &opaque_ty.substitution);
655 write_bounds_like_dyn_trait_with_prefix("impl", bounds.skip_binders(), f)?;
657 ImplTraitId::AsyncBlockTypeImplTrait(..) => {
658 write!(f, "{{async block}}")?;
663 if f.display_target.is_source_code() {
664 return Err(HirDisplayError::DisplaySourceCodeError(
665 DisplaySourceCodeError::UnknownType,
668 write!(f, "{{unknown}}")?;
670 TyKind::InferenceVar(..) => write!(f, "_")?,
671 TyKind::Generator(..) => write!(f, "{{generator}}")?,
672 TyKind::GeneratorWitness(..) => write!(f, "{{generator witness}}")?,
678 impl HirDisplay for CallableSig {
679 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
681 f.write_joined(self.params(), ", ")?;
683 if self.params().is_empty() {
690 let ret = self.ret();
699 fn fn_traits(db: &dyn DefDatabase, trait_: TraitId) -> impl Iterator<Item = TraitId> {
700 let krate = trait_.lookup(db).container.krate();
702 db.lang_item(krate, "fn".into()),
703 db.lang_item(krate, "fn_mut".into()),
704 db.lang_item(krate, "fn_once".into()),
706 array::IntoIter::new(fn_traits).into_iter().flatten().flat_map(|it| it.as_trait())
709 pub fn write_bounds_like_dyn_trait_with_prefix(
711 predicates: &[QuantifiedWhereClause],
712 f: &mut HirFormatter,
713 ) -> Result<(), HirDisplayError> {
714 write!(f, "{}", prefix)?;
715 if !predicates.is_empty() {
717 write_bounds_like_dyn_trait(predicates, f)
723 fn write_bounds_like_dyn_trait(
724 predicates: &[QuantifiedWhereClause],
725 f: &mut HirFormatter,
726 ) -> Result<(), HirDisplayError> {
727 // Note: This code is written to produce nice results (i.e.
728 // corresponding to surface Rust) for types that can occur in
729 // actual Rust. It will have weird results if the predicates
730 // aren't as expected (i.e. self types = $0, projection
731 // predicates for a certain trait come after the Implemented
732 // predicate for that trait).
733 let mut first = true;
734 let mut angle_open = false;
735 let mut is_fn_trait = false;
736 for p in predicates.iter() {
737 match p.skip_binders() {
738 WhereClause::Implemented(trait_ref) => {
739 let trait_ = trait_ref.hir_trait_id();
741 is_fn_trait = fn_traits(f.db.upcast(), trait_).any(|it| it == trait_);
743 if !is_fn_trait && angle_open {
750 // We assume that the self type is ^0.0 (i.e. the
751 // existential) here, which is the only thing that's
752 // possible in actual Rust, and hence don't print it
753 write!(f, "{}", f.db.trait_data(trait_).name)?;
754 if let [_, params @ ..] = &*trait_ref.substitution.as_slice(&Interner) {
757 params.first().and_then(|it| it.assert_ty_ref(&Interner).as_tuple())
760 f.write_joined(args.as_slice(&Interner), ", ")?;
763 } else if !params.is_empty() {
765 f.write_joined(params, ", ")?;
766 // there might be assoc type bindings, so we leave the angle brackets open
771 WhereClause::AliasEq(alias_eq) if is_fn_trait => {
774 alias_eq.ty.hir_fmt(f)?;
776 WhereClause::AliasEq(AliasEq { ty, alias }) => {
777 // in types in actual Rust, these will always come
778 // after the corresponding Implemented predicate
785 if let AliasTy::Projection(proj) = alias {
787 f.db.type_alias_data(from_assoc_type_id(proj.associated_ty_id));
788 write!(f, "{} = ", type_alias.name)?;
793 // FIXME implement these
794 WhereClause::LifetimeOutlives(_) => {}
795 WhereClause::TypeOutlives(_) => {}
805 fn fmt_trait_ref(tr: &TraitRef, f: &mut HirFormatter, use_as: bool) -> Result<(), HirDisplayError> {
806 if f.should_truncate() {
807 return write!(f, "{}", TYPE_HINT_TRUNCATION);
810 tr.self_type_parameter(&Interner).hir_fmt(f)?;
816 write!(f, "{}", f.db.trait_data(tr.hir_trait_id()).name)?;
817 if tr.substitution.len(&Interner) > 1 {
819 f.write_joined(&tr.substitution.as_slice(&Interner)[1..], ", ")?;
825 impl HirDisplay for TraitRef {
826 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
827 fmt_trait_ref(self, f, false)
831 impl HirDisplay for WhereClause {
832 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
833 if f.should_truncate() {
834 return write!(f, "{}", TYPE_HINT_TRUNCATION);
838 WhereClause::Implemented(trait_ref) => trait_ref.hir_fmt(f)?,
839 WhereClause::AliasEq(AliasEq { alias: AliasTy::Projection(projection_ty), ty }) => {
841 fmt_trait_ref(&projection_ty.trait_ref(f.db), f, true)?;
845 f.db.type_alias_data(from_assoc_type_id(projection_ty.associated_ty_id)).name,
849 WhereClause::AliasEq(_) => write!(f, "{{error}}")?,
851 // FIXME implement these
852 WhereClause::TypeOutlives(..) => {}
853 WhereClause::LifetimeOutlives(..) => {}
859 impl HirDisplay for LifetimeOutlives {
860 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
867 impl HirDisplay for Lifetime {
868 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
869 self.interned().hir_fmt(f)
873 impl HirDisplay for LifetimeData {
874 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
876 LifetimeData::BoundVar(idx) => idx.hir_fmt(f),
877 LifetimeData::InferenceVar(_) => write!(f, "_"),
878 LifetimeData::Placeholder(idx) => {
879 let id = lt_from_placeholder_idx(f.db, *idx);
880 let generics = generics(f.db.upcast(), id.parent);
881 let param_data = &generics.params.lifetimes[id.local_id];
882 write!(f, "{}", param_data.name)
884 LifetimeData::Static => write!(f, "'static"),
885 LifetimeData::Empty(_) => Ok(()),
886 LifetimeData::Erased => Ok(()),
887 LifetimeData::Phantom(_, _) => Ok(()),
892 impl HirDisplay for DomainGoal {
893 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
895 DomainGoal::Holds(wc) => {
896 write!(f, "Holds(")?;
900 _ => write!(f, "?")?,
906 pub fn write_visibility(
909 f: &mut HirFormatter,
910 ) -> Result<(), HirDisplayError> {
912 Visibility::Public => write!(f, "pub "),
913 Visibility::Module(vis_id) => {
914 let def_map = module_id.def_map(f.db.upcast());
915 let root_module_id = def_map.module_id(def_map.root());
916 if vis_id == module_id {
917 // pub(self) or omitted
919 } else if root_module_id == vis_id {
920 write!(f, "pub(crate) ")
921 } else if module_id.containing_module(f.db.upcast()) == Some(vis_id) {
922 write!(f, "pub(super) ")
924 write!(f, "pub(in ...) ")
930 impl HirDisplay for TypeRef {
931 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
933 TypeRef::Never => write!(f, "!")?,
934 TypeRef::Placeholder => write!(f, "_")?,
935 TypeRef::Tuple(elems) => {
937 f.write_joined(elems, ", ")?;
938 if elems.len() == 1 {
943 TypeRef::Path(path) => path.hir_fmt(f)?,
944 TypeRef::RawPtr(inner, mutability) => {
945 let mutability = match mutability {
946 hir_def::type_ref::Mutability::Shared => "*const ",
947 hir_def::type_ref::Mutability::Mut => "*mut ",
949 write!(f, "{}", mutability)?;
952 TypeRef::Reference(inner, lifetime, mutability) => {
953 let mutability = match mutability {
954 hir_def::type_ref::Mutability::Shared => "",
955 hir_def::type_ref::Mutability::Mut => "mut ",
958 if let Some(lifetime) = lifetime {
959 write!(f, "{} ", lifetime.name)?;
961 write!(f, "{}", mutability)?;
964 TypeRef::Array(inner) => {
967 // FIXME: Array length?
970 TypeRef::Slice(inner) => {
975 TypeRef::Fn(tys, is_varargs) => {
976 // FIXME: Function pointer qualifiers.
978 f.write_joined(&tys[..tys.len() - 1], ", ")?;
980 write!(f, "{}...", if tys.len() == 1 { "" } else { ", " })?;
983 let ret_ty = tys.last().unwrap();
985 TypeRef::Tuple(tup) if tup.is_empty() => {}
992 TypeRef::ImplTrait(bounds) => {
994 f.write_joined(bounds, " + ")?;
996 TypeRef::DynTrait(bounds) => {
998 f.write_joined(bounds, " + ")?;
1000 TypeRef::Error => write!(f, "{{error}}")?,
1006 impl HirDisplay for TypeBound {
1007 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1009 TypeBound::Path(path) => path.hir_fmt(f),
1010 TypeBound::Lifetime(lifetime) => write!(f, "{}", lifetime.name),
1011 TypeBound::Error => write!(f, "{{error}}"),
1016 impl HirDisplay for Path {
1017 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1018 match (self.type_anchor(), self.kind()) {
1019 (Some(anchor), _) => {
1024 (_, PathKind::Plain) => {}
1025 (_, PathKind::Abs) => write!(f, "::")?,
1026 (_, PathKind::Crate) => write!(f, "crate")?,
1027 (_, PathKind::Super(0)) => write!(f, "self")?,
1028 (_, PathKind::Super(n)) => {
1029 write!(f, "super")?;
1031 write!(f, "::super")?;
1034 (_, PathKind::DollarCrate(_)) => write!(f, "{{extern_crate}}")?,
1037 for (seg_idx, segment) in self.segments().iter().enumerate() {
1041 write!(f, "{}", segment.name)?;
1042 if let Some(generic_args) = segment.args_and_bindings {
1043 // We should be in type context, so format as `Foo<Bar>` instead of `Foo::<Bar>`.
1044 // Do we actually format expressions?
1046 let mut first = true;
1047 for arg in &generic_args.args {
1050 if generic_args.has_self_type {
1051 // FIXME: Convert to `<Ty as Trait>` form.
1052 write!(f, "Self = ")?;
1059 for binding in &generic_args.bindings {
1065 write!(f, "{}", binding.name)?;
1066 match &binding.type_ref {
1073 f.write_joined(&binding.bounds, " + ")?;
1084 impl HirDisplay for hir_def::path::GenericArg {
1085 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1087 hir_def::path::GenericArg::Type(ty) => ty.hir_fmt(f),
1088 hir_def::path::GenericArg::Lifetime(lifetime) => write!(f, "{}", lifetime.name),