1 use crate::def::{CtorKind, DefKind, Res};
2 use crate::def_id::DefId;
3 pub(crate) use crate::hir_id::{HirId, ItemLocalId, OwnerId};
4 use crate::intravisit::FnKind;
8 use rustc_ast::util::parser::ExprPrecedence;
9 use rustc_ast::{Attribute, FloatTy, IntTy, Label, LitKind, TraitObjectSyntax, UintTy};
10 pub use rustc_ast::{BindingAnnotation, BorrowKind, ByRef, ImplPolarity, IsAuto};
11 pub use rustc_ast::{CaptureBy, Movability, Mutability};
12 use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
13 use rustc_data_structures::fingerprint::Fingerprint;
14 use rustc_data_structures::fx::FxHashMap;
15 use rustc_data_structures::sorted_map::SortedMap;
16 use rustc_error_messages::MultiSpan;
17 use rustc_index::vec::IndexVec;
18 use rustc_macros::HashStable_Generic;
19 use rustc_span::hygiene::MacroKind;
20 use rustc_span::source_map::Spanned;
21 use rustc_span::symbol::{kw, sym, Ident, Symbol};
22 use rustc_span::{def_id::LocalDefId, BytePos, Span, DUMMY_SP};
23 use rustc_target::asm::InlineAsmRegOrRegClass;
24 use rustc_target::spec::abi::Abi;
26 use smallvec::SmallVec;
29 #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)]
33 /// Either "`'a`", referring to a named lifetime definition,
34 /// `'_` referring to an anonymous lifetime (either explicitly `'_` or `&type`),
35 /// or "``" (i.e., `kw::Empty`) when appearing in path.
37 /// See `Lifetime::suggestion_position` for practical use.
40 /// Semantics of this lifetime.
41 pub res: LifetimeName,
44 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
45 #[derive(HashStable_Generic)]
47 /// Some user-given name like `T` or `'x`.
50 /// Synthetic name generated when user elided a lifetime in an impl header.
52 /// E.g., the lifetimes in cases like these:
53 /// ```ignore (fragment)
55 /// impl Foo<'_> for u32
57 /// in that case, we rewrite to
58 /// ```ignore (fragment)
59 /// impl<'f> Foo for &'f u32
60 /// impl<'f> Foo<'f> for u32
62 /// where `'f` is something like `Fresh(0)`. The indices are
63 /// unique per impl, but not necessarily continuous.
66 /// Indicates an illegal name was given and an error has been
67 /// reported (so we should squelch other derived errors). Occurs
68 /// when, e.g., `'_` is used in the wrong place.
73 pub fn ident(&self) -> Ident {
75 ParamName::Plain(ident) => ident,
76 ParamName::Fresh | ParamName::Error => Ident::with_dummy_span(kw::UnderscoreLifetime),
80 pub fn normalize_to_macros_2_0(&self) -> ParamName {
82 ParamName::Plain(ident) => ParamName::Plain(ident.normalize_to_macros_2_0()),
83 param_name => param_name,
88 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
89 #[derive(HashStable_Generic)]
90 pub enum LifetimeName {
91 /// User-given names or fresh (synthetic) names.
94 /// Implicit lifetime in a context like `dyn Foo`. This is
95 /// distinguished from implicit lifetimes elsewhere because the
96 /// lifetime that they default to must appear elsewhere within the
97 /// enclosing type. This means that, in an `impl Trait` context, we
98 /// don't have to create a parameter for them. That is, `impl
99 /// Trait<Item = &u32>` expands to an opaque type like `type
100 /// Foo<'a> = impl Trait<Item = &'a u32>`, but `impl Trait<item =
101 /// dyn Bar>` expands to `type Foo = impl Trait<Item = dyn Bar +
102 /// 'static>`. The latter uses `ImplicitObjectLifetimeDefault` so
103 /// that surrounding code knows not to create a lifetime
105 ImplicitObjectLifetimeDefault,
107 /// Indicates an error during lowering (usually `'_` in wrong place)
108 /// that was already reported.
111 /// User wrote an anonymous lifetime, either `'_` or nothing.
112 /// The semantics of this lifetime should be inferred by typechecking code.
115 /// User wrote `'static`.
120 pub fn is_elided(&self) -> bool {
122 LifetimeName::ImplicitObjectLifetimeDefault | LifetimeName::Infer => true,
124 // It might seem surprising that `Fresh` counts as not *elided*
125 // -- but this is because, as far as the code in the compiler is
126 // concerned -- `Fresh` variants act equivalently to "some fresh name".
127 // They correspond to early-bound regions on an impl, in other words.
128 LifetimeName::Error | LifetimeName::Param(..) | LifetimeName::Static => false,
133 impl fmt::Display for Lifetime {
134 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
135 if self.ident.name != kw::Empty { self.ident.name.fmt(f) } else { "'_".fmt(f) }
139 pub enum LifetimeSuggestionPosition {
140 /// The user wrote `'a` or `'_`.
142 /// The user wrote `&type` or `&mut type`.
144 /// The user wrote `Path` and omitted the `<'_>`.
146 /// The user wrote `Path<T>`, and omitted the `'_,`.
148 /// The user wrote `dyn Trait` and omitted the `+ '_`.
153 pub fn is_elided(&self) -> bool {
157 pub fn is_anonymous(&self) -> bool {
158 self.ident.name == kw::Empty || self.ident.name == kw::UnderscoreLifetime
161 pub fn suggestion_position(&self) -> (LifetimeSuggestionPosition, Span) {
162 if self.ident.name == kw::Empty {
163 if self.ident.span.is_empty() {
164 (LifetimeSuggestionPosition::ElidedPathArgument, self.ident.span)
166 (LifetimeSuggestionPosition::ElidedPath, self.ident.span.shrink_to_hi())
168 } else if self.res == LifetimeName::ImplicitObjectLifetimeDefault {
169 (LifetimeSuggestionPosition::ObjectDefault, self.ident.span)
170 } else if self.ident.span.is_empty() {
171 (LifetimeSuggestionPosition::Ampersand, self.ident.span)
173 (LifetimeSuggestionPosition::Normal, self.ident.span)
177 pub fn is_static(&self) -> bool {
178 self.res == LifetimeName::Static
182 /// A `Path` is essentially Rust's notion of a name; for instance,
183 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
184 /// along with a bunch of supporting information.
185 #[derive(Debug, HashStable_Generic)]
186 pub struct Path<'hir, R = Res> {
188 /// The resolution for the path.
190 /// The segments in the path: the things separated by `::`.
191 pub segments: &'hir [PathSegment<'hir>],
194 /// Up to three resolutions for type, value and macro namespaces.
195 pub type UsePath<'hir> = Path<'hir, SmallVec<[Res; 3]>>;
198 pub fn is_global(&self) -> bool {
199 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
203 /// A segment of a path: an identifier, an optional lifetime, and a set of
205 #[derive(Debug, HashStable_Generic)]
206 pub struct PathSegment<'hir> {
207 /// The identifier portion of this path segment.
212 /// Type/lifetime parameters attached to this path. They come in
213 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
214 /// this is more than just simple syntactic sugar; the use of
215 /// parens affects the region binding rules, so we preserve the
217 pub args: Option<&'hir GenericArgs<'hir>>,
219 /// Whether to infer remaining type parameters, if any.
220 /// This only applies to expression and pattern paths, and
221 /// out of those only the segments with no type parameters
222 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
223 pub infer_args: bool,
226 impl<'hir> PathSegment<'hir> {
227 /// Converts an identifier to the corresponding segment.
228 pub fn new(ident: Ident, hir_id: HirId, res: Res) -> PathSegment<'hir> {
229 PathSegment { ident, hir_id, res, infer_args: true, args: None }
232 pub fn invalid() -> Self {
233 Self::new(Ident::empty(), HirId::INVALID, Res::Err)
236 pub fn args(&self) -> &GenericArgs<'hir> {
237 if let Some(ref args) = self.args {
240 const DUMMY: &GenericArgs<'_> = &GenericArgs::none();
246 #[derive(Encodable, Debug, HashStable_Generic)]
247 pub struct ConstArg {
248 pub value: AnonConst,
252 #[derive(Encodable, Debug, HashStable_Generic)]
253 pub struct InferArg {
259 pub fn to_ty(&self) -> Ty<'_> {
260 Ty { kind: TyKind::Infer, span: self.span, hir_id: self.hir_id }
264 #[derive(Debug, HashStable_Generic)]
265 pub enum GenericArg<'hir> {
266 Lifetime(&'hir Lifetime),
267 Type(&'hir Ty<'hir>),
272 impl GenericArg<'_> {
273 pub fn span(&self) -> Span {
275 GenericArg::Lifetime(l) => l.ident.span,
276 GenericArg::Type(t) => t.span,
277 GenericArg::Const(c) => c.span,
278 GenericArg::Infer(i) => i.span,
282 pub fn hir_id(&self) -> HirId {
284 GenericArg::Lifetime(l) => l.hir_id,
285 GenericArg::Type(t) => t.hir_id,
286 GenericArg::Const(c) => c.value.hir_id,
287 GenericArg::Infer(i) => i.hir_id,
291 pub fn is_synthetic(&self) -> bool {
292 matches!(self, GenericArg::Lifetime(lifetime) if lifetime.ident == Ident::empty())
295 pub fn descr(&self) -> &'static str {
297 GenericArg::Lifetime(_) => "lifetime",
298 GenericArg::Type(_) => "type",
299 GenericArg::Const(_) => "constant",
300 GenericArg::Infer(_) => "inferred",
304 pub fn to_ord(&self) -> ast::ParamKindOrd {
306 GenericArg::Lifetime(_) => ast::ParamKindOrd::Lifetime,
307 GenericArg::Type(_) | GenericArg::Const(_) | GenericArg::Infer(_) => {
308 ast::ParamKindOrd::TypeOrConst
313 pub fn is_ty_or_const(&self) -> bool {
315 GenericArg::Lifetime(_) => false,
316 GenericArg::Type(_) | GenericArg::Const(_) | GenericArg::Infer(_) => true,
321 #[derive(Debug, HashStable_Generic)]
322 pub struct GenericArgs<'hir> {
323 /// The generic arguments for this path segment.
324 pub args: &'hir [GenericArg<'hir>],
325 /// Bindings (equality constraints) on associated types, if present.
326 /// E.g., `Foo<A = Bar>`.
327 pub bindings: &'hir [TypeBinding<'hir>],
328 /// Were arguments written in parenthesized form `Fn(T) -> U`?
329 /// This is required mostly for pretty-printing and diagnostics,
330 /// but also for changing lifetime elision rules to be "function-like".
331 pub parenthesized: bool,
332 /// The span encompassing arguments and the surrounding brackets `<>` or `()`
333 /// Foo<A, B, AssocTy = D> Fn(T, U, V) -> W
334 /// ^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^
335 /// Note that this may be:
336 /// - empty, if there are no generic brackets (but there may be hidden lifetimes)
337 /// - dummy, if this was generated while desugaring
341 impl<'hir> GenericArgs<'hir> {
342 pub const fn none() -> Self {
343 Self { args: &[], bindings: &[], parenthesized: false, span_ext: DUMMY_SP }
346 pub fn inputs(&self) -> &[Ty<'hir>] {
347 if self.parenthesized {
348 for arg in self.args {
350 GenericArg::Lifetime(_) => {}
351 GenericArg::Type(ref ty) => {
352 if let TyKind::Tup(ref tys) = ty.kind {
357 GenericArg::Const(_) => {}
358 GenericArg::Infer(_) => {}
362 panic!("GenericArgs::inputs: not a `Fn(T) -> U`");
366 pub fn has_type_params(&self) -> bool {
367 self.args.iter().any(|arg| matches!(arg, GenericArg::Type(_)))
370 pub fn has_err(&self) -> bool {
371 self.args.iter().any(|arg| match arg {
372 GenericArg::Type(ty) => matches!(ty.kind, TyKind::Err),
374 }) || self.bindings.iter().any(|arg| match arg.kind {
375 TypeBindingKind::Equality { term: Term::Ty(ty) } => matches!(ty.kind, TyKind::Err),
381 pub fn num_type_params(&self) -> usize {
382 self.args.iter().filter(|arg| matches!(arg, GenericArg::Type(_))).count()
386 pub fn num_lifetime_params(&self) -> usize {
387 self.args.iter().filter(|arg| matches!(arg, GenericArg::Lifetime(_))).count()
391 pub fn has_lifetime_params(&self) -> bool {
392 self.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)))
396 /// This function returns the number of type and const generic params.
397 /// It should only be used for diagnostics.
398 pub fn num_generic_params(&self) -> usize {
399 self.args.iter().filter(|arg| !matches!(arg, GenericArg::Lifetime(_))).count()
402 /// The span encompassing the text inside the surrounding brackets.
403 /// It will also include bindings if they aren't in the form `-> Ret`
404 /// Returns `None` if the span is empty (e.g. no brackets) or dummy
405 pub fn span(&self) -> Option<Span> {
406 let span_ext = self.span_ext()?;
407 Some(span_ext.with_lo(span_ext.lo() + BytePos(1)).with_hi(span_ext.hi() - BytePos(1)))
410 /// Returns span encompassing arguments and their surrounding `<>` or `()`
411 pub fn span_ext(&self) -> Option<Span> {
412 Some(self.span_ext).filter(|span| !span.is_empty())
415 pub fn is_empty(&self) -> bool {
420 /// A modifier on a bound, currently this is only used for `?Sized`, where the
421 /// modifier is `Maybe`. Negative bounds should also be handled here.
422 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
423 #[derive(HashStable_Generic)]
424 pub enum TraitBoundModifier {
430 /// The AST represents all type param bounds as types.
431 /// `typeck::collect::compute_bounds` matches these against
432 /// the "special" built-in traits (see `middle::lang_items`) and
433 /// detects `Copy`, `Send` and `Sync`.
434 #[derive(Clone, Debug, HashStable_Generic)]
435 pub enum GenericBound<'hir> {
436 Trait(PolyTraitRef<'hir>, TraitBoundModifier),
437 // FIXME(davidtwco): Introduce `PolyTraitRef::LangItem`
438 LangItemTrait(LangItem, Span, HirId, &'hir GenericArgs<'hir>),
439 Outlives(&'hir Lifetime),
442 impl GenericBound<'_> {
443 pub fn trait_ref(&self) -> Option<&TraitRef<'_>> {
445 GenericBound::Trait(data, _) => Some(&data.trait_ref),
450 pub fn span(&self) -> Span {
452 GenericBound::Trait(t, ..) => t.span,
453 GenericBound::LangItemTrait(_, span, ..) => *span,
454 GenericBound::Outlives(l) => l.ident.span,
459 pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
461 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
462 pub enum LifetimeParamKind {
463 // Indicates that the lifetime definition was explicitly declared (e.g., in
464 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
467 // Indication that the lifetime was elided (e.g., in both cases in
468 // `fn foo(x: &u8) -> &'_ u8 { x }`).
471 // Indication that the lifetime name was somehow in error.
475 #[derive(Debug, HashStable_Generic)]
476 pub enum GenericParamKind<'hir> {
477 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
479 kind: LifetimeParamKind,
482 default: Option<&'hir Ty<'hir>>,
487 /// Optional default value for the const generic param
488 default: Option<AnonConst>,
492 #[derive(Debug, HashStable_Generic)]
493 pub struct GenericParam<'hir> {
495 pub def_id: LocalDefId,
498 pub pure_wrt_drop: bool,
499 pub kind: GenericParamKind<'hir>,
500 pub colon_span: Option<Span>,
503 impl<'hir> GenericParam<'hir> {
504 /// Synthetic type-parameters are inserted after normal ones.
505 /// In order for normal parameters to be able to refer to synthetic ones,
506 /// scans them first.
507 pub fn is_impl_trait(&self) -> bool {
508 matches!(self.kind, GenericParamKind::Type { synthetic: true, .. })
511 /// This can happen for `async fn`, e.g. `async fn f<'_>(&'_ self)`.
513 /// See `lifetime_to_generic_param` in `rustc_ast_lowering` for more information.
514 pub fn is_elided_lifetime(&self) -> bool {
515 matches!(self.kind, GenericParamKind::Lifetime { kind: LifetimeParamKind::Elided })
520 pub struct GenericParamCount {
521 pub lifetimes: usize,
527 /// Represents lifetimes and type parameters attached to a declaration
528 /// of a function, enum, trait, etc.
529 #[derive(Debug, HashStable_Generic)]
530 pub struct Generics<'hir> {
531 pub params: &'hir [GenericParam<'hir>],
532 pub predicates: &'hir [WherePredicate<'hir>],
533 pub has_where_clause_predicates: bool,
534 pub where_clause_span: Span,
538 impl<'hir> Generics<'hir> {
539 pub const fn empty() -> &'hir Generics<'hir> {
540 const NOPE: Generics<'_> = Generics {
543 has_where_clause_predicates: false,
544 where_clause_span: DUMMY_SP,
550 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'hir>> {
551 self.params.iter().find(|¶m| name == param.name.ident().name)
554 pub fn spans(&self) -> MultiSpan {
555 if self.params.is_empty() {
558 self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
562 /// If there are generic parameters, return where to introduce a new one.
563 pub fn span_for_lifetime_suggestion(&self) -> Option<Span> {
564 if let Some(first) = self.params.first()
565 && self.span.contains(first.span)
567 // `fn foo<A>(t: impl Trait)`
568 // ^ suggest `'a, ` here
569 Some(first.span.shrink_to_lo())
575 /// If there are generic parameters, return where to introduce a new one.
576 pub fn span_for_param_suggestion(&self) -> Option<Span> {
577 if self.params.iter().any(|p| self.span.contains(p.span)) {
578 // `fn foo<A>(t: impl Trait)`
579 // ^ suggest `, T: Trait` here
580 let span = self.span.with_lo(self.span.hi() - BytePos(1)).shrink_to_lo();
587 /// `Span` where further predicates would be suggested, accounting for trailing commas, like
588 /// in `fn foo<T>(t: T) where T: Foo,` so we don't suggest two trailing commas.
589 pub fn tail_span_for_predicate_suggestion(&self) -> Span {
590 let end = self.where_clause_span.shrink_to_hi();
591 if self.has_where_clause_predicates {
594 .rfind(|&p| p.in_where_clause())
595 .map_or(end, |p| p.span())
603 pub fn add_where_or_trailing_comma(&self) -> &'static str {
604 if self.has_where_clause_predicates {
606 } else if self.where_clause_span.is_empty() {
609 // No where clause predicates, but we have `where` token
614 pub fn bounds_for_param(
616 param_def_id: LocalDefId,
617 ) -> impl Iterator<Item = &WhereBoundPredicate<'hir>> {
618 self.predicates.iter().filter_map(move |pred| match pred {
619 WherePredicate::BoundPredicate(bp) if bp.is_param_bound(param_def_id.to_def_id()) => {
626 pub fn outlives_for_param(
628 param_def_id: LocalDefId,
629 ) -> impl Iterator<Item = &WhereRegionPredicate<'_>> {
630 self.predicates.iter().filter_map(move |pred| match pred {
631 WherePredicate::RegionPredicate(rp) if rp.is_param_bound(param_def_id) => Some(rp),
636 pub fn bounds_span_for_suggestions(&self, param_def_id: LocalDefId) -> Option<Span> {
637 self.bounds_for_param(param_def_id).flat_map(|bp| bp.bounds.iter().rev()).find_map(
639 // We include bounds that come from a `#[derive(_)]` but point at the user's code,
640 // as we use this method to get a span appropriate for suggestions.
641 let bs = bound.span();
642 if bs.can_be_used_for_suggestions() { Some(bs.shrink_to_hi()) } else { None }
647 pub fn span_for_predicate_removal(&self, pos: usize) -> Span {
648 let predicate = &self.predicates[pos];
649 let span = predicate.span();
651 if !predicate.in_where_clause() {
657 // We need to find out which comma to remove.
658 if pos < self.predicates.len() - 1 {
659 let next_pred = &self.predicates[pos + 1];
660 if next_pred.in_where_clause() {
661 // where T: ?Sized, Foo: Bar,
663 return span.until(next_pred.span());
668 let prev_pred = &self.predicates[pos - 1];
669 if prev_pred.in_where_clause() {
670 // where Foo: Bar, T: ?Sized,
672 return prev_pred.span().shrink_to_hi().to(span);
676 // This is the only predicate in the where clause.
679 self.where_clause_span
682 pub fn span_for_bound_removal(&self, predicate_pos: usize, bound_pos: usize) -> Span {
683 let predicate = &self.predicates[predicate_pos];
684 let bounds = predicate.bounds();
686 if bounds.len() == 1 {
687 return self.span_for_predicate_removal(predicate_pos);
690 let span = bounds[bound_pos].span();
692 // where T: ?Sized + Bar, Foo: Bar,
694 span.to(bounds[1].span().shrink_to_lo())
696 // where T: Bar + ?Sized, Foo: Bar,
698 bounds[bound_pos - 1].span().shrink_to_hi().to(span)
703 /// A single predicate in a where-clause.
704 #[derive(Debug, HashStable_Generic)]
705 pub enum WherePredicate<'hir> {
706 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
707 BoundPredicate(WhereBoundPredicate<'hir>),
708 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
709 RegionPredicate(WhereRegionPredicate<'hir>),
710 /// An equality predicate (unsupported).
711 EqPredicate(WhereEqPredicate<'hir>),
714 impl<'hir> WherePredicate<'hir> {
715 pub fn span(&self) -> Span {
717 WherePredicate::BoundPredicate(p) => p.span,
718 WherePredicate::RegionPredicate(p) => p.span,
719 WherePredicate::EqPredicate(p) => p.span,
723 pub fn in_where_clause(&self) -> bool {
725 WherePredicate::BoundPredicate(p) => p.origin == PredicateOrigin::WhereClause,
726 WherePredicate::RegionPredicate(p) => p.in_where_clause,
727 WherePredicate::EqPredicate(_) => false,
731 pub fn bounds(&self) -> GenericBounds<'hir> {
733 WherePredicate::BoundPredicate(p) => p.bounds,
734 WherePredicate::RegionPredicate(p) => p.bounds,
735 WherePredicate::EqPredicate(_) => &[],
740 #[derive(Copy, Clone, Debug, HashStable_Generic, PartialEq, Eq)]
741 pub enum PredicateOrigin {
747 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
748 #[derive(Debug, HashStable_Generic)]
749 pub struct WhereBoundPredicate<'hir> {
752 /// Origin of the predicate.
753 pub origin: PredicateOrigin,
754 /// Any generics from a `for` binding.
755 pub bound_generic_params: &'hir [GenericParam<'hir>],
756 /// The type being bounded.
757 pub bounded_ty: &'hir Ty<'hir>,
758 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
759 pub bounds: GenericBounds<'hir>,
762 impl<'hir> WhereBoundPredicate<'hir> {
763 /// Returns `true` if `param_def_id` matches the `bounded_ty` of this predicate.
764 pub fn is_param_bound(&self, param_def_id: DefId) -> bool {
765 self.bounded_ty.as_generic_param().map_or(false, |(def_id, _)| def_id == param_def_id)
769 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
770 #[derive(Debug, HashStable_Generic)]
771 pub struct WhereRegionPredicate<'hir> {
773 pub in_where_clause: bool,
774 pub lifetime: &'hir Lifetime,
775 pub bounds: GenericBounds<'hir>,
778 impl<'hir> WhereRegionPredicate<'hir> {
779 /// Returns `true` if `param_def_id` matches the `lifetime` of this predicate.
780 pub fn is_param_bound(&self, param_def_id: LocalDefId) -> bool {
781 self.lifetime.res == LifetimeName::Param(param_def_id)
785 /// An equality predicate (e.g., `T = int`); currently unsupported.
786 #[derive(Debug, HashStable_Generic)]
787 pub struct WhereEqPredicate<'hir> {
789 pub lhs_ty: &'hir Ty<'hir>,
790 pub rhs_ty: &'hir Ty<'hir>,
793 /// HIR node coupled with its parent's id in the same HIR owner.
795 /// The parent is trash when the node is a HIR owner.
796 #[derive(Clone, Debug)]
797 pub struct ParentedNode<'tcx> {
798 pub parent: ItemLocalId,
799 pub node: Node<'tcx>,
802 /// Attributes owned by a HIR owner.
804 pub struct AttributeMap<'tcx> {
805 pub map: SortedMap<ItemLocalId, &'tcx [Attribute]>,
806 pub hash: Fingerprint,
809 impl<'tcx> AttributeMap<'tcx> {
810 pub const EMPTY: &'static AttributeMap<'static> =
811 &AttributeMap { map: SortedMap::new(), hash: Fingerprint::ZERO };
814 pub fn get(&self, id: ItemLocalId) -> &'tcx [Attribute] {
815 self.map.get(&id).copied().unwrap_or(&[])
819 /// Map of all HIR nodes inside the current owner.
820 /// These nodes are mapped by `ItemLocalId` alongside the index of their parent node.
821 /// The HIR tree, including bodies, is pre-hashed.
822 pub struct OwnerNodes<'tcx> {
823 /// Pre-computed hash of the full HIR.
824 pub hash_including_bodies: Fingerprint,
825 /// Pre-computed hash of the item signature, without recursing into the body.
826 pub hash_without_bodies: Fingerprint,
827 /// Full HIR for the current owner.
828 // The zeroth node's parent should never be accessed: the owner's parent is computed by the
829 // hir_owner_parent query. It is set to `ItemLocalId::INVALID` to force an ICE if accidentally
831 pub nodes: IndexVec<ItemLocalId, Option<ParentedNode<'tcx>>>,
832 /// Content of local bodies.
833 pub bodies: SortedMap<ItemLocalId, &'tcx Body<'tcx>>,
834 /// Non-owning definitions contained in this owner.
835 pub local_id_to_def_id: SortedMap<ItemLocalId, LocalDefId>,
838 impl<'tcx> OwnerNodes<'tcx> {
839 pub fn node(&self) -> OwnerNode<'tcx> {
840 use rustc_index::vec::Idx;
841 let node = self.nodes[ItemLocalId::new(0)].as_ref().unwrap().node;
842 let node = node.as_owner().unwrap(); // Indexing must ensure it is an OwnerNode.
847 impl fmt::Debug for OwnerNodes<'_> {
848 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
849 f.debug_struct("OwnerNodes")
850 // Do not print all the pointers to all the nodes, as it would be unreadable.
851 .field("node", &self.nodes[ItemLocalId::from_u32(0)])
857 .map(|(id, parented_node)| {
858 let parented_node = parented_node.as_ref().map(|node| node.parent);
860 debug_fn(move |f| write!(f, "({id:?}, {parented_node:?})"))
862 .collect::<Vec<_>>(),
864 .field("bodies", &self.bodies)
865 .field("local_id_to_def_id", &self.local_id_to_def_id)
866 .field("hash_without_bodies", &self.hash_without_bodies)
867 .field("hash_including_bodies", &self.hash_including_bodies)
872 /// Full information resulting from lowering an AST node.
873 #[derive(Debug, HashStable_Generic)]
874 pub struct OwnerInfo<'hir> {
875 /// Contents of the HIR.
876 pub nodes: OwnerNodes<'hir>,
877 /// Map from each nested owner to its parent's local id.
878 pub parenting: FxHashMap<LocalDefId, ItemLocalId>,
879 /// Collected attributes of the HIR nodes.
880 pub attrs: AttributeMap<'hir>,
881 /// Map indicating what traits are in scope for places where this
882 /// is relevant; generated by resolve.
883 pub trait_map: FxHashMap<ItemLocalId, Box<[TraitCandidate]>>,
886 impl<'tcx> OwnerInfo<'tcx> {
888 pub fn node(&self) -> OwnerNode<'tcx> {
893 #[derive(Copy, Clone, Debug, HashStable_Generic)]
894 pub enum MaybeOwner<T> {
897 /// Used as a placeholder for unused LocalDefId.
901 impl<T> MaybeOwner<T> {
902 pub fn as_owner(self) -> Option<T> {
904 MaybeOwner::Owner(i) => Some(i),
905 MaybeOwner::NonOwner(_) | MaybeOwner::Phantom => None,
909 pub fn map<U>(self, f: impl FnOnce(T) -> U) -> MaybeOwner<U> {
911 MaybeOwner::Owner(i) => MaybeOwner::Owner(f(i)),
912 MaybeOwner::NonOwner(hir_id) => MaybeOwner::NonOwner(hir_id),
913 MaybeOwner::Phantom => MaybeOwner::Phantom,
917 pub fn unwrap(self) -> T {
919 MaybeOwner::Owner(i) => i,
920 MaybeOwner::NonOwner(_) | MaybeOwner::Phantom => panic!("Not a HIR owner"),
925 /// The top-level data structure that stores the entire contents of
926 /// the crate currently being compiled.
928 /// For more details, see the [rustc dev guide].
930 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
932 pub struct Crate<'hir> {
933 pub owners: IndexVec<LocalDefId, MaybeOwner<&'hir OwnerInfo<'hir>>>,
934 pub hir_hash: Fingerprint,
937 #[derive(Debug, HashStable_Generic)]
938 pub struct Closure<'hir> {
939 pub def_id: LocalDefId,
940 pub binder: ClosureBinder,
941 pub capture_clause: CaptureBy,
942 pub bound_generic_params: &'hir [GenericParam<'hir>],
943 pub fn_decl: &'hir FnDecl<'hir>,
945 /// The span of the declaration block: 'move |...| -> ...'
946 pub fn_decl_span: Span,
947 /// The span of the argument block `|...|`
948 pub fn_arg_span: Option<Span>,
949 pub movability: Option<Movability>,
952 /// A block of statements `{ .. }`, which may have a label (in this case the
953 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
954 /// the `rules` being anything but `DefaultBlock`.
955 #[derive(Debug, HashStable_Generic)]
956 pub struct Block<'hir> {
957 /// Statements in a block.
958 pub stmts: &'hir [Stmt<'hir>],
959 /// An expression at the end of the block
960 /// without a semicolon, if any.
961 pub expr: Option<&'hir Expr<'hir>>,
962 #[stable_hasher(ignore)]
964 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
965 pub rules: BlockCheckMode,
967 /// If true, then there may exist `break 'a` values that aim to
968 /// break out of this block early.
969 /// Used by `'label: {}` blocks and by `try {}` blocks.
970 pub targeted_by_break: bool,
973 impl<'hir> Block<'hir> {
974 pub fn innermost_block(&self) -> &Block<'hir> {
975 let mut block = self;
976 while let Some(Expr { kind: ExprKind::Block(inner_block, _), .. }) = block.expr {
983 #[derive(Debug, HashStable_Generic)]
984 pub struct Pat<'hir> {
985 #[stable_hasher(ignore)]
987 pub kind: PatKind<'hir>,
989 /// Whether to use default binding modes.
990 /// At present, this is false only for destructuring assignment.
991 pub default_binding_modes: bool,
994 impl<'hir> Pat<'hir> {
995 // FIXME(#19596) this is a workaround, but there should be a better way
996 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) -> bool {
1003 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
1004 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
1005 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
1006 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
1007 Slice(before, slice, after) => {
1008 before.iter().chain(slice).chain(after.iter()).all(|p| p.walk_short_(it))
1013 /// Walk the pattern in left-to-right order,
1014 /// short circuiting (with `.all(..)`) if `false` is returned.
1016 /// Note that when visiting e.g. `Tuple(ps)`,
1017 /// if visiting `ps[0]` returns `false`,
1018 /// then `ps[1]` will not be visited.
1019 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) -> bool {
1020 self.walk_short_(&mut it)
1023 // FIXME(#19596) this is a workaround, but there should be a better way
1024 fn walk_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) {
1031 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
1032 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
1033 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
1034 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
1035 Slice(before, slice, after) => {
1036 before.iter().chain(slice).chain(after.iter()).for_each(|p| p.walk_(it))
1041 /// Walk the pattern in left-to-right order.
1043 /// If `it(pat)` returns `false`, the children are not visited.
1044 pub fn walk(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) {
1048 /// Walk the pattern in left-to-right order.
1050 /// If you always want to recurse, prefer this method over `walk`.
1051 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
1059 /// A single field in a struct pattern.
1061 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
1062 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
1063 /// except `is_shorthand` is true.
1064 #[derive(Debug, HashStable_Generic)]
1065 pub struct PatField<'hir> {
1066 #[stable_hasher(ignore)]
1068 /// The identifier for the field.
1070 /// The pattern the field is destructured to.
1071 pub pat: &'hir Pat<'hir>,
1072 pub is_shorthand: bool,
1076 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1082 impl fmt::Display for RangeEnd {
1083 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1084 f.write_str(match self {
1085 RangeEnd::Included => "..=",
1086 RangeEnd::Excluded => "..",
1091 // Equivalent to `Option<usize>`. That type takes up 16 bytes on 64-bit, but
1092 // this type only takes up 4 bytes, at the cost of being restricted to a
1093 // maximum value of `u32::MAX - 1`. In practice, this is more than enough.
1094 #[derive(Clone, Copy, PartialEq, Eq, Hash, HashStable_Generic)]
1095 pub struct DotDotPos(u32);
1098 /// Panics if n >= u32::MAX.
1099 pub fn new(n: Option<usize>) -> Self {
1102 assert!(n < u32::MAX as usize);
1105 None => Self(u32::MAX),
1109 pub fn as_opt_usize(&self) -> Option<usize> {
1110 if self.0 == u32::MAX { None } else { Some(self.0 as usize) }
1114 impl fmt::Debug for DotDotPos {
1115 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1116 self.as_opt_usize().fmt(f)
1120 #[derive(Debug, HashStable_Generic)]
1121 pub enum PatKind<'hir> {
1122 /// Represents a wildcard pattern (i.e., `_`).
1125 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
1126 /// The `HirId` is the canonical ID for the variable being bound,
1127 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
1128 /// which is the pattern ID of the first `x`.
1129 Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
1131 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
1132 /// The `bool` is `true` in the presence of a `..`.
1133 Struct(QPath<'hir>, &'hir [PatField<'hir>], bool),
1135 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
1136 /// If the `..` pattern fragment is present, then `DotDotPos` denotes its position.
1137 /// `0 <= position <= subpats.len()`
1138 TupleStruct(QPath<'hir>, &'hir [Pat<'hir>], DotDotPos),
1140 /// An or-pattern `A | B | C`.
1141 /// Invariant: `pats.len() >= 2`.
1142 Or(&'hir [Pat<'hir>]),
1144 /// A path pattern for a unit struct/variant or a (maybe-associated) constant.
1147 /// A tuple pattern (e.g., `(a, b)`).
1148 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
1149 /// `0 <= position <= subpats.len()`
1150 Tuple(&'hir [Pat<'hir>], DotDotPos),
1152 /// A `box` pattern.
1153 Box(&'hir Pat<'hir>),
1155 /// A reference pattern (e.g., `&mut (a, b)`).
1156 Ref(&'hir Pat<'hir>, Mutability),
1159 Lit(&'hir Expr<'hir>),
1161 /// A range pattern (e.g., `1..=2` or `1..2`).
1162 Range(Option<&'hir Expr<'hir>>, Option<&'hir Expr<'hir>>, RangeEnd),
1164 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
1166 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
1167 /// If `slice` exists, then `after` can be non-empty.
1169 /// The representation for e.g., `[a, b, .., c, d]` is:
1170 /// ```ignore (illustrative)
1171 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
1173 Slice(&'hir [Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [Pat<'hir>]),
1176 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1177 pub enum BinOpKind {
1178 /// The `+` operator (addition).
1180 /// The `-` operator (subtraction).
1182 /// The `*` operator (multiplication).
1184 /// The `/` operator (division).
1186 /// The `%` operator (modulus).
1188 /// The `&&` operator (logical and).
1190 /// The `||` operator (logical or).
1192 /// The `^` operator (bitwise xor).
1194 /// The `&` operator (bitwise and).
1196 /// The `|` operator (bitwise or).
1198 /// The `<<` operator (shift left).
1200 /// The `>>` operator (shift right).
1202 /// The `==` operator (equality).
1204 /// The `<` operator (less than).
1206 /// The `<=` operator (less than or equal to).
1208 /// The `!=` operator (not equal to).
1210 /// The `>=` operator (greater than or equal to).
1212 /// The `>` operator (greater than).
1217 pub fn as_str(self) -> &'static str {
1219 BinOpKind::Add => "+",
1220 BinOpKind::Sub => "-",
1221 BinOpKind::Mul => "*",
1222 BinOpKind::Div => "/",
1223 BinOpKind::Rem => "%",
1224 BinOpKind::And => "&&",
1225 BinOpKind::Or => "||",
1226 BinOpKind::BitXor => "^",
1227 BinOpKind::BitAnd => "&",
1228 BinOpKind::BitOr => "|",
1229 BinOpKind::Shl => "<<",
1230 BinOpKind::Shr => ">>",
1231 BinOpKind::Eq => "==",
1232 BinOpKind::Lt => "<",
1233 BinOpKind::Le => "<=",
1234 BinOpKind::Ne => "!=",
1235 BinOpKind::Ge => ">=",
1236 BinOpKind::Gt => ">",
1240 pub fn is_lazy(self) -> bool {
1241 matches!(self, BinOpKind::And | BinOpKind::Or)
1244 pub fn is_shift(self) -> bool {
1245 matches!(self, BinOpKind::Shl | BinOpKind::Shr)
1248 pub fn is_comparison(self) -> bool {
1255 | BinOpKind::Ge => true,
1267 | BinOpKind::Shr => false,
1271 /// Returns `true` if the binary operator takes its arguments by value.
1272 pub fn is_by_value(self) -> bool {
1273 !self.is_comparison()
1277 impl Into<ast::BinOpKind> for BinOpKind {
1278 fn into(self) -> ast::BinOpKind {
1280 BinOpKind::Add => ast::BinOpKind::Add,
1281 BinOpKind::Sub => ast::BinOpKind::Sub,
1282 BinOpKind::Mul => ast::BinOpKind::Mul,
1283 BinOpKind::Div => ast::BinOpKind::Div,
1284 BinOpKind::Rem => ast::BinOpKind::Rem,
1285 BinOpKind::And => ast::BinOpKind::And,
1286 BinOpKind::Or => ast::BinOpKind::Or,
1287 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1288 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1289 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1290 BinOpKind::Shl => ast::BinOpKind::Shl,
1291 BinOpKind::Shr => ast::BinOpKind::Shr,
1292 BinOpKind::Eq => ast::BinOpKind::Eq,
1293 BinOpKind::Lt => ast::BinOpKind::Lt,
1294 BinOpKind::Le => ast::BinOpKind::Le,
1295 BinOpKind::Ne => ast::BinOpKind::Ne,
1296 BinOpKind::Ge => ast::BinOpKind::Ge,
1297 BinOpKind::Gt => ast::BinOpKind::Gt,
1302 pub type BinOp = Spanned<BinOpKind>;
1304 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1306 /// The `*` operator (dereferencing).
1308 /// The `!` operator (logical negation).
1310 /// The `-` operator (negation).
1315 pub fn as_str(self) -> &'static str {
1323 /// Returns `true` if the unary operator takes its argument by value.
1324 pub fn is_by_value(self) -> bool {
1325 matches!(self, Self::Neg | Self::Not)
1330 #[derive(Debug, HashStable_Generic)]
1331 pub struct Stmt<'hir> {
1333 pub kind: StmtKind<'hir>,
1337 /// The contents of a statement.
1338 #[derive(Debug, HashStable_Generic)]
1339 pub enum StmtKind<'hir> {
1340 /// A local (`let`) binding.
1341 Local(&'hir Local<'hir>),
1343 /// An item binding.
1346 /// An expression without a trailing semi-colon (must have unit type).
1347 Expr(&'hir Expr<'hir>),
1349 /// An expression with a trailing semi-colon (may have any type).
1350 Semi(&'hir Expr<'hir>),
1353 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <init>;`).
1354 #[derive(Debug, HashStable_Generic)]
1355 pub struct Local<'hir> {
1356 pub pat: &'hir Pat<'hir>,
1357 /// Type annotation, if any (otherwise the type will be inferred).
1358 pub ty: Option<&'hir Ty<'hir>>,
1359 /// Initializer expression to set the value, if any.
1360 pub init: Option<&'hir Expr<'hir>>,
1361 /// Else block for a `let...else` binding.
1362 pub els: Option<&'hir Block<'hir>>,
1365 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1366 /// desugaring. Otherwise will be `Normal`.
1367 pub source: LocalSource,
1370 /// Represents a single arm of a `match` expression, e.g.
1371 /// `<pat> (if <guard>) => <body>`.
1372 #[derive(Debug, HashStable_Generic)]
1373 pub struct Arm<'hir> {
1374 #[stable_hasher(ignore)]
1377 /// If this pattern and the optional guard matches, then `body` is evaluated.
1378 pub pat: &'hir Pat<'hir>,
1379 /// Optional guard clause.
1380 pub guard: Option<Guard<'hir>>,
1381 /// The expression the arm evaluates to if this arm matches.
1382 pub body: &'hir Expr<'hir>,
1385 /// Represents a `let <pat>[: <ty>] = <expr>` expression (not a Local), occurring in an `if-let` or
1386 /// `let-else`, evaluating to a boolean. Typically the pattern is refutable.
1388 /// In an if-let, imagine it as `if (let <pat> = <expr>) { ... }`; in a let-else, it is part of the
1389 /// desugaring to if-let. Only let-else supports the type annotation at present.
1390 #[derive(Debug, HashStable_Generic)]
1391 pub struct Let<'hir> {
1394 pub pat: &'hir Pat<'hir>,
1395 pub ty: Option<&'hir Ty<'hir>>,
1396 pub init: &'hir Expr<'hir>,
1399 #[derive(Debug, HashStable_Generic)]
1400 pub enum Guard<'hir> {
1401 If(&'hir Expr<'hir>),
1402 IfLet(&'hir Let<'hir>),
1405 impl<'hir> Guard<'hir> {
1406 /// Returns the body of the guard
1408 /// In other words, returns the e in either of the following:
1411 /// - `if let x = e`
1412 pub fn body(&self) -> &'hir Expr<'hir> {
1414 Guard::If(e) | Guard::IfLet(Let { init: e, .. }) => e,
1419 #[derive(Debug, HashStable_Generic)]
1420 pub struct ExprField<'hir> {
1421 #[stable_hasher(ignore)]
1424 pub expr: &'hir Expr<'hir>,
1426 pub is_shorthand: bool,
1429 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1430 pub enum BlockCheckMode {
1432 UnsafeBlock(UnsafeSource),
1435 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1436 pub enum UnsafeSource {
1441 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
1446 /// The body of a function, closure, or constant value. In the case of
1447 /// a function, the body contains not only the function body itself
1448 /// (which is an expression), but also the argument patterns, since
1449 /// those are something that the caller doesn't really care about.
1454 /// fn foo((x, y): (u32, u32)) -> u32 {
1459 /// Here, the `Body` associated with `foo()` would contain:
1461 /// - an `params` array containing the `(x, y)` pattern
1462 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1463 /// - `generator_kind` would be `None`
1465 /// All bodies have an **owner**, which can be accessed via the HIR
1466 /// map using `body_owner_def_id()`.
1467 #[derive(Debug, HashStable_Generic)]
1468 pub struct Body<'hir> {
1469 pub params: &'hir [Param<'hir>],
1470 pub value: &'hir Expr<'hir>,
1471 pub generator_kind: Option<GeneratorKind>,
1474 impl<'hir> Body<'hir> {
1475 pub fn id(&self) -> BodyId {
1476 BodyId { hir_id: self.value.hir_id }
1479 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1484 /// The type of source expression that caused this generator to be created.
1485 #[derive(Clone, PartialEq, PartialOrd, Eq, Hash, Debug, Copy)]
1486 #[derive(HashStable_Generic, Encodable, Decodable)]
1487 pub enum GeneratorKind {
1488 /// An explicit `async` block or the body of an async function.
1489 Async(AsyncGeneratorKind),
1491 /// A generator literal created via a `yield` inside a closure.
1495 impl fmt::Display for GeneratorKind {
1496 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1498 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1499 GeneratorKind::Gen => f.write_str("generator"),
1504 impl GeneratorKind {
1505 pub fn descr(&self) -> &'static str {
1507 GeneratorKind::Async(ask) => ask.descr(),
1508 GeneratorKind::Gen => "generator",
1513 /// In the case of a generator created as part of an async construct,
1514 /// which kind of async construct caused it to be created?
1516 /// This helps error messages but is also used to drive coercions in
1517 /// type-checking (see #60424).
1518 #[derive(Clone, PartialEq, PartialOrd, Eq, Hash, Debug, Copy)]
1519 #[derive(HashStable_Generic, Encodable, Decodable)]
1520 pub enum AsyncGeneratorKind {
1521 /// An explicit `async` block written by the user.
1524 /// An explicit `async` closure written by the user.
1527 /// The `async` block generated as the body of an async function.
1531 impl fmt::Display for AsyncGeneratorKind {
1532 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1533 f.write_str(match self {
1534 AsyncGeneratorKind::Block => "async block",
1535 AsyncGeneratorKind::Closure => "async closure body",
1536 AsyncGeneratorKind::Fn => "async fn body",
1541 impl AsyncGeneratorKind {
1542 pub fn descr(&self) -> &'static str {
1544 AsyncGeneratorKind::Block => "`async` block",
1545 AsyncGeneratorKind::Closure => "`async` closure body",
1546 AsyncGeneratorKind::Fn => "`async fn` body",
1551 #[derive(Copy, Clone, Debug)]
1552 pub enum BodyOwnerKind {
1553 /// Functions and methods.
1559 /// Constants and associated constants.
1562 /// Initializer of a `static` item.
1566 impl BodyOwnerKind {
1567 pub fn is_fn_or_closure(self) -> bool {
1569 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1570 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1575 /// The kind of an item that requires const-checking.
1576 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1577 pub enum ConstContext {
1581 /// A `static` or `static mut`.
1584 /// A `const`, associated `const`, or other const context.
1586 /// Other contexts include:
1587 /// - Array length expressions
1588 /// - Enum discriminants
1589 /// - Const generics
1591 /// For the most part, other contexts are treated just like a regular `const`, so they are
1592 /// lumped into the same category.
1597 /// A description of this const context that can appear between backticks in an error message.
1599 /// E.g. `const` or `static mut`.
1600 pub fn keyword_name(self) -> &'static str {
1602 Self::Const => "const",
1603 Self::Static(Mutability::Not) => "static",
1604 Self::Static(Mutability::Mut) => "static mut",
1605 Self::ConstFn => "const fn",
1610 /// A colloquial, trivially pluralizable description of this const context for use in error
1612 impl fmt::Display for ConstContext {
1613 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1615 Self::Const => write!(f, "constant"),
1616 Self::Static(_) => write!(f, "static"),
1617 Self::ConstFn => write!(f, "constant function"),
1622 // NOTE: `IntoDiagnosticArg` impl for `ConstContext` lives in `rustc_errors`
1623 // due to a cyclical dependency between hir that crate.
1626 pub type Lit = Spanned<LitKind>;
1628 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1635 pub fn hir_id(&self) -> HirId {
1637 &ArrayLen::Infer(hir_id, _) | &ArrayLen::Body(AnonConst { hir_id, .. }) => hir_id,
1642 /// A constant (expression) that's not an item or associated item,
1643 /// but needs its own `DefId` for type-checking, const-eval, etc.
1644 /// These are usually found nested inside types (e.g., array lengths)
1645 /// or expressions (e.g., repeat counts), and also used to define
1646 /// explicit discriminant values for enum variants.
1648 /// You can check if this anon const is a default in a const param
1649 /// `const N: usize = { ... }` with `tcx.hir().opt_const_param_default_param_def_id(..)`
1650 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1651 pub struct AnonConst {
1653 pub def_id: LocalDefId,
1658 #[derive(Debug, HashStable_Generic)]
1659 pub struct Expr<'hir> {
1661 pub kind: ExprKind<'hir>,
1666 pub fn precedence(&self) -> ExprPrecedence {
1668 ExprKind::Box(_) => ExprPrecedence::Box,
1669 ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1670 ExprKind::Array(_) => ExprPrecedence::Array,
1671 ExprKind::Call(..) => ExprPrecedence::Call,
1672 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1673 ExprKind::Tup(_) => ExprPrecedence::Tup,
1674 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1675 ExprKind::Unary(..) => ExprPrecedence::Unary,
1676 ExprKind::Lit(_) => ExprPrecedence::Lit,
1677 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1678 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1679 ExprKind::If(..) => ExprPrecedence::If,
1680 ExprKind::Let(..) => ExprPrecedence::Let,
1681 ExprKind::Loop(..) => ExprPrecedence::Loop,
1682 ExprKind::Match(..) => ExprPrecedence::Match,
1683 ExprKind::Closure { .. } => ExprPrecedence::Closure,
1684 ExprKind::Block(..) => ExprPrecedence::Block,
1685 ExprKind::Assign(..) => ExprPrecedence::Assign,
1686 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1687 ExprKind::Field(..) => ExprPrecedence::Field,
1688 ExprKind::Index(..) => ExprPrecedence::Index,
1689 ExprKind::Path(..) => ExprPrecedence::Path,
1690 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1691 ExprKind::Break(..) => ExprPrecedence::Break,
1692 ExprKind::Continue(..) => ExprPrecedence::Continue,
1693 ExprKind::Ret(..) => ExprPrecedence::Ret,
1694 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1695 ExprKind::Struct(..) => ExprPrecedence::Struct,
1696 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1697 ExprKind::Yield(..) => ExprPrecedence::Yield,
1698 ExprKind::Err => ExprPrecedence::Err,
1702 /// Whether this looks like a place expr, without checking for deref
1704 /// This will return `true` in some potentially surprising cases such as
1705 /// `CONSTANT.field`.
1706 pub fn is_syntactic_place_expr(&self) -> bool {
1707 self.is_place_expr(|_| true)
1710 /// Whether this is a place expression.
1712 /// `allow_projections_from` should return `true` if indexing a field or index expression based
1713 /// on the given expression should be considered a place expression.
1714 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1716 ExprKind::Path(QPath::Resolved(_, ref path)) => {
1717 matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static(_), _) | Res::Err)
1720 // Type ascription inherits its place expression kind from its
1722 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1723 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1725 ExprKind::Unary(UnOp::Deref, _) => true,
1727 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1728 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1731 // Lang item paths cannot currently be local variables or statics.
1732 ExprKind::Path(QPath::LangItem(..)) => false,
1734 // Partially qualified paths in expressions can only legally
1735 // refer to associated items which are always rvalues.
1736 ExprKind::Path(QPath::TypeRelative(..))
1737 | ExprKind::Call(..)
1738 | ExprKind::MethodCall(..)
1739 | ExprKind::Struct(..)
1742 | ExprKind::Match(..)
1743 | ExprKind::Closure { .. }
1744 | ExprKind::Block(..)
1745 | ExprKind::Repeat(..)
1746 | ExprKind::Array(..)
1747 | ExprKind::Break(..)
1748 | ExprKind::Continue(..)
1751 | ExprKind::Loop(..)
1752 | ExprKind::Assign(..)
1753 | ExprKind::InlineAsm(..)
1754 | ExprKind::AssignOp(..)
1756 | ExprKind::ConstBlock(..)
1757 | ExprKind::Unary(..)
1759 | ExprKind::AddrOf(..)
1760 | ExprKind::Binary(..)
1761 | ExprKind::Yield(..)
1762 | ExprKind::Cast(..)
1763 | ExprKind::DropTemps(..)
1764 | ExprKind::Err => false,
1768 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1769 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1770 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1771 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1772 /// beyond remembering to call this function before doing analysis on it.
1773 pub fn peel_drop_temps(&self) -> &Self {
1774 let mut expr = self;
1775 while let ExprKind::DropTemps(inner) = &expr.kind {
1781 pub fn peel_blocks(&self) -> &Self {
1782 let mut expr = self;
1783 while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind {
1789 pub fn can_have_side_effects(&self) -> bool {
1790 match self.peel_drop_temps().kind {
1791 ExprKind::Path(_) | ExprKind::Lit(_) => false,
1792 ExprKind::Type(base, _)
1793 | ExprKind::Unary(_, base)
1794 | ExprKind::Field(base, _)
1795 | ExprKind::Index(base, _)
1796 | ExprKind::AddrOf(.., base)
1797 | ExprKind::Cast(base, _) => {
1798 // This isn't exactly true for `Index` and all `Unary`, but we are using this
1799 // method exclusively for diagnostics and there's a *cultural* pressure against
1800 // them being used only for its side-effects.
1801 base.can_have_side_effects()
1803 ExprKind::Struct(_, fields, init) => fields
1805 .map(|field| field.expr)
1806 .chain(init.into_iter())
1807 .all(|e| e.can_have_side_effects()),
1809 ExprKind::Array(args)
1810 | ExprKind::Tup(args)
1814 ExprKind::Path(QPath::Resolved(
1816 Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. },
1821 ) => args.iter().all(|arg| arg.can_have_side_effects()),
1823 | ExprKind::Match(..)
1824 | ExprKind::MethodCall(..)
1825 | ExprKind::Call(..)
1826 | ExprKind::Closure { .. }
1827 | ExprKind::Block(..)
1828 | ExprKind::Repeat(..)
1829 | ExprKind::Break(..)
1830 | ExprKind::Continue(..)
1833 | ExprKind::Loop(..)
1834 | ExprKind::Assign(..)
1835 | ExprKind::InlineAsm(..)
1836 | ExprKind::AssignOp(..)
1837 | ExprKind::ConstBlock(..)
1839 | ExprKind::Binary(..)
1840 | ExprKind::Yield(..)
1841 | ExprKind::DropTemps(..)
1842 | ExprKind::Err => true,
1846 /// To a first-order approximation, is this a pattern?
1847 pub fn is_approximately_pattern(&self) -> bool {
1850 | ExprKind::Array(_)
1851 | ExprKind::Call(..)
1855 | ExprKind::Struct(..) => true,
1860 pub fn method_ident(&self) -> Option<Ident> {
1862 ExprKind::MethodCall(receiver_method, ..) => Some(receiver_method.ident),
1863 ExprKind::Unary(_, expr) | ExprKind::AddrOf(.., expr) => expr.method_ident(),
1869 /// Checks if the specified expression is a built-in range literal.
1870 /// (See: `LoweringContext::lower_expr()`).
1871 pub fn is_range_literal(expr: &Expr<'_>) -> bool {
1873 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1874 ExprKind::Struct(ref qpath, _, _) => matches!(
1879 | LangItem::RangeFrom
1880 | LangItem::RangeFull
1881 | LangItem::RangeToInclusive,
1886 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1887 ExprKind::Call(ref func, _) => {
1888 matches!(func.kind, ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, ..)))
1895 #[derive(Debug, HashStable_Generic)]
1896 pub enum ExprKind<'hir> {
1897 /// A `box x` expression.
1898 Box(&'hir Expr<'hir>),
1899 /// Allow anonymous constants from an inline `const` block
1900 ConstBlock(AnonConst),
1901 /// An array (e.g., `[a, b, c, d]`).
1902 Array(&'hir [Expr<'hir>]),
1903 /// A function call.
1905 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1906 /// and the second field is the list of arguments.
1907 /// This also represents calling the constructor of
1908 /// tuple-like ADTs such as tuple structs and enum variants.
1909 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1910 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1912 /// The `PathSegment` represents the method name and its generic arguments
1913 /// (within the angle brackets).
1914 /// The `&Expr` is the expression that evaluates
1915 /// to the object on which the method is being called on (the receiver),
1916 /// and the `&[Expr]` is the rest of the arguments.
1917 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1918 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, x, [a, b, c, d], span)`.
1919 /// The final `Span` represents the span of the function and arguments
1920 /// (e.g. `foo::<Bar, Baz>(a, b, c, d)` in `x.foo::<Bar, Baz>(a, b, c, d)`
1922 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1923 /// the `hir_id` of the `MethodCall` node itself.
1925 /// [`type_dependent_def_id`]: ../../rustc_middle/ty/struct.TypeckResults.html#method.type_dependent_def_id
1926 MethodCall(&'hir PathSegment<'hir>, &'hir Expr<'hir>, &'hir [Expr<'hir>], Span),
1927 /// A tuple (e.g., `(a, b, c, d)`).
1928 Tup(&'hir [Expr<'hir>]),
1929 /// A binary operation (e.g., `a + b`, `a * b`).
1930 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1931 /// A unary operation (e.g., `!x`, `*x`).
1932 Unary(UnOp, &'hir Expr<'hir>),
1933 /// A literal (e.g., `1`, `"foo"`).
1935 /// A cast (e.g., `foo as f64`).
1936 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1937 /// A type reference (e.g., `Foo`).
1938 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1939 /// Wraps the expression in a terminating scope.
1940 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1942 /// This construct only exists to tweak the drop order in HIR lowering.
1943 /// An example of that is the desugaring of `for` loops.
1944 DropTemps(&'hir Expr<'hir>),
1945 /// A `let $pat = $expr` expression.
1947 /// These are not `Local` and only occur as expressions.
1948 /// The `let Some(x) = foo()` in `if let Some(x) = foo()` is an example of `Let(..)`.
1949 Let(&'hir Let<'hir>),
1950 /// An `if` block, with an optional else block.
1952 /// I.e., `if <expr> { <expr> } else { <expr> }`.
1953 If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
1954 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1956 /// I.e., `'label: loop { <block> }`.
1958 /// The `Span` is the loop header (`for x in y`/`while let pat = expr`).
1959 Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span),
1960 /// A `match` block, with a source that indicates whether or not it is
1961 /// the result of a desugaring, and if so, which kind.
1962 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1963 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1965 /// The `Span` is the argument block `|...|`.
1967 /// This may also be a generator literal or an `async block` as indicated by the
1968 /// `Option<Movability>`.
1969 Closure(&'hir Closure<'hir>),
1970 /// A block (e.g., `'label: { ... }`).
1971 Block(&'hir Block<'hir>, Option<Label>),
1973 /// An assignment (e.g., `a = foo()`).
1974 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1975 /// An assignment with an operator.
1978 AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1979 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1980 Field(&'hir Expr<'hir>, Ident),
1981 /// An indexing operation (`foo[2]`).
1982 Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1984 /// Path to a definition, possibly containing lifetime or type parameters.
1987 /// A referencing operation (i.e., `&a` or `&mut a`).
1988 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1989 /// A `break`, with an optional label to break.
1990 Break(Destination, Option<&'hir Expr<'hir>>),
1991 /// A `continue`, with an optional label.
1992 Continue(Destination),
1993 /// A `return`, with an optional value to be returned.
1994 Ret(Option<&'hir Expr<'hir>>),
1996 /// Inline assembly (from `asm!`), with its outputs and inputs.
1997 InlineAsm(&'hir InlineAsm<'hir>),
1999 /// A struct or struct-like variant literal expression.
2001 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
2002 /// where `base` is the `Option<Expr>`.
2003 Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], Option<&'hir Expr<'hir>>),
2005 /// An array literal constructed from one repeated element.
2007 /// E.g., `[1; 5]`. The first expression is the element
2008 /// to be repeated; the second is the number of times to repeat it.
2009 Repeat(&'hir Expr<'hir>, ArrayLen),
2011 /// A suspension point for generators (i.e., `yield <expr>`).
2012 Yield(&'hir Expr<'hir>, YieldSource),
2014 /// A placeholder for an expression that wasn't syntactically well formed in some way.
2018 /// Represents an optionally `Self`-qualified value/type path or associated extension.
2020 /// To resolve the path to a `DefId`, call [`qpath_res`].
2022 /// [`qpath_res`]: ../../rustc_middle/ty/struct.TypeckResults.html#method.qpath_res
2023 #[derive(Debug, HashStable_Generic)]
2024 pub enum QPath<'hir> {
2025 /// Path to a definition, optionally "fully-qualified" with a `Self`
2026 /// type, if the path points to an associated item in a trait.
2028 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
2029 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
2030 /// even though they both have the same two-segment `Clone::clone` `Path`.
2031 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
2033 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
2034 /// Will be resolved by type-checking to an associated item.
2036 /// UFCS source paths can desugar into this, with `Vec::new` turning into
2037 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
2038 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
2039 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
2041 /// Reference to a `#[lang = "foo"]` item. `HirId` of the inner expr.
2042 LangItem(LangItem, Span, Option<HirId>),
2045 impl<'hir> QPath<'hir> {
2046 /// Returns the span of this `QPath`.
2047 pub fn span(&self) -> Span {
2049 QPath::Resolved(_, path) => path.span,
2050 QPath::TypeRelative(qself, ps) => qself.span.to(ps.ident.span),
2051 QPath::LangItem(_, span, _) => span,
2055 /// Returns the span of the qself of this `QPath`. For example, `()` in
2056 /// `<() as Trait>::method`.
2057 pub fn qself_span(&self) -> Span {
2059 QPath::Resolved(_, path) => path.span,
2060 QPath::TypeRelative(qself, _) => qself.span,
2061 QPath::LangItem(_, span, _) => span,
2065 /// Returns the span of the last segment of this `QPath`. For example, `method` in
2066 /// `<() as Trait>::method`.
2067 pub fn last_segment_span(&self) -> Span {
2069 QPath::Resolved(_, path) => path.segments.last().unwrap().ident.span,
2070 QPath::TypeRelative(_, segment) => segment.ident.span,
2071 QPath::LangItem(_, span, _) => span,
2076 /// Hints at the original code for a let statement.
2077 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2078 pub enum LocalSource {
2079 /// A `match _ { .. }`.
2081 /// When lowering async functions, we create locals within the `async move` so that
2082 /// all parameters are dropped after the future is polled.
2084 /// ```ignore (pseudo-Rust)
2085 /// async fn foo(<pattern> @ x: Type) {
2087 /// let <pattern> = x;
2092 /// A desugared `<expr>.await`.
2094 /// A desugared `expr = expr`, where the LHS is a tuple, struct or array.
2095 /// The span is that of the `=` sign.
2096 AssignDesugar(Span),
2099 /// Hints at the original code for a `match _ { .. }`.
2100 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
2101 #[derive(HashStable_Generic)]
2102 pub enum MatchSource {
2103 /// A `match _ { .. }`.
2105 /// A desugared `for _ in _ { .. }` loop.
2107 /// A desugared `?` operator.
2109 /// A desugared `<expr>.await`.
2115 pub const fn name(self) -> &'static str {
2119 ForLoopDesugar => "for",
2121 AwaitDesugar => ".await",
2126 /// The loop type that yielded an `ExprKind::Loop`.
2127 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2128 pub enum LoopSource {
2129 /// A `loop { .. }` loop.
2131 /// A `while _ { .. }` loop.
2133 /// A `for _ in _ { .. }` loop.
2138 pub fn name(self) -> &'static str {
2140 LoopSource::Loop => "loop",
2141 LoopSource::While => "while",
2142 LoopSource::ForLoop => "for",
2147 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2148 pub enum LoopIdError {
2150 UnlabeledCfInWhileCondition,
2154 impl fmt::Display for LoopIdError {
2155 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2156 f.write_str(match self {
2157 LoopIdError::OutsideLoopScope => "not inside loop scope",
2158 LoopIdError::UnlabeledCfInWhileCondition => {
2159 "unlabeled control flow (break or continue) in while condition"
2161 LoopIdError::UnresolvedLabel => "label not found",
2166 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2167 pub struct Destination {
2168 /// This is `Some(_)` iff there is an explicit user-specified 'label
2169 pub label: Option<Label>,
2171 /// These errors are caught and then reported during the diagnostics pass in
2172 /// `librustc_passes/loops.rs`
2173 pub target_id: Result<HirId, LoopIdError>,
2176 /// The yield kind that caused an `ExprKind::Yield`.
2177 #[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
2178 pub enum YieldSource {
2179 /// An `<expr>.await`.
2180 Await { expr: Option<HirId> },
2181 /// A plain `yield`.
2186 pub fn is_await(&self) -> bool {
2187 matches!(self, YieldSource::Await { .. })
2191 impl fmt::Display for YieldSource {
2192 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2193 f.write_str(match self {
2194 YieldSource::Await { .. } => "`await`",
2195 YieldSource::Yield => "`yield`",
2200 impl From<GeneratorKind> for YieldSource {
2201 fn from(kind: GeneratorKind) -> Self {
2203 // Guess based on the kind of the current generator.
2204 GeneratorKind::Gen => Self::Yield,
2205 GeneratorKind::Async(_) => Self::Await { expr: None },
2210 // N.B., if you change this, you'll probably want to change the corresponding
2211 // type structure in middle/ty.rs as well.
2212 #[derive(Debug, HashStable_Generic)]
2213 pub struct MutTy<'hir> {
2214 pub ty: &'hir Ty<'hir>,
2215 pub mutbl: Mutability,
2218 /// Represents a function's signature in a trait declaration,
2219 /// trait implementation, or a free function.
2220 #[derive(Debug, HashStable_Generic)]
2221 pub struct FnSig<'hir> {
2222 pub header: FnHeader,
2223 pub decl: &'hir FnDecl<'hir>,
2227 // The bodies for items are stored "out of line", in a separate
2228 // hashmap in the `Crate`. Here we just record the hir-id of the item
2229 // so it can fetched later.
2230 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2231 pub struct TraitItemId {
2232 pub owner_id: OwnerId,
2237 pub fn hir_id(&self) -> HirId {
2238 // Items are always HIR owners.
2239 HirId::make_owner(self.owner_id.def_id)
2243 /// Represents an item declaration within a trait declaration,
2244 /// possibly including a default implementation. A trait item is
2245 /// either required (meaning it doesn't have an implementation, just a
2246 /// signature) or provided (meaning it has a default implementation).
2247 #[derive(Debug, HashStable_Generic)]
2248 pub struct TraitItem<'hir> {
2250 pub owner_id: OwnerId,
2251 pub generics: &'hir Generics<'hir>,
2252 pub kind: TraitItemKind<'hir>,
2254 pub defaultness: Defaultness,
2257 impl TraitItem<'_> {
2259 pub fn hir_id(&self) -> HirId {
2260 // Items are always HIR owners.
2261 HirId::make_owner(self.owner_id.def_id)
2264 pub fn trait_item_id(&self) -> TraitItemId {
2265 TraitItemId { owner_id: self.owner_id }
2269 /// Represents a trait method's body (or just argument names).
2270 #[derive(Encodable, Debug, HashStable_Generic)]
2271 pub enum TraitFn<'hir> {
2272 /// No default body in the trait, just a signature.
2273 Required(&'hir [Ident]),
2275 /// Both signature and body are provided in the trait.
2279 /// Represents a trait method or associated constant or type
2280 #[derive(Debug, HashStable_Generic)]
2281 pub enum TraitItemKind<'hir> {
2282 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
2283 Const(&'hir Ty<'hir>, Option<BodyId>),
2284 /// An associated function with an optional body.
2285 Fn(FnSig<'hir>, TraitFn<'hir>),
2286 /// An associated type with (possibly empty) bounds and optional concrete
2288 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
2291 // The bodies for items are stored "out of line", in a separate
2292 // hashmap in the `Crate`. Here we just record the hir-id of the item
2293 // so it can fetched later.
2294 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2295 pub struct ImplItemId {
2296 pub owner_id: OwnerId,
2301 pub fn hir_id(&self) -> HirId {
2302 // Items are always HIR owners.
2303 HirId::make_owner(self.owner_id.def_id)
2307 /// Represents anything within an `impl` block.
2308 #[derive(Debug, HashStable_Generic)]
2309 pub struct ImplItem<'hir> {
2311 pub owner_id: OwnerId,
2312 pub generics: &'hir Generics<'hir>,
2313 pub kind: ImplItemKind<'hir>,
2314 pub defaultness: Defaultness,
2321 pub fn hir_id(&self) -> HirId {
2322 // Items are always HIR owners.
2323 HirId::make_owner(self.owner_id.def_id)
2326 pub fn impl_item_id(&self) -> ImplItemId {
2327 ImplItemId { owner_id: self.owner_id }
2331 /// Represents various kinds of content within an `impl`.
2332 #[derive(Debug, HashStable_Generic)]
2333 pub enum ImplItemKind<'hir> {
2334 /// An associated constant of the given type, set to the constant result
2335 /// of the expression.
2336 Const(&'hir Ty<'hir>, BodyId),
2337 /// An associated function implementation with the given signature and body.
2338 Fn(FnSig<'hir>, BodyId),
2339 /// An associated type.
2340 Type(&'hir Ty<'hir>),
2343 /// The name of the associated type for `Fn` return types.
2344 pub const FN_OUTPUT_NAME: Symbol = sym::Output;
2346 /// Bind a type to an associated type (i.e., `A = Foo`).
2348 /// Bindings like `A: Debug` are represented as a special type `A =
2349 /// $::Debug` that is understood by the astconv code.
2351 /// FIXME(alexreg): why have a separate type for the binding case,
2352 /// wouldn't it be better to make the `ty` field an enum like the
2355 /// ```ignore (pseudo-rust)
2356 /// enum TypeBindingKind {
2361 #[derive(Debug, HashStable_Generic)]
2362 pub struct TypeBinding<'hir> {
2365 pub gen_args: &'hir GenericArgs<'hir>,
2366 pub kind: TypeBindingKind<'hir>,
2370 #[derive(Debug, HashStable_Generic)]
2371 pub enum Term<'hir> {
2376 impl<'hir> From<&'hir Ty<'hir>> for Term<'hir> {
2377 fn from(ty: &'hir Ty<'hir>) -> Self {
2382 impl<'hir> From<AnonConst> for Term<'hir> {
2383 fn from(c: AnonConst) -> Self {
2388 // Represents the two kinds of type bindings.
2389 #[derive(Debug, HashStable_Generic)]
2390 pub enum TypeBindingKind<'hir> {
2391 /// E.g., `Foo<Bar: Send>`.
2392 Constraint { bounds: &'hir [GenericBound<'hir>] },
2393 /// E.g., `Foo<Bar = ()>`, `Foo<Bar = ()>`
2394 Equality { term: Term<'hir> },
2397 impl TypeBinding<'_> {
2398 pub fn ty(&self) -> &Ty<'_> {
2400 TypeBindingKind::Equality { term: Term::Ty(ref ty) } => ty,
2401 _ => panic!("expected equality type binding for parenthesized generic args"),
2404 pub fn opt_const(&self) -> Option<&'_ AnonConst> {
2406 TypeBindingKind::Equality { term: Term::Const(ref c) } => Some(c),
2412 #[derive(Debug, HashStable_Generic)]
2413 pub struct Ty<'hir> {
2415 pub kind: TyKind<'hir>,
2419 impl<'hir> Ty<'hir> {
2420 /// Returns `true` if `param_def_id` matches the `bounded_ty` of this predicate.
2421 pub fn as_generic_param(&self) -> Option<(DefId, Ident)> {
2422 let TyKind::Path(QPath::Resolved(None, path)) = self.kind else {
2425 let [segment] = &path.segments else {
2429 Res::Def(DefKind::TyParam, def_id) | Res::SelfTyParam { trait_: def_id } => {
2430 Some((def_id, segment.ident))
2436 pub fn peel_refs(&self) -> &Self {
2437 let mut final_ty = self;
2438 while let TyKind::Ref(_, MutTy { ty, .. }) = &final_ty.kind {
2444 pub fn find_self_aliases(&self) -> Vec<Span> {
2445 use crate::intravisit::Visitor;
2446 struct MyVisitor(Vec<Span>);
2447 impl<'v> Visitor<'v> for MyVisitor {
2448 fn visit_ty(&mut self, t: &'v Ty<'v>) {
2451 TyKind::Path(QPath::Resolved(
2453 Path { res: crate::def::Res::SelfTyAlias { .. }, .. },
2456 self.0.push(t.span);
2459 crate::intravisit::walk_ty(self, t);
2463 let mut my_visitor = MyVisitor(vec![]);
2464 my_visitor.visit_ty(self);
2469 /// Not represented directly in the AST; referred to by name through a `ty_path`.
2470 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
2471 #[derive(HashStable_Generic)]
2482 /// All of the primitive types
2483 pub const ALL: [Self; 17] = [
2484 // any changes here should also be reflected in `PrimTy::from_name`
2485 Self::Int(IntTy::I8),
2486 Self::Int(IntTy::I16),
2487 Self::Int(IntTy::I32),
2488 Self::Int(IntTy::I64),
2489 Self::Int(IntTy::I128),
2490 Self::Int(IntTy::Isize),
2491 Self::Uint(UintTy::U8),
2492 Self::Uint(UintTy::U16),
2493 Self::Uint(UintTy::U32),
2494 Self::Uint(UintTy::U64),
2495 Self::Uint(UintTy::U128),
2496 Self::Uint(UintTy::Usize),
2497 Self::Float(FloatTy::F32),
2498 Self::Float(FloatTy::F64),
2504 /// Like [`PrimTy::name`], but returns a &str instead of a symbol.
2507 pub fn name_str(self) -> &'static str {
2509 PrimTy::Int(i) => i.name_str(),
2510 PrimTy::Uint(u) => u.name_str(),
2511 PrimTy::Float(f) => f.name_str(),
2512 PrimTy::Str => "str",
2513 PrimTy::Bool => "bool",
2514 PrimTy::Char => "char",
2518 pub fn name(self) -> Symbol {
2520 PrimTy::Int(i) => i.name(),
2521 PrimTy::Uint(u) => u.name(),
2522 PrimTy::Float(f) => f.name(),
2523 PrimTy::Str => sym::str,
2524 PrimTy::Bool => sym::bool,
2525 PrimTy::Char => sym::char,
2529 /// Returns the matching `PrimTy` for a `Symbol` such as "str" or "i32".
2530 /// Returns `None` if no matching type is found.
2531 pub fn from_name(name: Symbol) -> Option<Self> {
2532 let ty = match name {
2533 // any changes here should also be reflected in `PrimTy::ALL`
2534 sym::i8 => Self::Int(IntTy::I8),
2535 sym::i16 => Self::Int(IntTy::I16),
2536 sym::i32 => Self::Int(IntTy::I32),
2537 sym::i64 => Self::Int(IntTy::I64),
2538 sym::i128 => Self::Int(IntTy::I128),
2539 sym::isize => Self::Int(IntTy::Isize),
2540 sym::u8 => Self::Uint(UintTy::U8),
2541 sym::u16 => Self::Uint(UintTy::U16),
2542 sym::u32 => Self::Uint(UintTy::U32),
2543 sym::u64 => Self::Uint(UintTy::U64),
2544 sym::u128 => Self::Uint(UintTy::U128),
2545 sym::usize => Self::Uint(UintTy::Usize),
2546 sym::f32 => Self::Float(FloatTy::F32),
2547 sym::f64 => Self::Float(FloatTy::F64),
2548 sym::bool => Self::Bool,
2549 sym::char => Self::Char,
2550 sym::str => Self::Str,
2557 #[derive(Debug, HashStable_Generic)]
2558 pub struct BareFnTy<'hir> {
2559 pub unsafety: Unsafety,
2561 pub generic_params: &'hir [GenericParam<'hir>],
2562 pub decl: &'hir FnDecl<'hir>,
2563 pub param_names: &'hir [Ident],
2566 #[derive(Debug, HashStable_Generic)]
2567 pub struct OpaqueTy<'hir> {
2568 pub generics: &'hir Generics<'hir>,
2569 pub bounds: GenericBounds<'hir>,
2570 pub origin: OpaqueTyOrigin,
2574 /// From whence the opaque type came.
2575 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2576 pub enum OpaqueTyOrigin {
2578 FnReturn(LocalDefId),
2580 AsyncFn(LocalDefId),
2581 /// type aliases: `type Foo = impl Trait;`
2585 /// The various kinds of types recognized by the compiler.
2586 #[derive(Debug, HashStable_Generic)]
2587 pub enum TyKind<'hir> {
2588 /// A variable length slice (i.e., `[T]`).
2589 Slice(&'hir Ty<'hir>),
2590 /// A fixed length array (i.e., `[T; n]`).
2591 Array(&'hir Ty<'hir>, ArrayLen),
2592 /// A raw pointer (i.e., `*const T` or `*mut T`).
2594 /// A reference (i.e., `&'a T` or `&'a mut T`).
2595 Ref(&'hir Lifetime, MutTy<'hir>),
2596 /// A bare function (e.g., `fn(usize) -> bool`).
2597 BareFn(&'hir BareFnTy<'hir>),
2598 /// The never type (`!`).
2600 /// A tuple (`(A, B, C, D, ...)`).
2601 Tup(&'hir [Ty<'hir>]),
2602 /// A path to a type definition (`module::module::...::Type`), or an
2603 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2605 /// Type parameters may be stored in each `PathSegment`.
2607 /// An opaque type definition itself. This is only used for `impl Trait`.
2609 /// The generic argument list contains the lifetimes (and in the future
2610 /// possibly parameters) that are actually bound on the `impl Trait`.
2612 /// The last parameter specifies whether this opaque appears in a trait definition.
2613 OpaqueDef(ItemId, &'hir [GenericArg<'hir>], bool),
2614 /// A trait object type `Bound1 + Bound2 + Bound3`
2615 /// where `Bound` is a trait or a lifetime.
2616 TraitObject(&'hir [PolyTraitRef<'hir>], &'hir Lifetime, TraitObjectSyntax),
2619 /// `TyKind::Infer` means the type should be inferred instead of it having been
2620 /// specified. This can appear anywhere in a type.
2622 /// Placeholder for a type that has failed to be defined.
2626 #[derive(Debug, HashStable_Generic)]
2627 pub enum InlineAsmOperand<'hir> {
2629 reg: InlineAsmRegOrRegClass,
2630 expr: &'hir Expr<'hir>,
2633 reg: InlineAsmRegOrRegClass,
2635 expr: Option<&'hir Expr<'hir>>,
2638 reg: InlineAsmRegOrRegClass,
2640 expr: &'hir Expr<'hir>,
2643 reg: InlineAsmRegOrRegClass,
2645 in_expr: &'hir Expr<'hir>,
2646 out_expr: Option<&'hir Expr<'hir>>,
2649 anon_const: AnonConst,
2652 anon_const: AnonConst,
2660 impl<'hir> InlineAsmOperand<'hir> {
2661 pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
2663 Self::In { reg, .. }
2664 | Self::Out { reg, .. }
2665 | Self::InOut { reg, .. }
2666 | Self::SplitInOut { reg, .. } => Some(reg),
2667 Self::Const { .. } | Self::SymFn { .. } | Self::SymStatic { .. } => None,
2671 pub fn is_clobber(&self) -> bool {
2674 InlineAsmOperand::Out { reg: InlineAsmRegOrRegClass::Reg(_), late: _, expr: None }
2679 #[derive(Debug, HashStable_Generic)]
2680 pub struct InlineAsm<'hir> {
2681 pub template: &'hir [InlineAsmTemplatePiece],
2682 pub template_strs: &'hir [(Symbol, Option<Symbol>, Span)],
2683 pub operands: &'hir [(InlineAsmOperand<'hir>, Span)],
2684 pub options: InlineAsmOptions,
2685 pub line_spans: &'hir [Span],
2688 /// Represents a parameter in a function header.
2689 #[derive(Debug, HashStable_Generic)]
2690 pub struct Param<'hir> {
2692 pub pat: &'hir Pat<'hir>,
2697 /// Represents the header (not the body) of a function declaration.
2698 #[derive(Debug, HashStable_Generic)]
2699 pub struct FnDecl<'hir> {
2700 /// The types of the function's parameters.
2702 /// Additional argument data is stored in the function's [body](Body::params).
2703 pub inputs: &'hir [Ty<'hir>],
2704 pub output: FnRetTy<'hir>,
2705 pub c_variadic: bool,
2706 /// Does the function have an implicit self?
2707 pub implicit_self: ImplicitSelfKind,
2708 /// Is lifetime elision allowed.
2709 pub lifetime_elision_allowed: bool,
2712 /// Represents what type of implicit self a function has, if any.
2713 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2714 pub enum ImplicitSelfKind {
2715 /// Represents a `fn x(self);`.
2717 /// Represents a `fn x(mut self);`.
2719 /// Represents a `fn x(&self);`.
2721 /// Represents a `fn x(&mut self);`.
2723 /// Represents when a function does not have a self argument or
2724 /// when a function has a `self: X` argument.
2728 impl ImplicitSelfKind {
2729 /// Does this represent an implicit self?
2730 pub fn has_implicit_self(&self) -> bool {
2731 !matches!(*self, ImplicitSelfKind::None)
2735 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable, Debug)]
2736 #[derive(HashStable_Generic)]
2743 pub fn is_async(self) -> bool {
2744 self == IsAsync::Async
2748 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable, HashStable_Generic)]
2749 pub enum Defaultness {
2750 Default { has_value: bool },
2755 pub fn has_value(&self) -> bool {
2757 Defaultness::Default { has_value } => has_value,
2758 Defaultness::Final => true,
2762 pub fn is_final(&self) -> bool {
2763 *self == Defaultness::Final
2766 pub fn is_default(&self) -> bool {
2767 matches!(*self, Defaultness::Default { .. })
2771 #[derive(Debug, HashStable_Generic)]
2772 pub enum FnRetTy<'hir> {
2773 /// Return type is not specified.
2775 /// Functions default to `()` and
2776 /// closures default to inference. Span points to where return
2777 /// type would be inserted.
2778 DefaultReturn(Span),
2779 /// Everything else.
2780 Return(&'hir Ty<'hir>),
2785 pub fn span(&self) -> Span {
2787 Self::DefaultReturn(span) => span,
2788 Self::Return(ref ty) => ty.span,
2793 /// Represents `for<...>` binder before a closure
2794 #[derive(Copy, Clone, Debug, HashStable_Generic)]
2795 pub enum ClosureBinder {
2796 /// Binder is not specified.
2798 /// Binder is specified.
2800 /// Span points to the whole `for<...>`.
2804 #[derive(Encodable, Debug, HashStable_Generic)]
2805 pub struct Mod<'hir> {
2806 pub spans: ModSpans,
2807 pub item_ids: &'hir [ItemId],
2810 #[derive(Copy, Clone, Debug, HashStable_Generic, Encodable)]
2811 pub struct ModSpans {
2812 /// A span from the first token past `{` to the last token until `}`.
2813 /// For `mod foo;`, the inner span ranges from the first token
2814 /// to the last token in the external file.
2815 pub inner_span: Span,
2816 pub inject_use_span: Span,
2819 #[derive(Debug, HashStable_Generic)]
2820 pub struct EnumDef<'hir> {
2821 pub variants: &'hir [Variant<'hir>],
2824 #[derive(Debug, HashStable_Generic)]
2825 pub struct Variant<'hir> {
2826 /// Name of the variant.
2828 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2830 pub def_id: LocalDefId,
2831 /// Fields and constructor id of the variant.
2832 pub data: VariantData<'hir>,
2833 /// Explicit discriminant (e.g., `Foo = 1`).
2834 pub disr_expr: Option<AnonConst>,
2839 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2841 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2842 /// Also produced for each element of a list `use`, e.g.
2843 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2846 /// Glob import, e.g., `use foo::*`.
2849 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2850 /// an additional `use foo::{}` for performing checks such as
2851 /// unstable feature gating. May be removed in the future.
2855 /// References to traits in impls.
2857 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2858 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2859 /// trait being referred to but just a unique `HirId` that serves as a key
2860 /// within the resolution map.
2861 #[derive(Clone, Debug, HashStable_Generic)]
2862 pub struct TraitRef<'hir> {
2863 pub path: &'hir Path<'hir>,
2864 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2865 #[stable_hasher(ignore)]
2866 pub hir_ref_id: HirId,
2870 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2871 pub fn trait_def_id(&self) -> Option<DefId> {
2872 match self.path.res {
2873 Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
2875 _ => unreachable!(),
2880 #[derive(Clone, Debug, HashStable_Generic)]
2881 pub struct PolyTraitRef<'hir> {
2882 /// The `'a` in `for<'a> Foo<&'a T>`.
2883 pub bound_generic_params: &'hir [GenericParam<'hir>],
2885 /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
2886 pub trait_ref: TraitRef<'hir>,
2891 #[derive(Debug, HashStable_Generic)]
2892 pub struct FieldDef<'hir> {
2897 pub def_id: LocalDefId,
2898 pub ty: &'hir Ty<'hir>,
2902 // Still necessary in couple of places
2903 pub fn is_positional(&self) -> bool {
2904 let first = self.ident.as_str().as_bytes()[0];
2905 (b'0'..=b'9').contains(&first)
2909 /// Fields and constructor IDs of enum variants and structs.
2910 #[derive(Debug, HashStable_Generic)]
2911 pub enum VariantData<'hir> {
2912 /// A struct variant.
2914 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2915 Struct(&'hir [FieldDef<'hir>], /* recovered */ bool),
2916 /// A tuple variant.
2918 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2919 Tuple(&'hir [FieldDef<'hir>], HirId, LocalDefId),
2922 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2923 Unit(HirId, LocalDefId),
2926 impl<'hir> VariantData<'hir> {
2927 /// Return the fields of this variant.
2928 pub fn fields(&self) -> &'hir [FieldDef<'hir>] {
2930 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2935 pub fn ctor(&self) -> Option<(CtorKind, HirId, LocalDefId)> {
2937 VariantData::Tuple(_, hir_id, def_id) => Some((CtorKind::Fn, hir_id, def_id)),
2938 VariantData::Unit(hir_id, def_id) => Some((CtorKind::Const, hir_id, def_id)),
2939 VariantData::Struct(..) => None,
2944 pub fn ctor_kind(&self) -> Option<CtorKind> {
2945 self.ctor().map(|(kind, ..)| kind)
2948 /// Return the `HirId` of this variant's constructor, if it has one.
2950 pub fn ctor_hir_id(&self) -> Option<HirId> {
2951 self.ctor().map(|(_, hir_id, _)| hir_id)
2954 /// Return the `LocalDefId` of this variant's constructor, if it has one.
2956 pub fn ctor_def_id(&self) -> Option<LocalDefId> {
2957 self.ctor().map(|(.., def_id)| def_id)
2961 // The bodies for items are stored "out of line", in a separate
2962 // hashmap in the `Crate`. Here we just record the hir-id of the item
2963 // so it can fetched later.
2964 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
2966 pub owner_id: OwnerId,
2971 pub fn hir_id(&self) -> HirId {
2972 // Items are always HIR owners.
2973 HirId::make_owner(self.owner_id.def_id)
2979 /// The name might be a dummy name in case of anonymous items
2980 #[derive(Debug, HashStable_Generic)]
2981 pub struct Item<'hir> {
2983 pub owner_id: OwnerId,
2984 pub kind: ItemKind<'hir>,
2991 pub fn hir_id(&self) -> HirId {
2992 // Items are always HIR owners.
2993 HirId::make_owner(self.owner_id.def_id)
2996 pub fn item_id(&self) -> ItemId {
2997 ItemId { owner_id: self.owner_id }
3001 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
3002 #[derive(Encodable, Decodable, HashStable_Generic)]
3009 pub fn prefix_str(&self) -> &'static str {
3011 Self::Unsafe => "unsafe ",
3017 impl fmt::Display for Unsafety {
3018 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3019 f.write_str(match *self {
3020 Self::Unsafe => "unsafe",
3021 Self::Normal => "normal",
3026 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
3027 #[derive(Encodable, Decodable, HashStable_Generic)]
3028 pub enum Constness {
3033 impl fmt::Display for Constness {
3034 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3035 f.write_str(match *self {
3036 Self::Const => "const",
3037 Self::NotConst => "non-const",
3042 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
3043 pub struct FnHeader {
3044 pub unsafety: Unsafety,
3045 pub constness: Constness,
3046 pub asyncness: IsAsync,
3051 pub fn is_async(&self) -> bool {
3052 matches!(&self.asyncness, IsAsync::Async)
3055 pub fn is_const(&self) -> bool {
3056 matches!(&self.constness, Constness::Const)
3059 pub fn is_unsafe(&self) -> bool {
3060 matches!(&self.unsafety, Unsafety::Unsafe)
3064 #[derive(Debug, HashStable_Generic)]
3065 pub enum ItemKind<'hir> {
3066 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
3068 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
3069 ExternCrate(Option<Symbol>),
3071 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
3075 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
3076 Use(&'hir UsePath<'hir>, UseKind),
3078 /// A `static` item.
3079 Static(&'hir Ty<'hir>, Mutability, BodyId),
3081 Const(&'hir Ty<'hir>, BodyId),
3082 /// A function declaration.
3083 Fn(FnSig<'hir>, &'hir Generics<'hir>, BodyId),
3084 /// A MBE macro definition (`macro_rules!` or `macro`).
3085 Macro(ast::MacroDef, MacroKind),
3087 Mod(&'hir Mod<'hir>),
3088 /// An external module, e.g. `extern { .. }`.
3089 ForeignMod { abi: Abi, items: &'hir [ForeignItemRef] },
3090 /// Module-level inline assembly (from `global_asm!`).
3091 GlobalAsm(&'hir InlineAsm<'hir>),
3092 /// A type alias, e.g., `type Foo = Bar<u8>`.
3093 TyAlias(&'hir Ty<'hir>, &'hir Generics<'hir>),
3094 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
3095 OpaqueTy(OpaqueTy<'hir>),
3096 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
3097 Enum(EnumDef<'hir>, &'hir Generics<'hir>),
3098 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
3099 Struct(VariantData<'hir>, &'hir Generics<'hir>),
3100 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
3101 Union(VariantData<'hir>, &'hir Generics<'hir>),
3102 /// A trait definition.
3103 Trait(IsAuto, Unsafety, &'hir Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
3105 TraitAlias(&'hir Generics<'hir>, GenericBounds<'hir>),
3107 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
3108 Impl(&'hir Impl<'hir>),
3111 #[derive(Debug, HashStable_Generic)]
3112 pub struct Impl<'hir> {
3113 pub unsafety: Unsafety,
3114 pub polarity: ImplPolarity,
3115 pub defaultness: Defaultness,
3116 // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata
3117 // decoding as `Span`s cannot be decoded when a `Session` is not available.
3118 pub defaultness_span: Option<Span>,
3119 pub constness: Constness,
3120 pub generics: &'hir Generics<'hir>,
3122 /// The trait being implemented, if any.
3123 pub of_trait: Option<TraitRef<'hir>>,
3125 pub self_ty: &'hir Ty<'hir>,
3126 pub items: &'hir [ImplItemRef],
3130 pub fn generics(&self) -> Option<&Generics<'_>> {
3132 ItemKind::Fn(_, ref generics, _)
3133 | ItemKind::TyAlias(_, ref generics)
3134 | ItemKind::OpaqueTy(OpaqueTy { ref generics, .. })
3135 | ItemKind::Enum(_, ref generics)
3136 | ItemKind::Struct(_, ref generics)
3137 | ItemKind::Union(_, ref generics)
3138 | ItemKind::Trait(_, _, ref generics, _, _)
3139 | ItemKind::TraitAlias(ref generics, _)
3140 | ItemKind::Impl(Impl { ref generics, .. }) => generics,
3145 pub fn descr(&self) -> &'static str {
3147 ItemKind::ExternCrate(..) => "extern crate",
3148 ItemKind::Use(..) => "`use` import",
3149 ItemKind::Static(..) => "static item",
3150 ItemKind::Const(..) => "constant item",
3151 ItemKind::Fn(..) => "function",
3152 ItemKind::Macro(..) => "macro",
3153 ItemKind::Mod(..) => "module",
3154 ItemKind::ForeignMod { .. } => "extern block",
3155 ItemKind::GlobalAsm(..) => "global asm item",
3156 ItemKind::TyAlias(..) => "type alias",
3157 ItemKind::OpaqueTy(..) => "opaque type",
3158 ItemKind::Enum(..) => "enum",
3159 ItemKind::Struct(..) => "struct",
3160 ItemKind::Union(..) => "union",
3161 ItemKind::Trait(..) => "trait",
3162 ItemKind::TraitAlias(..) => "trait alias",
3163 ItemKind::Impl(..) => "implementation",
3168 /// A reference from an trait to one of its associated items. This
3169 /// contains the item's id, naturally, but also the item's name and
3170 /// some other high-level details (like whether it is an associated
3171 /// type or method, and whether it is public). This allows other
3172 /// passes to find the impl they want without loading the ID (which
3173 /// means fewer edges in the incremental compilation graph).
3174 #[derive(Encodable, Debug, HashStable_Generic)]
3175 pub struct TraitItemRef {
3176 pub id: TraitItemId,
3178 pub kind: AssocItemKind,
3182 /// A reference from an impl to one of its associated items. This
3183 /// contains the item's ID, naturally, but also the item's name and
3184 /// some other high-level details (like whether it is an associated
3185 /// type or method, and whether it is public). This allows other
3186 /// passes to find the impl they want without loading the ID (which
3187 /// means fewer edges in the incremental compilation graph).
3188 #[derive(Debug, HashStable_Generic)]
3189 pub struct ImplItemRef {
3192 pub kind: AssocItemKind,
3194 /// When we are in a trait impl, link to the trait-item's id.
3195 pub trait_item_def_id: Option<DefId>,
3198 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
3199 pub enum AssocItemKind {
3201 Fn { has_self: bool },
3205 // The bodies for items are stored "out of line", in a separate
3206 // hashmap in the `Crate`. Here we just record the hir-id of the item
3207 // so it can fetched later.
3208 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3209 pub struct ForeignItemId {
3210 pub owner_id: OwnerId,
3213 impl ForeignItemId {
3215 pub fn hir_id(&self) -> HirId {
3216 // Items are always HIR owners.
3217 HirId::make_owner(self.owner_id.def_id)
3221 /// A reference from a foreign block to one of its items. This
3222 /// contains the item's ID, naturally, but also the item's name and
3223 /// some other high-level details (like whether it is an associated
3224 /// type or method, and whether it is public). This allows other
3225 /// passes to find the impl they want without loading the ID (which
3226 /// means fewer edges in the incremental compilation graph).
3227 #[derive(Debug, HashStable_Generic)]
3228 pub struct ForeignItemRef {
3229 pub id: ForeignItemId,
3234 #[derive(Debug, HashStable_Generic)]
3235 pub struct ForeignItem<'hir> {
3237 pub kind: ForeignItemKind<'hir>,
3238 pub owner_id: OwnerId,
3243 impl ForeignItem<'_> {
3245 pub fn hir_id(&self) -> HirId {
3246 // Items are always HIR owners.
3247 HirId::make_owner(self.owner_id.def_id)
3250 pub fn foreign_item_id(&self) -> ForeignItemId {
3251 ForeignItemId { owner_id: self.owner_id }
3255 /// An item within an `extern` block.
3256 #[derive(Debug, HashStable_Generic)]
3257 pub enum ForeignItemKind<'hir> {
3258 /// A foreign function.
3259 Fn(&'hir FnDecl<'hir>, &'hir [Ident], &'hir Generics<'hir>),
3260 /// A foreign static item (`static ext: u8`).
3261 Static(&'hir Ty<'hir>, Mutability),
3266 /// A variable captured by a closure.
3267 #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)]
3269 /// First span where it is accessed (there can be multiple).
3273 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
3274 // has length > 0 if the trait is found through an chain of imports, starting with the
3275 // import/use statement in the scope where the trait is used.
3276 #[derive(Encodable, Decodable, Clone, Debug, HashStable_Generic)]
3277 pub struct TraitCandidate {
3279 pub import_ids: SmallVec<[LocalDefId; 1]>,
3282 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3283 pub enum OwnerNode<'hir> {
3284 Item(&'hir Item<'hir>),
3285 ForeignItem(&'hir ForeignItem<'hir>),
3286 TraitItem(&'hir TraitItem<'hir>),
3287 ImplItem(&'hir ImplItem<'hir>),
3288 Crate(&'hir Mod<'hir>),
3291 impl<'hir> OwnerNode<'hir> {
3292 pub fn ident(&self) -> Option<Ident> {
3294 OwnerNode::Item(Item { ident, .. })
3295 | OwnerNode::ForeignItem(ForeignItem { ident, .. })
3296 | OwnerNode::ImplItem(ImplItem { ident, .. })
3297 | OwnerNode::TraitItem(TraitItem { ident, .. }) => Some(*ident),
3298 OwnerNode::Crate(..) => None,
3302 pub fn span(&self) -> Span {
3304 OwnerNode::Item(Item { span, .. })
3305 | OwnerNode::ForeignItem(ForeignItem { span, .. })
3306 | OwnerNode::ImplItem(ImplItem { span, .. })
3307 | OwnerNode::TraitItem(TraitItem { span, .. }) => *span,
3308 OwnerNode::Crate(Mod { spans: ModSpans { inner_span, .. }, .. }) => *inner_span,
3312 pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
3314 OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3315 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3316 | OwnerNode::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3317 OwnerNode::ForeignItem(ForeignItem {
3318 kind: ForeignItemKind::Fn(fn_decl, _, _),
3320 }) => Some(fn_decl),
3325 pub fn body_id(&self) -> Option<BodyId> {
3327 OwnerNode::TraitItem(TraitItem {
3328 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3331 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3332 | OwnerNode::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3337 pub fn generics(self) -> Option<&'hir Generics<'hir>> {
3338 Node::generics(self.into())
3341 pub fn def_id(self) -> OwnerId {
3343 OwnerNode::Item(Item { owner_id, .. })
3344 | OwnerNode::TraitItem(TraitItem { owner_id, .. })
3345 | OwnerNode::ImplItem(ImplItem { owner_id, .. })
3346 | OwnerNode::ForeignItem(ForeignItem { owner_id, .. }) => *owner_id,
3347 OwnerNode::Crate(..) => crate::CRATE_HIR_ID.owner,
3351 pub fn expect_item(self) -> &'hir Item<'hir> {
3353 OwnerNode::Item(n) => n,
3358 pub fn expect_foreign_item(self) -> &'hir ForeignItem<'hir> {
3360 OwnerNode::ForeignItem(n) => n,
3365 pub fn expect_impl_item(self) -> &'hir ImplItem<'hir> {
3367 OwnerNode::ImplItem(n) => n,
3372 pub fn expect_trait_item(self) -> &'hir TraitItem<'hir> {
3374 OwnerNode::TraitItem(n) => n,
3380 impl<'hir> Into<OwnerNode<'hir>> for &'hir Item<'hir> {
3381 fn into(self) -> OwnerNode<'hir> {
3382 OwnerNode::Item(self)
3386 impl<'hir> Into<OwnerNode<'hir>> for &'hir ForeignItem<'hir> {
3387 fn into(self) -> OwnerNode<'hir> {
3388 OwnerNode::ForeignItem(self)
3392 impl<'hir> Into<OwnerNode<'hir>> for &'hir ImplItem<'hir> {
3393 fn into(self) -> OwnerNode<'hir> {
3394 OwnerNode::ImplItem(self)
3398 impl<'hir> Into<OwnerNode<'hir>> for &'hir TraitItem<'hir> {
3399 fn into(self) -> OwnerNode<'hir> {
3400 OwnerNode::TraitItem(self)
3404 impl<'hir> Into<Node<'hir>> for OwnerNode<'hir> {
3405 fn into(self) -> Node<'hir> {
3407 OwnerNode::Item(n) => Node::Item(n),
3408 OwnerNode::ForeignItem(n) => Node::ForeignItem(n),
3409 OwnerNode::ImplItem(n) => Node::ImplItem(n),
3410 OwnerNode::TraitItem(n) => Node::TraitItem(n),
3411 OwnerNode::Crate(n) => Node::Crate(n),
3416 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3417 pub enum Node<'hir> {
3418 Param(&'hir Param<'hir>),
3419 Item(&'hir Item<'hir>),
3420 ForeignItem(&'hir ForeignItem<'hir>),
3421 TraitItem(&'hir TraitItem<'hir>),
3422 ImplItem(&'hir ImplItem<'hir>),
3423 Variant(&'hir Variant<'hir>),
3424 Field(&'hir FieldDef<'hir>),
3425 AnonConst(&'hir AnonConst),
3426 Expr(&'hir Expr<'hir>),
3427 ExprField(&'hir ExprField<'hir>),
3428 Stmt(&'hir Stmt<'hir>),
3429 PathSegment(&'hir PathSegment<'hir>),
3431 TypeBinding(&'hir TypeBinding<'hir>),
3432 TraitRef(&'hir TraitRef<'hir>),
3433 Pat(&'hir Pat<'hir>),
3434 PatField(&'hir PatField<'hir>),
3435 Arm(&'hir Arm<'hir>),
3436 Block(&'hir Block<'hir>),
3437 Local(&'hir Local<'hir>),
3439 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
3440 /// with synthesized constructors.
3441 Ctor(&'hir VariantData<'hir>),
3443 Lifetime(&'hir Lifetime),
3444 GenericParam(&'hir GenericParam<'hir>),
3446 Crate(&'hir Mod<'hir>),
3448 Infer(&'hir InferArg),
3451 impl<'hir> Node<'hir> {
3452 /// Get the identifier of this `Node`, if applicable.
3456 /// Calling `.ident()` on a [`Node::Ctor`] will return `None`
3457 /// because `Ctor`s do not have identifiers themselves.
3458 /// Instead, call `.ident()` on the parent struct/variant, like so:
3460 /// ```ignore (illustrative)
3463 /// .and_then(|ctor_id| tcx.hir().find(tcx.hir().get_parent_node(ctor_id)))
3464 /// .and_then(|parent| parent.ident())
3466 pub fn ident(&self) -> Option<Ident> {
3468 Node::TraitItem(TraitItem { ident, .. })
3469 | Node::ImplItem(ImplItem { ident, .. })
3470 | Node::ForeignItem(ForeignItem { ident, .. })
3471 | Node::Field(FieldDef { ident, .. })
3472 | Node::Variant(Variant { ident, .. })
3473 | Node::Item(Item { ident, .. })
3474 | Node::PathSegment(PathSegment { ident, .. }) => Some(*ident),
3475 Node::Lifetime(lt) => Some(lt.ident),
3476 Node::GenericParam(p) => Some(p.name.ident()),
3477 Node::TypeBinding(b) => Some(b.ident),
3479 | Node::AnonConst(..)
3485 | Node::PatField(..)
3486 | Node::ExprField(..)
3491 | Node::TraitRef(..)
3492 | Node::Infer(..) => None,
3496 pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
3498 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3499 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3500 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3501 Node::Expr(Expr { kind: ExprKind::Closure(Closure { fn_decl, .. }), .. })
3502 | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
3509 pub fn fn_sig(self) -> Option<&'hir FnSig<'hir>> {
3511 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3512 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3513 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig),
3518 pub fn body_id(&self) -> Option<BodyId> {
3520 Node::TraitItem(TraitItem {
3521 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3524 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3525 | Node::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3530 pub fn generics(self) -> Option<&'hir Generics<'hir>> {
3532 Node::ForeignItem(ForeignItem {
3533 kind: ForeignItemKind::Fn(_, _, generics), ..
3535 | Node::TraitItem(TraitItem { generics, .. })
3536 | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
3537 Node::Item(item) => item.kind.generics(),
3542 pub fn as_owner(self) -> Option<OwnerNode<'hir>> {
3544 Node::Item(i) => Some(OwnerNode::Item(i)),
3545 Node::ForeignItem(i) => Some(OwnerNode::ForeignItem(i)),
3546 Node::TraitItem(i) => Some(OwnerNode::TraitItem(i)),
3547 Node::ImplItem(i) => Some(OwnerNode::ImplItem(i)),
3548 Node::Crate(i) => Some(OwnerNode::Crate(i)),
3553 pub fn fn_kind(self) -> Option<FnKind<'hir>> {
3555 Node::Item(i) => match i.kind {
3556 ItemKind::Fn(ref sig, ref generics, _) => {
3557 Some(FnKind::ItemFn(i.ident, generics, sig.header))
3561 Node::TraitItem(ti) => match ti.kind {
3562 TraitItemKind::Fn(ref sig, TraitFn::Provided(_)) => {
3563 Some(FnKind::Method(ti.ident, sig))
3567 Node::ImplItem(ii) => match ii.kind {
3568 ImplItemKind::Fn(ref sig, _) => Some(FnKind::Method(ii.ident, sig)),
3571 Node::Expr(e) => match e.kind {
3572 ExprKind::Closure { .. } => Some(FnKind::Closure),
3579 /// Get the fields for the tuple-constructor,
3580 /// if this node is a tuple constructor, otherwise None
3581 pub fn tuple_fields(&self) -> Option<&'hir [FieldDef<'hir>]> {
3582 if let Node::Ctor(&VariantData::Tuple(fields, _, _)) = self { Some(fields) } else { None }
3586 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3587 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
3590 // tidy-alphabetical-start
3591 static_assert_size!(Block<'_>, 48);
3592 static_assert_size!(Body<'_>, 32);
3593 static_assert_size!(Expr<'_>, 64);
3594 static_assert_size!(ExprKind<'_>, 48);
3595 static_assert_size!(FnDecl<'_>, 40);
3596 static_assert_size!(ForeignItem<'_>, 72);
3597 static_assert_size!(ForeignItemKind<'_>, 40);
3598 static_assert_size!(GenericArg<'_>, 32);
3599 static_assert_size!(GenericBound<'_>, 48);
3600 static_assert_size!(Generics<'_>, 56);
3601 static_assert_size!(Impl<'_>, 80);
3602 static_assert_size!(ImplItem<'_>, 80);
3603 static_assert_size!(ImplItemKind<'_>, 32);
3604 static_assert_size!(Item<'_>, 80);
3605 static_assert_size!(ItemKind<'_>, 48);
3606 static_assert_size!(Local<'_>, 64);
3607 static_assert_size!(Param<'_>, 32);
3608 static_assert_size!(Pat<'_>, 72);
3609 static_assert_size!(Path<'_>, 40);
3610 static_assert_size!(PathSegment<'_>, 48);
3611 static_assert_size!(PatKind<'_>, 48);
3612 static_assert_size!(QPath<'_>, 24);
3613 static_assert_size!(Res, 12);
3614 static_assert_size!(Stmt<'_>, 32);
3615 static_assert_size!(StmtKind<'_>, 16);
3616 static_assert_size!(TraitItem<'_>, 80);
3617 static_assert_size!(TraitItemKind<'_>, 40);
3618 static_assert_size!(Ty<'_>, 48);
3619 static_assert_size!(TyKind<'_>, 32);
3620 // tidy-alphabetical-end
3623 fn debug_fn(f: impl Fn(&mut fmt::Formatter<'_>) -> fmt::Result) -> impl fmt::Debug {
3624 struct DebugFn<F>(F);
3625 impl<F: Fn(&mut fmt::Formatter<'_>) -> fmt::Result> fmt::Debug for DebugFn<F> {
3626 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {