1 //! The type system. We currently use this to infer types for completion, hover
2 //! information and various assists.
5 pub(crate) mod primitive;
9 pub(crate) mod method_resolution;
13 pub(crate) mod display;
17 use std::{fmt, iter, mem};
22 generics::{GenericParams, HasGenericParams},
24 Adt, Crate, DefWithBody, FloatTy, IntTy, Mutability, Name, Trait, TypeAlias, Uncertain,
26 use display::{HirDisplay, HirFormatter};
28 pub(crate) use autoderef::autoderef;
29 pub(crate) use infer::{infer_query, InferTy, InferenceResult};
30 pub use lower::CallableDef;
31 pub(crate) use lower::{
32 callable_item_sig, generic_defaults_query, generic_predicates_for_param_query,
33 generic_predicates_query, type_for_def, type_for_field, Namespace, TypableDef,
35 pub(crate) use traits::{InEnvironment, Obligation, ProjectionPredicate, TraitEnvironment};
37 /// A type constructor or type name: this might be something like the primitive
38 /// type `bool`, a struct like `Vec`, or things like function pointers or
40 #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
42 /// The primitive boolean type. Written as `bool`.
45 /// The primitive character type; holds a Unicode scalar value
46 /// (a non-surrogate code point). Written as `char`.
49 /// A primitive integer type. For example, `i32`.
50 Int(Uncertain<IntTy>),
52 /// A primitive floating-point type. For example, `f64`.
53 Float(Uncertain<FloatTy>),
55 /// Structures, enumerations and unions.
58 /// The pointee of a string slice. Written as `str`.
61 /// The pointee of an array slice. Written as `[T]`.
64 /// An array with the given length. Written as `[T; n]`.
67 /// A raw pointer. Written as `*mut T` or `*const T`
70 /// A reference; a pointer with an associated lifetime. Written as
71 /// `&'a mut T` or `&'a T`.
74 /// The anonymous type of a function declaration/definition. Each
75 /// function has a unique type, which is output (for a function
76 /// named `foo` returning an `i32`) as `fn() -> i32 {foo}`.
78 /// This includes tuple struct / enum variant constructors as well.
80 /// For example the type of `bar` here:
83 /// fn foo() -> i32 { 1 }
84 /// let bar = foo; // bar: fn() -> i32 {foo}
88 /// A pointer to a function. Written as `fn() -> i32`.
90 /// For example the type of `bar` here:
93 /// fn foo() -> i32 { 1 }
94 /// let bar: fn() -> i32 = foo;
96 FnPtr { num_args: u16 },
98 /// The never type `!`.
101 /// A tuple type. For example, `(i32, bool)`.
102 Tuple { cardinality: u16 },
104 /// Represents an associated item like `Iterator::Item`. This is used
105 /// when we have tried to normalize a projection like `T::Item` but
106 /// couldn't find a better representation. In that case, we generate
107 /// an **application type** like `(Iterator::Item)<T>`.
108 AssociatedType(TypeAlias),
110 /// The type of a specific closure.
112 /// The closure signature is stored in a `FnPtr` type in the first type
114 Closure { def: DefWithBody, expr: ExprId },
118 pub fn num_ty_params(self, db: &impl HirDatabase) -> usize {
125 | TypeCtor::Never => 0,
128 | TypeCtor::RawPtr(_)
130 | TypeCtor::Closure { .. } // 1 param representing the signature of the closure
132 TypeCtor::Adt(adt) => {
133 let generic_params = adt.generic_params(db);
134 generic_params.count_params_including_parent()
136 TypeCtor::FnDef(callable) => {
137 let generic_params = callable.generic_params(db);
138 generic_params.count_params_including_parent()
140 TypeCtor::AssociatedType(type_alias) => {
141 let generic_params = type_alias.generic_params(db);
142 generic_params.count_params_including_parent()
144 TypeCtor::FnPtr { num_args } => num_args as usize + 1,
145 TypeCtor::Tuple { cardinality } => cardinality as usize,
149 pub fn krate(self, db: &impl HirDatabase) -> Option<Crate> {
159 | TypeCtor::RawPtr(_)
161 | TypeCtor::FnPtr { .. }
162 | TypeCtor::Tuple { .. } => None,
163 TypeCtor::Closure { def, .. } => def.krate(db),
164 TypeCtor::Adt(adt) => adt.krate(db),
165 TypeCtor::FnDef(callable) => callable.krate(db),
166 TypeCtor::AssociatedType(type_alias) => type_alias.krate(db),
170 pub fn as_generic_def(self) -> Option<crate::generics::GenericDef> {
180 | TypeCtor::RawPtr(_)
182 | TypeCtor::FnPtr { .. }
183 | TypeCtor::Tuple { .. }
184 | TypeCtor::Closure { .. } => None,
185 TypeCtor::Adt(adt) => Some(adt.into()),
186 TypeCtor::FnDef(callable) => Some(callable.into()),
187 TypeCtor::AssociatedType(type_alias) => Some(type_alias.into()),
192 /// A nominal type with (maybe 0) type parameters. This might be a primitive
193 /// type like `bool`, a struct, tuple, function pointer, reference or
194 /// several other things.
195 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
196 pub struct ApplicationTy {
198 pub parameters: Substs,
201 /// A "projection" type corresponds to an (unnormalized)
202 /// projection like `<P0 as Trait<P1..Pn>>::Foo`. Note that the
203 /// trait and all its parameters are fully known.
204 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
205 pub struct ProjectionTy {
206 pub associated_ty: TypeAlias,
207 pub parameters: Substs,
211 pub fn trait_ref(&self, db: &impl HirDatabase) -> TraitRef {
216 .expect("projection ty without parent trait"),
217 substs: self.parameters.clone(),
222 impl TypeWalk for ProjectionTy {
223 fn walk(&self, f: &mut impl FnMut(&Ty)) {
224 self.parameters.walk(f);
227 fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) {
228 self.parameters.walk_mut_binders(f, binders);
234 /// See also the `TyKind` enum in rustc (librustc/ty/sty.rs), which represents
235 /// the same thing (but in a different way).
237 /// This should be cheap to clone.
238 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
240 /// A nominal type with (maybe 0) type parameters. This might be a primitive
241 /// type like `bool`, a struct, tuple, function pointer, reference or
242 /// several other things.
243 Apply(ApplicationTy),
245 /// A "projection" type corresponds to an (unnormalized)
246 /// projection like `<P0 as Trait<P1..Pn>>::Foo`. Note that the
247 /// trait and all its parameters are fully known.
248 Projection(ProjectionTy),
250 /// A type parameter; for example, `T` in `fn f<T>(x: T) {}
252 /// The index of the parameter (starting with parameters from the
253 /// surrounding impl, then the current function).
255 /// The name of the parameter, for displaying.
256 // FIXME get rid of this
260 /// A bound type variable. Used during trait resolution to represent Chalk
261 /// variables, and in `Dyn` and `Opaque` bounds to represent the `Self` type.
264 /// A type variable used during type checking. Not to be confused with a
268 /// A trait object (`dyn Trait` or bare `Trait` in pre-2018 Rust).
270 /// The predicates are quantified over the `Self` type, i.e. `Ty::Bound(0)`
271 /// represents the `Self` type inside the bounds. This is currently
272 /// implicit; Chalk has the `Binders` struct to make it explicit, but it
273 /// didn't seem worth the overhead yet.
274 Dyn(Arc<[GenericPredicate]>),
276 /// An opaque type (`impl Trait`).
278 /// The predicates are quantified over the `Self` type; see `Ty::Dyn` for
280 Opaque(Arc<[GenericPredicate]>),
282 /// A placeholder for a type which could not be computed; this is propagated
283 /// to avoid useless error messages. Doubles as a placeholder where type
284 /// variables are inserted before type checking, since we want to try to
285 /// infer a better type here anyway -- for the IDE use case, we want to try
286 /// to infer as much as possible even in the presence of type errors.
290 /// A list of substitutions for generic parameters.
291 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
292 pub struct Substs(Arc<[Ty]>);
294 impl TypeWalk for Substs {
295 fn walk(&self, f: &mut impl FnMut(&Ty)) {
296 for t in self.0.iter() {
301 fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) {
302 for t in make_mut_slice(&mut self.0) {
303 t.walk_mut_binders(f, binders);
309 pub fn empty() -> Substs {
313 pub fn single(ty: Ty) -> Substs {
314 Substs(Arc::new([ty]))
317 pub fn prefix(&self, n: usize) -> Substs {
318 Substs(self.0[..std::cmp::min(self.0.len(), n)].into())
321 pub fn as_single(&self) -> &Ty {
322 if self.0.len() != 1 {
323 panic!("expected substs of len 1, got {:?}", self);
328 /// Return Substs that replace each parameter by itself (i.e. `Ty::Param`).
329 pub fn identity(generic_params: &GenericParams) -> Substs {
332 .params_including_parent()
334 .map(|p| Ty::Param { idx: p.idx, name: p.name.clone() })
339 /// Return Substs that replace each parameter by a bound variable.
340 pub fn bound_vars(generic_params: &GenericParams) -> Substs {
343 .params_including_parent()
345 .map(|p| Ty::Bound(p.idx))
350 pub fn build_for_def(db: &impl HirDatabase, def: impl HasGenericParams) -> SubstsBuilder {
351 let params = def.generic_params(db);
352 let param_count = params.count_params_including_parent();
353 Substs::builder(param_count)
356 pub fn build_for_generics(generic_params: &GenericParams) -> SubstsBuilder {
357 Substs::builder(generic_params.count_params_including_parent())
360 pub fn build_for_type_ctor(db: &impl HirDatabase, type_ctor: TypeCtor) -> SubstsBuilder {
361 Substs::builder(type_ctor.num_ty_params(db))
364 fn builder(param_count: usize) -> SubstsBuilder {
365 SubstsBuilder { vec: Vec::with_capacity(param_count), param_count }
369 #[derive(Debug, Clone)]
370 pub struct SubstsBuilder {
376 pub fn build(self) -> Substs {
377 assert_eq!(self.vec.len(), self.param_count);
378 Substs(self.vec.into())
381 pub fn push(mut self, ty: Ty) -> Self {
386 fn remaining(&self) -> usize {
387 self.param_count - self.vec.len()
390 pub fn fill_with_bound_vars(self, starting_from: u32) -> Self {
391 self.fill((starting_from..).map(Ty::Bound))
394 pub fn fill_with_params(self) -> Self {
395 let start = self.vec.len() as u32;
396 self.fill((start..).map(|idx| Ty::Param { idx, name: Name::missing() }))
399 pub fn fill_with_unknown(self) -> Self {
400 self.fill(iter::repeat(Ty::Unknown))
403 pub fn fill(mut self, filler: impl Iterator<Item = Ty>) -> Self {
404 self.vec.extend(filler.take(self.remaining()));
405 assert_eq!(self.remaining(), 0);
409 pub fn use_parent_substs(mut self, parent_substs: &Substs) -> Self {
410 assert!(self.vec.is_empty());
411 assert!(parent_substs.len() <= self.param_count);
412 self.vec.extend(parent_substs.iter().cloned());
417 impl Deref for Substs {
420 fn deref(&self) -> &[Ty] {
425 /// A trait with type parameters. This includes the `Self`, so this represents a concrete type implementing the trait.
426 /// Name to be bikeshedded: TraitBound? TraitImplements?
427 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
428 pub struct TraitRef {
435 pub fn self_ty(&self) -> &Ty {
440 impl TypeWalk for TraitRef {
441 fn walk(&self, f: &mut impl FnMut(&Ty)) {
445 fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) {
446 self.substs.walk_mut_binders(f, binders);
450 /// Like `generics::WherePredicate`, but with resolved types: A condition on the
451 /// parameters of a generic item.
452 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
453 pub enum GenericPredicate {
454 /// The given trait needs to be implemented for its type parameters.
455 Implemented(TraitRef),
456 /// An associated type bindings like in `Iterator<Item = T>`.
457 Projection(ProjectionPredicate),
458 /// We couldn't resolve the trait reference. (If some type parameters can't
459 /// be resolved, they will just be Unknown).
463 impl GenericPredicate {
464 pub fn is_error(&self) -> bool {
466 GenericPredicate::Error => true,
471 pub fn is_implemented(&self) -> bool {
473 GenericPredicate::Implemented(_) => true,
478 pub fn trait_ref(&self, db: &impl HirDatabase) -> Option<TraitRef> {
480 GenericPredicate::Implemented(tr) => Some(tr.clone()),
481 GenericPredicate::Projection(proj) => Some(proj.projection_ty.trait_ref(db)),
482 GenericPredicate::Error => None,
487 impl TypeWalk for GenericPredicate {
488 fn walk(&self, f: &mut impl FnMut(&Ty)) {
490 GenericPredicate::Implemented(trait_ref) => trait_ref.walk(f),
491 GenericPredicate::Projection(projection_pred) => projection_pred.walk(f),
492 GenericPredicate::Error => {}
496 fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) {
498 GenericPredicate::Implemented(trait_ref) => trait_ref.walk_mut_binders(f, binders),
499 GenericPredicate::Projection(projection_pred) => {
500 projection_pred.walk_mut_binders(f, binders)
502 GenericPredicate::Error => {}
507 /// Basically a claim (currently not validated / checked) that the contained
508 /// type / trait ref contains no inference variables; any inference variables it
509 /// contained have been replaced by bound variables, and `num_vars` tells us how
510 /// many there are. This is used to erase irrelevant differences between types
511 /// before using them in queries.
512 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
513 pub struct Canonical<T> {
518 /// A function signature as seen by type inference: Several parameter types and
520 #[derive(Clone, PartialEq, Eq, Debug)]
522 params_and_return: Arc<[Ty]>,
526 pub fn from_params_and_return(mut params: Vec<Ty>, ret: Ty) -> FnSig {
528 FnSig { params_and_return: params.into() }
531 pub fn from_fn_ptr_substs(substs: &Substs) -> FnSig {
532 FnSig { params_and_return: Arc::clone(&substs.0) }
535 pub fn params(&self) -> &[Ty] {
536 &self.params_and_return[0..self.params_and_return.len() - 1]
539 pub fn ret(&self) -> &Ty {
540 &self.params_and_return[self.params_and_return.len() - 1]
544 impl TypeWalk for FnSig {
545 fn walk(&self, f: &mut impl FnMut(&Ty)) {
546 for t in self.params_and_return.iter() {
551 fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) {
552 for t in make_mut_slice(&mut self.params_and_return) {
553 t.walk_mut_binders(f, binders);
559 pub fn simple(ctor: TypeCtor) -> Ty {
560 Ty::Apply(ApplicationTy { ctor, parameters: Substs::empty() })
562 pub fn apply_one(ctor: TypeCtor, param: Ty) -> Ty {
563 Ty::Apply(ApplicationTy { ctor, parameters: Substs::single(param) })
565 pub fn apply(ctor: TypeCtor, parameters: Substs) -> Ty {
566 Ty::Apply(ApplicationTy { ctor, parameters })
568 pub fn unit() -> Self {
569 Ty::apply(TypeCtor::Tuple { cardinality: 0 }, Substs::empty())
572 pub fn as_reference(&self) -> Option<(&Ty, Mutability)> {
574 Ty::Apply(ApplicationTy { ctor: TypeCtor::Ref(mutability), parameters }) => {
575 Some((parameters.as_single(), *mutability))
581 pub fn as_adt(&self) -> Option<(Adt, &Substs)> {
583 Ty::Apply(ApplicationTy { ctor: TypeCtor::Adt(adt_def), parameters }) => {
584 Some((*adt_def, parameters))
590 pub fn as_tuple(&self) -> Option<&Substs> {
592 Ty::Apply(ApplicationTy { ctor: TypeCtor::Tuple { .. }, parameters }) => {
599 pub fn as_callable(&self) -> Option<(CallableDef, &Substs)> {
601 Ty::Apply(ApplicationTy { ctor: TypeCtor::FnDef(callable_def), parameters }) => {
602 Some((*callable_def, parameters))
608 fn builtin_deref(&self) -> Option<Ty> {
610 Ty::Apply(a_ty) => match a_ty.ctor {
611 TypeCtor::Ref(..) => Some(Ty::clone(a_ty.parameters.as_single())),
612 TypeCtor::RawPtr(..) => Some(Ty::clone(a_ty.parameters.as_single())),
619 fn callable_sig(&self, db: &impl HirDatabase) -> Option<FnSig> {
621 Ty::Apply(a_ty) => match a_ty.ctor {
622 TypeCtor::FnPtr { .. } => Some(FnSig::from_fn_ptr_substs(&a_ty.parameters)),
623 TypeCtor::FnDef(def) => {
624 let sig = db.callable_item_signature(def);
625 Some(sig.subst(&a_ty.parameters))
627 TypeCtor::Closure { .. } => {
628 let sig_param = &a_ty.parameters[0];
629 sig_param.callable_sig(db)
637 /// If this is a type with type parameters (an ADT or function), replaces
638 /// the `Substs` for these type parameters with the given ones. (So e.g. if
639 /// `self` is `Option<_>` and the substs contain `u32`, we'll have
640 /// `Option<u32>` afterwards.)
641 pub fn apply_substs(self, substs: Substs) -> Ty {
643 Ty::Apply(ApplicationTy { ctor, parameters: previous_substs }) => {
644 assert_eq!(previous_substs.len(), substs.len());
645 Ty::Apply(ApplicationTy { ctor, parameters: substs })
651 /// Returns the type parameters of this type if it has some (i.e. is an ADT
652 /// or function); so if `self` is `Option<u32>`, this returns the `u32`.
653 pub fn substs(&self) -> Option<Substs> {
655 Ty::Apply(ApplicationTy { parameters, .. }) => Some(parameters.clone()),
660 /// If this is an `impl Trait` or `dyn Trait`, returns that trait.
661 pub fn inherent_trait(&self) -> Option<Trait> {
663 Ty::Dyn(predicates) | Ty::Opaque(predicates) => {
664 predicates.iter().find_map(|pred| match pred {
665 GenericPredicate::Implemented(tr) => Some(tr.trait_),
674 /// This allows walking structures that contain types to do something with those
675 /// types, similar to Chalk's `Fold` trait.
677 fn walk(&self, f: &mut impl FnMut(&Ty));
678 fn walk_mut(&mut self, f: &mut impl FnMut(&mut Ty)) {
679 self.walk_mut_binders(&mut |ty, _binders| f(ty), 0);
681 /// Walk the type, counting entered binders.
683 /// `Ty::Bound` variables use DeBruijn indexing, which means that 0 refers
684 /// to the innermost binder, 1 to the next, etc.. So when we want to
685 /// substitute a certain bound variable, we can't just walk the whole type
686 /// and blindly replace each instance of a certain index; when we 'enter'
687 /// things that introduce new bound variables, we have to keep track of
688 /// that. Currently, the only thing that introduces bound variables on our
689 /// side are `Ty::Dyn` and `Ty::Opaque`, which each introduce a bound
690 /// variable for the self type.
691 fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize);
693 fn fold(mut self, f: &mut impl FnMut(Ty) -> Ty) -> Self
697 self.walk_mut(&mut |ty_mut| {
698 let ty = mem::replace(ty_mut, Ty::Unknown);
704 /// Replaces type parameters in this type using the given `Substs`. (So e.g.
705 /// if `self` is `&[T]`, where type parameter T has index 0, and the
706 /// `Substs` contain `u32` at index 0, we'll have `&[u32]` afterwards.)
707 fn subst(self, substs: &Substs) -> Self
711 self.fold(&mut |ty| match ty {
712 Ty::Param { idx, name } => {
713 substs.get(idx as usize).cloned().unwrap_or(Ty::Param { idx, name })
719 /// Substitutes `Ty::Bound` vars (as opposed to type parameters).
720 fn subst_bound_vars(mut self, substs: &Substs) -> Self
724 self.walk_mut_binders(
725 &mut |ty, binders| match ty {
726 &mut Ty::Bound(idx) => {
727 if idx as usize >= binders && (idx as usize - binders) < substs.len() {
728 *ty = substs.0[idx as usize - binders].clone();
738 /// Shifts up `Ty::Bound` vars by `n`.
739 fn shift_bound_vars(self, n: i32) -> Self
743 self.fold(&mut |ty| match ty {
745 assert!(idx as i32 >= -n);
746 Ty::Bound((idx as i32 + n) as u32)
753 impl TypeWalk for Ty {
754 fn walk(&self, f: &mut impl FnMut(&Ty)) {
757 for t in a_ty.parameters.iter() {
761 Ty::Projection(p_ty) => {
762 for t in p_ty.parameters.iter() {
766 Ty::Dyn(predicates) | Ty::Opaque(predicates) => {
767 for p in predicates.iter() {
771 Ty::Param { .. } | Ty::Bound(_) | Ty::Infer(_) | Ty::Unknown => {}
776 fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) {
779 a_ty.parameters.walk_mut_binders(f, binders);
781 Ty::Projection(p_ty) => {
782 p_ty.parameters.walk_mut_binders(f, binders);
784 Ty::Dyn(predicates) | Ty::Opaque(predicates) => {
785 for p in make_mut_slice(predicates) {
786 p.walk_mut_binders(f, binders + 1);
789 Ty::Param { .. } | Ty::Bound(_) | Ty::Infer(_) | Ty::Unknown => {}
795 impl HirDisplay for &Ty {
796 fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result {
797 HirDisplay::hir_fmt(*self, f)
801 impl HirDisplay for ApplicationTy {
802 fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result {
803 if f.should_truncate() {
804 return write!(f, "…");
808 TypeCtor::Bool => write!(f, "bool")?,
809 TypeCtor::Char => write!(f, "char")?,
810 TypeCtor::Int(t) => write!(f, "{}", t)?,
811 TypeCtor::Float(t) => write!(f, "{}", t)?,
812 TypeCtor::Str => write!(f, "str")?,
814 let t = self.parameters.as_single();
815 write!(f, "[{}]", t.display(f.db))?;
818 let t = self.parameters.as_single();
819 write!(f, "[{};_]", t.display(f.db))?;
821 TypeCtor::RawPtr(m) => {
822 let t = self.parameters.as_single();
823 write!(f, "*{}{}", m.as_keyword_for_ptr(), t.display(f.db))?;
825 TypeCtor::Ref(m) => {
826 let t = self.parameters.as_single();
827 write!(f, "&{}{}", m.as_keyword_for_ref(), t.display(f.db))?;
829 TypeCtor::Never => write!(f, "!")?,
830 TypeCtor::Tuple { .. } => {
831 let ts = &self.parameters;
833 write!(f, "({},)", ts[0].display(f.db))?;
836 f.write_joined(&*ts.0, ", ")?;
840 TypeCtor::FnPtr { .. } => {
841 let sig = FnSig::from_fn_ptr_substs(&self.parameters);
843 f.write_joined(sig.params(), ", ")?;
844 write!(f, ") -> {}", sig.ret().display(f.db))?;
846 TypeCtor::FnDef(def) => {
847 let sig = f.db.callable_item_signature(def);
848 let name = match def {
849 CallableDef::Function(ff) => ff.name(f.db),
850 CallableDef::Struct(s) => s.name(f.db).unwrap_or_else(Name::missing),
851 CallableDef::EnumVariant(e) => e.name(f.db).unwrap_or_else(Name::missing),
854 CallableDef::Function(_) => write!(f, "fn {}", name)?,
855 CallableDef::Struct(_) | CallableDef::EnumVariant(_) => write!(f, "{}", name)?,
857 if self.parameters.len() > 0 {
859 f.write_joined(&*self.parameters.0, ", ")?;
863 f.write_joined(sig.params(), ", ")?;
864 write!(f, ") -> {}", sig.ret().display(f.db))?;
866 TypeCtor::Adt(def_id) => {
867 let name = match def_id {
868 Adt::Struct(s) => s.name(f.db),
869 Adt::Union(u) => u.name(f.db),
870 Adt::Enum(e) => e.name(f.db),
872 .unwrap_or_else(Name::missing);
873 write!(f, "{}", name)?;
874 if self.parameters.len() > 0 {
876 f.write_joined(&*self.parameters.0, ", ")?;
880 TypeCtor::AssociatedType(type_alias) => {
881 let trait_name = type_alias
883 .and_then(|t| t.name(f.db))
884 .unwrap_or_else(Name::missing);
885 let name = type_alias.name(f.db);
886 write!(f, "{}::{}", trait_name, name)?;
887 if self.parameters.len() > 0 {
889 f.write_joined(&*self.parameters.0, ", ")?;
893 TypeCtor::Closure { .. } => {
894 let sig = self.parameters[0]
896 .expect("first closure parameter should contain signature");
898 f.write_joined(sig.params(), ", ")?;
899 write!(f, "| -> {}", sig.ret().display(f.db))?;
906 impl HirDisplay for ProjectionTy {
907 fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result {
908 if f.should_truncate() {
909 return write!(f, "…");
912 let trait_name = self
915 .and_then(|t| t.name(f.db))
916 .unwrap_or_else(Name::missing);
917 write!(f, "<{} as {}", self.parameters[0].display(f.db), trait_name,)?;
918 if self.parameters.len() > 1 {
920 f.write_joined(&self.parameters[1..], ", ")?;
923 write!(f, ">::{}", self.associated_ty.name(f.db))?;
928 impl HirDisplay for Ty {
929 fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result {
930 if f.should_truncate() {
931 return write!(f, "…");
935 Ty::Apply(a_ty) => a_ty.hir_fmt(f)?,
936 Ty::Projection(p_ty) => p_ty.hir_fmt(f)?,
937 Ty::Param { name, .. } => write!(f, "{}", name)?,
938 Ty::Bound(idx) => write!(f, "?{}", idx)?,
939 Ty::Dyn(predicates) | Ty::Opaque(predicates) => {
941 Ty::Dyn(_) => write!(f, "dyn ")?,
942 Ty::Opaque(_) => write!(f, "impl ")?,
945 // Note: This code is written to produce nice results (i.e.
946 // corresponding to surface Rust) for types that can occur in
947 // actual Rust. It will have weird results if the predicates
948 // aren't as expected (i.e. self types = $0, projection
949 // predicates for a certain trait come after the Implemented
950 // predicate for that trait).
951 let mut first = true;
952 let mut angle_open = false;
953 for p in predicates.iter() {
955 GenericPredicate::Implemented(trait_ref) => {
962 // We assume that the self type is $0 (i.e. the
963 // existential) here, which is the only thing that's
964 // possible in actual Rust, and hence don't print it
968 trait_ref.trait_.name(f.db).unwrap_or_else(Name::missing)
970 if trait_ref.substs.len() > 1 {
972 f.write_joined(&trait_ref.substs[1..], ", ")?;
973 // there might be assoc type bindings, so we leave the angle brackets open
977 GenericPredicate::Projection(projection_pred) => {
978 // in types in actual Rust, these will always come
979 // after the corresponding Implemented predicate
986 let name = projection_pred.projection_ty.associated_ty.name(f.db);
987 write!(f, "{} = ", name)?;
988 projection_pred.ty.hir_fmt(f)?;
990 GenericPredicate::Error => {
992 // impl Trait<X, {error}>
995 // impl Trait + {error}
1007 Ty::Unknown => write!(f, "{{unknown}}")?,
1008 Ty::Infer(..) => write!(f, "_")?,
1015 fn hir_fmt_ext(&self, f: &mut HirFormatter<impl HirDatabase>, use_as: bool) -> fmt::Result {
1016 if f.should_truncate() {
1017 return write!(f, "…");
1020 self.substs[0].hir_fmt(f)?;
1026 write!(f, "{}", self.trait_.name(f.db).unwrap_or_else(Name::missing))?;
1027 if self.substs.len() > 1 {
1029 f.write_joined(&self.substs[1..], ", ")?;
1036 impl HirDisplay for TraitRef {
1037 fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result {
1038 self.hir_fmt_ext(f, false)
1042 impl HirDisplay for &GenericPredicate {
1043 fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result {
1044 HirDisplay::hir_fmt(*self, f)
1048 impl HirDisplay for GenericPredicate {
1049 fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result {
1050 if f.should_truncate() {
1051 return write!(f, "…");
1055 GenericPredicate::Implemented(trait_ref) => trait_ref.hir_fmt(f)?,
1056 GenericPredicate::Projection(projection_pred) => {
1058 projection_pred.projection_ty.trait_ref(f.db).hir_fmt_ext(f, true)?;
1062 projection_pred.projection_ty.associated_ty.name(f.db),
1063 projection_pred.ty.display(f.db)
1066 GenericPredicate::Error => write!(f, "{{error}}")?,
1072 impl HirDisplay for Obligation {
1073 fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result {
1075 Obligation::Trait(tr) => write!(f, "Implements({})", tr.display(f.db)),
1076 Obligation::Projection(proj) => write!(
1078 "Normalize({} => {})",
1079 proj.projection_ty.display(f.db),
1080 proj.ty.display(f.db)