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 chalk_db::from_chalk, utils::generics, AdtId, AliasEq, AliasTy, CallableDefId,
25 CallableSig, Const, ConstValue, DomainGoal, GenericArg, ImplTraitId, Interner, Lifetime,
26 LifetimeData, LifetimeOutlives, Mutability, OpaqueTy, ProjectionTy, ProjectionTyExt,
27 QuantifiedWhereClause, Scalar, TraitRef, TraitRefExt, Ty, TyExt, TyKind, WhereClause,
30 pub struct HirFormatter<'a> {
31 pub db: &'a dyn HirDatabase,
32 fmt: &'a mut dyn fmt::Write,
35 pub(crate) max_size: Option<usize>,
36 omit_verbose_types: bool,
37 display_target: DisplayTarget,
40 pub trait HirDisplay {
41 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError>;
43 /// Returns a `Display`able type that is human-readable.
44 fn into_displayable<'a>(
46 db: &'a dyn HirDatabase,
47 max_size: Option<usize>,
48 omit_verbose_types: bool,
49 display_target: DisplayTarget,
50 ) -> HirDisplayWrapper<'a, Self>
55 !matches!(display_target, DisplayTarget::SourceCode { .. }),
56 "HirDisplayWrapper cannot fail with DisplaySourceCodeError, use HirDisplay::hir_fmt directly instead"
58 HirDisplayWrapper { db, t: self, max_size, omit_verbose_types, display_target }
61 /// Returns a `Display`able type that is human-readable.
62 /// Use this for showing types to the user (e.g. diagnostics)
63 fn display<'a>(&'a self, db: &'a dyn HirDatabase) -> HirDisplayWrapper<'a, Self>
71 omit_verbose_types: false,
72 display_target: DisplayTarget::Diagnostics,
76 /// Returns a `Display`able type that is human-readable and tries to be succinct.
77 /// Use this for showing types to the user where space is constrained (e.g. doc popups)
78 fn display_truncated<'a>(
80 db: &'a dyn HirDatabase,
81 max_size: Option<usize>,
82 ) -> HirDisplayWrapper<'a, Self>
90 omit_verbose_types: true,
91 display_target: DisplayTarget::Diagnostics,
95 /// Returns a String representation of `self` that can be inserted into the given module.
96 /// Use this when generating code (e.g. assists)
97 fn display_source_code<'a>(
99 db: &'a dyn HirDatabase,
101 ) -> Result<String, DisplaySourceCodeError> {
102 let mut result = String::new();
103 match self.hir_fmt(&mut HirFormatter {
106 buf: String::with_capacity(20),
109 omit_verbose_types: false,
110 display_target: DisplayTarget::SourceCode { module_id },
113 Err(HirDisplayError::FmtError) => panic!("Writing to String can't fail!"),
114 Err(HirDisplayError::DisplaySourceCodeError(e)) => return Err(e),
119 /// Returns a String representation of `self` for test purposes
120 fn display_test<'a>(&'a self, db: &'a dyn HirDatabase) -> HirDisplayWrapper<'a, Self>
128 omit_verbose_types: false,
129 display_target: DisplayTarget::Test,
134 impl<'a> HirFormatter<'a> {
135 pub fn write_joined<T: HirDisplay>(
137 iter: impl IntoIterator<Item = T>,
139 ) -> Result<(), HirDisplayError> {
140 let mut first = true;
143 write!(self, "{}", sep)?;
151 /// This allows using the `write!` macro directly with a `HirFormatter`.
152 pub fn write_fmt(&mut self, args: fmt::Arguments) -> Result<(), HirDisplayError> {
153 // We write to a buffer first to track output size
155 fmt::write(&mut self.buf, args)?;
156 self.curr_size += self.buf.len();
158 // Then we write to the internal formatter from the buffer
159 self.fmt.write_str(&self.buf).map_err(HirDisplayError::from)
162 pub fn should_truncate(&self) -> bool {
163 if let Some(max_size) = self.max_size {
164 self.curr_size >= max_size
170 pub fn omit_verbose_types(&self) -> bool {
171 self.omit_verbose_types
175 #[derive(Clone, Copy)]
176 pub enum DisplayTarget {
177 /// Display types for inlays, doc popups, autocompletion, etc...
178 /// Showing `{unknown}` or not qualifying paths is fine here.
179 /// There's no reason for this to fail.
181 /// Display types for inserting them in source files.
182 /// The generated code should compile, so paths need to be qualified.
183 SourceCode { module_id: ModuleId },
184 /// Only for test purpose to keep real types
189 fn is_source_code(&self) -> bool {
190 matches!(self, Self::SourceCode { .. })
192 fn is_test(&self) -> bool {
193 matches!(self, Self::Test)
198 pub enum DisplaySourceCodeError {
204 pub enum HirDisplayError {
205 /// Errors that can occur when generating source code
206 DisplaySourceCodeError(DisplaySourceCodeError),
207 /// `FmtError` is required to be compatible with std::fmt::Display
210 impl From<fmt::Error> for HirDisplayError {
211 fn from(_: fmt::Error) -> Self {
216 pub struct HirDisplayWrapper<'a, T> {
217 db: &'a dyn HirDatabase,
219 max_size: Option<usize>,
220 omit_verbose_types: bool,
221 display_target: DisplayTarget,
224 impl<'a, T> fmt::Display for HirDisplayWrapper<'a, T>
228 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
229 match self.t.hir_fmt(&mut HirFormatter {
232 buf: String::with_capacity(20),
234 max_size: self.max_size,
235 omit_verbose_types: self.omit_verbose_types,
236 display_target: self.display_target,
239 Err(HirDisplayError::FmtError) => Err(fmt::Error),
240 Err(HirDisplayError::DisplaySourceCodeError(_)) => {
241 // This should never happen
242 panic!("HirDisplay::hir_fmt failed with DisplaySourceCodeError when calling Display::fmt!")
248 const TYPE_HINT_TRUNCATION: &str = "…";
250 impl<T: HirDisplay> HirDisplay for &'_ T {
251 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
252 HirDisplay::hir_fmt(*self, f)
256 impl HirDisplay for ProjectionTy {
257 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
258 if f.should_truncate() {
259 return write!(f, "{}", TYPE_HINT_TRUNCATION);
262 let trait_ = f.db.trait_data(self.trait_(f.db));
264 self.self_type_parameter(&Interner).hir_fmt(f)?;
265 write!(f, " as {}", trait_.name)?;
266 if self.substitution.len(&Interner) > 1 {
268 f.write_joined(&self.substitution.as_slice(&Interner)[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),
290 crate::GenericArgData::Lifetime(lt) => lt.hir_fmt(f),
291 crate::GenericArgData::Const(c) => c.hir_fmt(f),
296 impl HirDisplay for Const {
297 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
298 let data = self.interned();
300 ConstValue::BoundVar(idx) => idx.hir_fmt(f),
301 ConstValue::InferenceVar(..) => write!(f, "_"),
302 ConstValue::Placeholder(idx) => {
303 let id = const_from_placeholder_idx(f.db, idx);
304 let generics = generics(f.db.upcast(), id.parent);
305 let param_data = &generics.params.consts[id.local_id];
306 write!(f, "{}", param_data.name)
308 ConstValue::Concrete(_) => write!(f, "_"),
313 impl HirDisplay for BoundVar {
314 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
315 write!(f, "?{}.{}", self.debruijn.depth(), self.index)
319 impl HirDisplay for Ty {
320 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
321 if f.should_truncate() {
322 return write!(f, "{}", TYPE_HINT_TRUNCATION);
325 match self.kind(&Interner) {
326 TyKind::Never => write!(f, "!")?,
327 TyKind::Str => write!(f, "str")?,
328 TyKind::Scalar(Scalar::Bool) => write!(f, "bool")?,
329 TyKind::Scalar(Scalar::Char) => write!(f, "char")?,
330 &TyKind::Scalar(Scalar::Float(t)) => write!(f, "{}", primitive::float_ty_to_string(t))?,
331 &TyKind::Scalar(Scalar::Int(t)) => write!(f, "{}", primitive::int_ty_to_string(t))?,
332 &TyKind::Scalar(Scalar::Uint(t)) => write!(f, "{}", primitive::uint_ty_to_string(t))?,
333 TyKind::Slice(t) => {
338 TyKind::Array(t, c) => {
345 TyKind::Raw(m, t) | TyKind::Ref(m, _, t) => {
346 if matches!(self.kind(&Interner), TyKind::Raw(..)) {
351 Mutability::Not => "const ",
352 Mutability::Mut => "mut ",
360 Mutability::Not => "",
361 Mutability::Mut => "mut ",
366 // FIXME: all this just to decide whether to use parentheses...
368 let predicates: Vec<_> = match t.kind(&Interner) {
369 TyKind::Dyn(dyn_ty) if dyn_ty.bounds.skip_binders().interned().len() > 1 => {
370 dyn_ty.bounds.skip_binders().interned().iter().cloned().collect()
372 &TyKind::Alias(AliasTy::Opaque(OpaqueTy {
374 substitution: ref parameters,
376 let impl_trait_id = f.db.lookup_intern_impl_trait_id(opaque_ty_id.into());
377 if let ImplTraitId::ReturnTypeImplTrait(func, idx) = impl_trait_id {
379 f.db.return_type_impl_traits(func)
380 .expect("impl trait id without data");
383 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
384 let bounds = data.substitute(&Interner, parameters);
385 bounds.into_value_and_skipped_binders().0
393 if let Some(WhereClause::Implemented(trait_ref)) =
394 predicates.get(0).map(|b| b.skip_binders())
396 let trait_ = trait_ref.hir_trait_id();
397 if fn_traits(f.db.upcast(), trait_).any(|it| it == trait_)
398 && predicates.len() <= 2
404 if predicates.len() > 1 {
412 TyKind::Tuple(_, substs) => {
413 if substs.len(&Interner) == 1 {
415 substs.at(&Interner, 0).hir_fmt(f)?;
419 f.write_joined(&*substs.as_slice(&Interner), ", ")?;
423 TyKind::Function(fn_ptr) => {
424 let sig = CallableSig::from_fn_ptr(fn_ptr);
427 TyKind::FnDef(def, parameters) => {
428 let def = from_chalk(f.db, *def);
429 let sig = f.db.callable_item_signature(def).substitute(&Interner, parameters);
431 CallableDefId::FunctionId(ff) => {
432 write!(f, "fn {}", f.db.function_data(ff).name)?
434 CallableDefId::StructId(s) => write!(f, "{}", f.db.struct_data(s).name)?,
435 CallableDefId::EnumVariantId(e) => {
436 write!(f, "{}", f.db.enum_data(e.parent).variants[e.local_id].name)?
439 if parameters.len(&Interner) > 0 {
440 let generics = generics(f.db.upcast(), def.into());
441 let (parent_params, self_param, type_params, _impl_trait_params) =
442 generics.provenance_split();
443 let total_len = parent_params + self_param + type_params;
444 // We print all params except implicit impl Trait params. Still a bit weird; should we leave out parent and self?
447 f.write_joined(¶meters.as_slice(&Interner)[..total_len], ", ")?;
452 f.write_joined(sig.params(), ", ")?;
460 TyKind::Adt(AdtId(def_id), parameters) => {
461 match f.display_target {
462 DisplayTarget::Diagnostics | DisplayTarget::Test => {
463 let name = match *def_id {
464 hir_def::AdtId::StructId(it) => f.db.struct_data(it).name.clone(),
465 hir_def::AdtId::UnionId(it) => f.db.union_data(it).name.clone(),
466 hir_def::AdtId::EnumId(it) => f.db.enum_data(it).name.clone(),
468 write!(f, "{}", name)?;
470 DisplayTarget::SourceCode { module_id } => {
471 if let Some(path) = find_path::find_path(
473 ItemInNs::Types((*def_id).into()),
476 write!(f, "{}", path)?;
478 return Err(HirDisplayError::DisplaySourceCodeError(
479 DisplaySourceCodeError::PathNotFound,
485 if parameters.len(&Interner) > 0 {
486 let parameters_to_write = if f.display_target.is_source_code()
487 || f.omit_verbose_types()
490 .as_generic_def(f.db)
491 .map(|generic_def_id| f.db.generic_defaults(generic_def_id))
492 .filter(|defaults| !defaults.is_empty())
494 None => parameters.as_slice(&Interner),
495 Some(default_parameters) => {
496 let mut default_from = 0;
497 for (i, parameter) in parameters.iter(&Interner).enumerate() {
499 parameter.assert_ty_ref(&Interner).kind(&Interner),
500 default_parameters.get(i),
502 (&TyKind::Error, _) | (_, None) => {
503 default_from = i + 1;
505 (_, Some(default_parameter)) => {
507 default_parameter.clone().substitute(
509 &subst_prefix(parameters, i),
511 if parameter.assert_ty_ref(&Interner) != &actual_default
513 default_from = i + 1;
518 ¶meters.as_slice(&Interner)[0..default_from]
522 parameters.as_slice(&Interner)
524 if !parameters_to_write.is_empty() {
526 f.write_joined(parameters_to_write, ", ")?;
531 TyKind::AssociatedType(assoc_type_id, parameters) => {
532 let type_alias = from_assoc_type_id(*assoc_type_id);
533 let trait_ = match type_alias.lookup(f.db.upcast()).container {
534 AssocContainerId::TraitId(it) => it,
535 _ => panic!("not an associated type"),
537 let trait_ = f.db.trait_data(trait_);
538 let type_alias_data = f.db.type_alias_data(type_alias);
540 // Use placeholder associated types when the target is test (https://rust-lang.github.io/chalk/book/clauses/type_equality.html#placeholder-associated-types)
541 if f.display_target.is_test() {
542 write!(f, "{}::{}", trait_.name, type_alias_data.name)?;
543 if parameters.len(&Interner) > 0 {
545 f.write_joined(&*parameters.as_slice(&Interner), ", ")?;
549 let projection_ty = ProjectionTy {
550 associated_ty_id: to_assoc_type_id(type_alias),
551 substitution: parameters.clone(),
554 projection_ty.hir_fmt(f)?;
557 TyKind::Foreign(type_alias) => {
558 let type_alias = f.db.type_alias_data(from_foreign_def_id(*type_alias));
559 write!(f, "{}", type_alias.name)?;
561 TyKind::OpaqueType(opaque_ty_id, parameters) => {
562 let impl_trait_id = f.db.lookup_intern_impl_trait_id((*opaque_ty_id).into());
563 match impl_trait_id {
564 ImplTraitId::ReturnTypeImplTrait(func, idx) => {
566 f.db.return_type_impl_traits(func).expect("impl trait id without data");
569 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
570 let bounds = data.substitute(&Interner, ¶meters);
571 write_bounds_like_dyn_trait_with_prefix("impl", bounds.skip_binders(), f)?;
572 // FIXME: it would maybe be good to distinguish this from the alias type (when debug printing), and to show the substitution
574 ImplTraitId::AsyncBlockTypeImplTrait(..) => {
575 write!(f, "impl Future<Output = ")?;
576 parameters.at(&Interner, 0).hir_fmt(f)?;
581 TyKind::Closure(.., substs) => {
582 if f.display_target.is_source_code() {
583 return Err(HirDisplayError::DisplaySourceCodeError(
584 DisplaySourceCodeError::Closure,
587 let sig = substs.at(&Interner, 0).assert_ty_ref(&Interner).callable_sig(f.db);
588 if let Some(sig) = sig {
589 if sig.params().is_empty() {
591 } else if f.omit_verbose_types() {
592 write!(f, "|{}|", TYPE_HINT_TRUNCATION)?;
595 f.write_joined(sig.params(), ", ")?;
600 sig.ret().hir_fmt(f)?;
602 write!(f, "{{closure}}")?;
605 TyKind::Placeholder(idx) => {
606 let id = from_placeholder_idx(f.db, *idx);
607 let generics = generics(f.db.upcast(), id.parent);
608 let param_data = &generics.params.types[id.local_id];
609 match param_data.provenance {
610 TypeParamProvenance::TypeParamList | TypeParamProvenance::TraitSelf => {
611 write!(f, "{}", param_data.name.clone().unwrap_or_else(Name::missing))?
613 TypeParamProvenance::ArgumentImplTrait => {
614 let substs = generics.type_params_subst(f.db);
616 f.db.generic_predicates(id.parent)
618 .map(|pred| pred.clone().substitute(&Interner, &substs))
619 .filter(|wc| match &wc.skip_binders() {
620 WhereClause::Implemented(tr) => {
621 &tr.self_type_parameter(&Interner) == self
623 WhereClause::AliasEq(AliasEq {
624 alias: AliasTy::Projection(proj),
626 }) => &proj.self_type_parameter(&Interner) == self,
629 .collect::<Vec<_>>();
630 write_bounds_like_dyn_trait_with_prefix("impl", &bounds, f)?;
634 TyKind::BoundVar(idx) => idx.hir_fmt(f)?,
635 TyKind::Dyn(dyn_ty) => {
636 write_bounds_like_dyn_trait_with_prefix(
638 dyn_ty.bounds.skip_binders().interned(),
642 TyKind::Alias(AliasTy::Projection(p_ty)) => p_ty.hir_fmt(f)?,
643 TyKind::Alias(AliasTy::Opaque(opaque_ty)) => {
644 let impl_trait_id = f.db.lookup_intern_impl_trait_id(opaque_ty.opaque_ty_id.into());
645 match impl_trait_id {
646 ImplTraitId::ReturnTypeImplTrait(func, idx) => {
648 f.db.return_type_impl_traits(func).expect("impl trait id without data");
651 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
652 let bounds = data.substitute(&Interner, &opaque_ty.substitution);
653 write_bounds_like_dyn_trait_with_prefix("impl", bounds.skip_binders(), f)?;
655 ImplTraitId::AsyncBlockTypeImplTrait(..) => {
656 write!(f, "{{async block}}")?;
661 if f.display_target.is_source_code() {
662 return Err(HirDisplayError::DisplaySourceCodeError(
663 DisplaySourceCodeError::UnknownType,
666 write!(f, "{{unknown}}")?;
668 TyKind::InferenceVar(..) => write!(f, "_")?,
669 TyKind::Generator(..) => write!(f, "{{generator}}")?,
670 TyKind::GeneratorWitness(..) => write!(f, "{{generator witness}}")?,
676 impl HirDisplay for CallableSig {
677 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
679 f.write_joined(self.params(), ", ")?;
681 if self.params().is_empty() {
688 let ret = self.ret();
697 fn fn_traits(db: &dyn DefDatabase, trait_: TraitId) -> impl Iterator<Item = TraitId> {
698 let krate = trait_.lookup(db).container.krate();
700 db.lang_item(krate, "fn".into()),
701 db.lang_item(krate, "fn_mut".into()),
702 db.lang_item(krate, "fn_once".into()),
704 array::IntoIter::new(fn_traits).into_iter().flatten().flat_map(|it| it.as_trait())
707 pub fn write_bounds_like_dyn_trait_with_prefix(
709 predicates: &[QuantifiedWhereClause],
710 f: &mut HirFormatter,
711 ) -> Result<(), HirDisplayError> {
712 write!(f, "{}", prefix)?;
713 if !predicates.is_empty() {
715 write_bounds_like_dyn_trait(predicates, f)
721 fn write_bounds_like_dyn_trait(
722 predicates: &[QuantifiedWhereClause],
723 f: &mut HirFormatter,
724 ) -> Result<(), HirDisplayError> {
725 // Note: This code is written to produce nice results (i.e.
726 // corresponding to surface Rust) for types that can occur in
727 // actual Rust. It will have weird results if the predicates
728 // aren't as expected (i.e. self types = $0, projection
729 // predicates for a certain trait come after the Implemented
730 // predicate for that trait).
731 let mut first = true;
732 let mut angle_open = false;
733 let mut is_fn_trait = false;
734 for p in predicates.iter() {
735 match p.skip_binders() {
736 WhereClause::Implemented(trait_ref) => {
737 let trait_ = trait_ref.hir_trait_id();
739 is_fn_trait = fn_traits(f.db.upcast(), trait_).any(|it| it == trait_);
741 if !is_fn_trait && angle_open {
748 // We assume that the self type is ^0.0 (i.e. the
749 // existential) here, which is the only thing that's
750 // possible in actual Rust, and hence don't print it
751 write!(f, "{}", f.db.trait_data(trait_).name)?;
752 if let [_, params @ ..] = &*trait_ref.substitution.as_slice(&Interner) {
755 params.first().and_then(|it| it.assert_ty_ref(&Interner).as_tuple())
758 f.write_joined(args.as_slice(&Interner), ", ")?;
761 } else if !params.is_empty() {
763 f.write_joined(params, ", ")?;
764 // there might be assoc type bindings, so we leave the angle brackets open
769 WhereClause::AliasEq(alias_eq) if is_fn_trait => {
772 alias_eq.ty.hir_fmt(f)?;
774 WhereClause::AliasEq(AliasEq { ty, alias }) => {
775 // in types in actual Rust, these will always come
776 // after the corresponding Implemented predicate
783 if let AliasTy::Projection(proj) = alias {
785 f.db.type_alias_data(from_assoc_type_id(proj.associated_ty_id));
786 write!(f, "{} = ", type_alias.name)?;
791 // FIXME implement these
792 WhereClause::LifetimeOutlives(_) => {}
793 WhereClause::TypeOutlives(_) => {}
803 fn fmt_trait_ref(tr: &TraitRef, f: &mut HirFormatter, use_as: bool) -> Result<(), HirDisplayError> {
804 if f.should_truncate() {
805 return write!(f, "{}", TYPE_HINT_TRUNCATION);
808 tr.self_type_parameter(&Interner).hir_fmt(f)?;
814 write!(f, "{}", f.db.trait_data(tr.hir_trait_id()).name)?;
815 if tr.substitution.len(&Interner) > 1 {
817 f.write_joined(&tr.substitution.as_slice(&Interner)[1..], ", ")?;
823 impl HirDisplay for TraitRef {
824 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
825 fmt_trait_ref(self, f, false)
829 impl HirDisplay for WhereClause {
830 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
831 if f.should_truncate() {
832 return write!(f, "{}", TYPE_HINT_TRUNCATION);
836 WhereClause::Implemented(trait_ref) => trait_ref.hir_fmt(f)?,
837 WhereClause::AliasEq(AliasEq { alias: AliasTy::Projection(projection_ty), ty }) => {
839 fmt_trait_ref(&projection_ty.trait_ref(f.db), f, true)?;
843 f.db.type_alias_data(from_assoc_type_id(projection_ty.associated_ty_id)).name,
847 WhereClause::AliasEq(_) => write!(f, "{{error}}")?,
849 // FIXME implement these
850 WhereClause::TypeOutlives(..) => {}
851 WhereClause::LifetimeOutlives(..) => {}
857 impl HirDisplay for LifetimeOutlives {
858 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
865 impl HirDisplay for Lifetime {
866 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
867 self.interned().hir_fmt(f)
871 impl HirDisplay for LifetimeData {
872 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
874 LifetimeData::BoundVar(idx) => idx.hir_fmt(f),
875 LifetimeData::InferenceVar(_) => write!(f, "_"),
876 LifetimeData::Placeholder(idx) => {
877 let id = lt_from_placeholder_idx(f.db, *idx);
878 let generics = generics(f.db.upcast(), id.parent);
879 let param_data = &generics.params.lifetimes[id.local_id];
880 write!(f, "{}", param_data.name)
882 LifetimeData::Static => write!(f, "'static"),
883 LifetimeData::Empty(_) => Ok(()),
884 LifetimeData::Erased => Ok(()),
885 LifetimeData::Phantom(_, _) => Ok(()),
890 impl HirDisplay for DomainGoal {
891 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
893 DomainGoal::Holds(wc) => {
894 write!(f, "Holds(")?;
898 _ => write!(f, "?")?,
904 pub fn write_visibility(
907 f: &mut HirFormatter,
908 ) -> Result<(), HirDisplayError> {
910 Visibility::Public => write!(f, "pub "),
911 Visibility::Module(vis_id) => {
912 let def_map = module_id.def_map(f.db.upcast());
913 let root_module_id = def_map.module_id(def_map.root());
914 if vis_id == module_id {
915 // pub(self) or omitted
917 } else if root_module_id == vis_id {
918 write!(f, "pub(crate) ")
919 } else if module_id.containing_module(f.db.upcast()) == Some(vis_id) {
920 write!(f, "pub(super) ")
922 write!(f, "pub(in ...) ")
928 impl HirDisplay for TypeRef {
929 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
931 TypeRef::Never => write!(f, "!")?,
932 TypeRef::Placeholder => write!(f, "_")?,
933 TypeRef::Tuple(elems) => {
935 f.write_joined(elems, ", ")?;
936 if elems.len() == 1 {
941 TypeRef::Path(path) => path.hir_fmt(f)?,
942 TypeRef::RawPtr(inner, mutability) => {
943 let mutability = match mutability {
944 hir_def::type_ref::Mutability::Shared => "*const ",
945 hir_def::type_ref::Mutability::Mut => "*mut ",
947 write!(f, "{}", mutability)?;
950 TypeRef::Reference(inner, lifetime, mutability) => {
951 let mutability = match mutability {
952 hir_def::type_ref::Mutability::Shared => "",
953 hir_def::type_ref::Mutability::Mut => "mut ",
956 if let Some(lifetime) = lifetime {
957 write!(f, "{} ", lifetime.name)?;
959 write!(f, "{}", mutability)?;
962 TypeRef::Array(inner) => {
965 // FIXME: Array length?
968 TypeRef::Slice(inner) => {
973 TypeRef::Fn(tys, is_varargs) => {
974 // FIXME: Function pointer qualifiers.
976 f.write_joined(&tys[..tys.len() - 1], ", ")?;
978 write!(f, "{}...", if tys.len() == 1 { "" } else { ", " })?;
981 let ret_ty = tys.last().unwrap();
983 TypeRef::Tuple(tup) if tup.is_empty() => {}
990 TypeRef::ImplTrait(bounds) => {
992 f.write_joined(bounds, " + ")?;
994 TypeRef::DynTrait(bounds) => {
996 f.write_joined(bounds, " + ")?;
998 TypeRef::Error => write!(f, "{{error}}")?,
1004 impl HirDisplay for TypeBound {
1005 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1007 TypeBound::Path(path) => path.hir_fmt(f),
1008 TypeBound::Lifetime(lifetime) => write!(f, "{}", lifetime.name),
1009 TypeBound::Error => write!(f, "{{error}}"),
1014 impl HirDisplay for Path {
1015 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1016 match (self.type_anchor(), self.kind()) {
1017 (Some(anchor), _) => {
1022 (_, PathKind::Plain) => {}
1023 (_, PathKind::Abs) => write!(f, "::")?,
1024 (_, PathKind::Crate) => write!(f, "crate")?,
1025 (_, PathKind::Super(0)) => write!(f, "self")?,
1026 (_, PathKind::Super(n)) => {
1027 write!(f, "super")?;
1029 write!(f, "::super")?;
1032 (_, PathKind::DollarCrate(_)) => write!(f, "{{extern_crate}}")?,
1035 for (seg_idx, segment) in self.segments().iter().enumerate() {
1039 write!(f, "{}", segment.name)?;
1040 if let Some(generic_args) = segment.args_and_bindings {
1041 // We should be in type context, so format as `Foo<Bar>` instead of `Foo::<Bar>`.
1042 // Do we actually format expressions?
1044 let mut first = true;
1045 for arg in &generic_args.args {
1048 if generic_args.has_self_type {
1049 // FIXME: Convert to `<Ty as Trait>` form.
1050 write!(f, "Self = ")?;
1057 for binding in &generic_args.bindings {
1063 write!(f, "{}", binding.name)?;
1064 match &binding.type_ref {
1071 f.write_joined(&binding.bounds, " + ")?;
1082 impl HirDisplay for hir_def::path::GenericArg {
1083 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1085 hir_def::path::GenericArg::Type(ty) => ty.hir_fmt(f),
1086 hir_def::path::GenericArg::Lifetime(lifetime) => write!(f, "{}", lifetime.name),