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 constness: Constness,
942 pub capture_clause: CaptureBy,
943 pub bound_generic_params: &'hir [GenericParam<'hir>],
944 pub fn_decl: &'hir FnDecl<'hir>,
946 /// The span of the declaration block: 'move |...| -> ...'
947 pub fn_decl_span: Span,
948 /// The span of the argument block `|...|`
949 pub fn_arg_span: Option<Span>,
950 pub movability: Option<Movability>,
953 /// A block of statements `{ .. }`, which may have a label (in this case the
954 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
955 /// the `rules` being anything but `DefaultBlock`.
956 #[derive(Debug, HashStable_Generic)]
957 pub struct Block<'hir> {
958 /// Statements in a block.
959 pub stmts: &'hir [Stmt<'hir>],
960 /// An expression at the end of the block
961 /// without a semicolon, if any.
962 pub expr: Option<&'hir Expr<'hir>>,
963 #[stable_hasher(ignore)]
965 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
966 pub rules: BlockCheckMode,
968 /// If true, then there may exist `break 'a` values that aim to
969 /// break out of this block early.
970 /// Used by `'label: {}` blocks and by `try {}` blocks.
971 pub targeted_by_break: bool,
974 impl<'hir> Block<'hir> {
975 pub fn innermost_block(&self) -> &Block<'hir> {
976 let mut block = self;
977 while let Some(Expr { kind: ExprKind::Block(inner_block, _), .. }) = block.expr {
984 #[derive(Debug, HashStable_Generic)]
985 pub struct Pat<'hir> {
986 #[stable_hasher(ignore)]
988 pub kind: PatKind<'hir>,
990 /// Whether to use default binding modes.
991 /// At present, this is false only for destructuring assignment.
992 pub default_binding_modes: bool,
995 impl<'hir> Pat<'hir> {
996 // FIXME(#19596) this is a workaround, but there should be a better way
997 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) -> bool {
1004 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
1005 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
1006 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
1007 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
1008 Slice(before, slice, after) => {
1009 before.iter().chain(slice).chain(after.iter()).all(|p| p.walk_short_(it))
1014 /// Walk the pattern in left-to-right order,
1015 /// short circuiting (with `.all(..)`) if `false` is returned.
1017 /// Note that when visiting e.g. `Tuple(ps)`,
1018 /// if visiting `ps[0]` returns `false`,
1019 /// then `ps[1]` will not be visited.
1020 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) -> bool {
1021 self.walk_short_(&mut it)
1024 // FIXME(#19596) this is a workaround, but there should be a better way
1025 fn walk_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) {
1032 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
1033 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
1034 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
1035 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
1036 Slice(before, slice, after) => {
1037 before.iter().chain(slice).chain(after.iter()).for_each(|p| p.walk_(it))
1042 /// Walk the pattern in left-to-right order.
1044 /// If `it(pat)` returns `false`, the children are not visited.
1045 pub fn walk(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) {
1049 /// Walk the pattern in left-to-right order.
1051 /// If you always want to recurse, prefer this method over `walk`.
1052 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
1060 /// A single field in a struct pattern.
1062 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
1063 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
1064 /// except `is_shorthand` is true.
1065 #[derive(Debug, HashStable_Generic)]
1066 pub struct PatField<'hir> {
1067 #[stable_hasher(ignore)]
1069 /// The identifier for the field.
1071 /// The pattern the field is destructured to.
1072 pub pat: &'hir Pat<'hir>,
1073 pub is_shorthand: bool,
1077 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1083 impl fmt::Display for RangeEnd {
1084 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1085 f.write_str(match self {
1086 RangeEnd::Included => "..=",
1087 RangeEnd::Excluded => "..",
1092 // Equivalent to `Option<usize>`. That type takes up 16 bytes on 64-bit, but
1093 // this type only takes up 4 bytes, at the cost of being restricted to a
1094 // maximum value of `u32::MAX - 1`. In practice, this is more than enough.
1095 #[derive(Clone, Copy, PartialEq, Eq, Hash, HashStable_Generic)]
1096 pub struct DotDotPos(u32);
1099 /// Panics if n >= u32::MAX.
1100 pub fn new(n: Option<usize>) -> Self {
1103 assert!(n < u32::MAX as usize);
1106 None => Self(u32::MAX),
1110 pub fn as_opt_usize(&self) -> Option<usize> {
1111 if self.0 == u32::MAX { None } else { Some(self.0 as usize) }
1115 impl fmt::Debug for DotDotPos {
1116 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1117 self.as_opt_usize().fmt(f)
1121 #[derive(Debug, HashStable_Generic)]
1122 pub enum PatKind<'hir> {
1123 /// Represents a wildcard pattern (i.e., `_`).
1126 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
1127 /// The `HirId` is the canonical ID for the variable being bound,
1128 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
1129 /// which is the pattern ID of the first `x`.
1130 Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
1132 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
1133 /// The `bool` is `true` in the presence of a `..`.
1134 Struct(QPath<'hir>, &'hir [PatField<'hir>], bool),
1136 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
1137 /// If the `..` pattern fragment is present, then `DotDotPos` denotes its position.
1138 /// `0 <= position <= subpats.len()`
1139 TupleStruct(QPath<'hir>, &'hir [Pat<'hir>], DotDotPos),
1141 /// An or-pattern `A | B | C`.
1142 /// Invariant: `pats.len() >= 2`.
1143 Or(&'hir [Pat<'hir>]),
1145 /// A path pattern for a unit struct/variant or a (maybe-associated) constant.
1148 /// A tuple pattern (e.g., `(a, b)`).
1149 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
1150 /// `0 <= position <= subpats.len()`
1151 Tuple(&'hir [Pat<'hir>], DotDotPos),
1153 /// A `box` pattern.
1154 Box(&'hir Pat<'hir>),
1156 /// A reference pattern (e.g., `&mut (a, b)`).
1157 Ref(&'hir Pat<'hir>, Mutability),
1160 Lit(&'hir Expr<'hir>),
1162 /// A range pattern (e.g., `1..=2` or `1..2`).
1163 Range(Option<&'hir Expr<'hir>>, Option<&'hir Expr<'hir>>, RangeEnd),
1165 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
1167 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
1168 /// If `slice` exists, then `after` can be non-empty.
1170 /// The representation for e.g., `[a, b, .., c, d]` is:
1171 /// ```ignore (illustrative)
1172 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
1174 Slice(&'hir [Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [Pat<'hir>]),
1177 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1178 pub enum BinOpKind {
1179 /// The `+` operator (addition).
1181 /// The `-` operator (subtraction).
1183 /// The `*` operator (multiplication).
1185 /// The `/` operator (division).
1187 /// The `%` operator (modulus).
1189 /// The `&&` operator (logical and).
1191 /// The `||` operator (logical or).
1193 /// The `^` operator (bitwise xor).
1195 /// The `&` operator (bitwise and).
1197 /// The `|` operator (bitwise or).
1199 /// The `<<` operator (shift left).
1201 /// The `>>` operator (shift right).
1203 /// The `==` operator (equality).
1205 /// The `<` operator (less than).
1207 /// The `<=` operator (less than or equal to).
1209 /// The `!=` operator (not equal to).
1211 /// The `>=` operator (greater than or equal to).
1213 /// The `>` operator (greater than).
1218 pub fn as_str(self) -> &'static str {
1220 BinOpKind::Add => "+",
1221 BinOpKind::Sub => "-",
1222 BinOpKind::Mul => "*",
1223 BinOpKind::Div => "/",
1224 BinOpKind::Rem => "%",
1225 BinOpKind::And => "&&",
1226 BinOpKind::Or => "||",
1227 BinOpKind::BitXor => "^",
1228 BinOpKind::BitAnd => "&",
1229 BinOpKind::BitOr => "|",
1230 BinOpKind::Shl => "<<",
1231 BinOpKind::Shr => ">>",
1232 BinOpKind::Eq => "==",
1233 BinOpKind::Lt => "<",
1234 BinOpKind::Le => "<=",
1235 BinOpKind::Ne => "!=",
1236 BinOpKind::Ge => ">=",
1237 BinOpKind::Gt => ">",
1241 pub fn is_lazy(self) -> bool {
1242 matches!(self, BinOpKind::And | BinOpKind::Or)
1245 pub fn is_shift(self) -> bool {
1246 matches!(self, BinOpKind::Shl | BinOpKind::Shr)
1249 pub fn is_comparison(self) -> bool {
1256 | BinOpKind::Ge => true,
1268 | BinOpKind::Shr => false,
1272 /// Returns `true` if the binary operator takes its arguments by value.
1273 pub fn is_by_value(self) -> bool {
1274 !self.is_comparison()
1278 impl Into<ast::BinOpKind> for BinOpKind {
1279 fn into(self) -> ast::BinOpKind {
1281 BinOpKind::Add => ast::BinOpKind::Add,
1282 BinOpKind::Sub => ast::BinOpKind::Sub,
1283 BinOpKind::Mul => ast::BinOpKind::Mul,
1284 BinOpKind::Div => ast::BinOpKind::Div,
1285 BinOpKind::Rem => ast::BinOpKind::Rem,
1286 BinOpKind::And => ast::BinOpKind::And,
1287 BinOpKind::Or => ast::BinOpKind::Or,
1288 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1289 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1290 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1291 BinOpKind::Shl => ast::BinOpKind::Shl,
1292 BinOpKind::Shr => ast::BinOpKind::Shr,
1293 BinOpKind::Eq => ast::BinOpKind::Eq,
1294 BinOpKind::Lt => ast::BinOpKind::Lt,
1295 BinOpKind::Le => ast::BinOpKind::Le,
1296 BinOpKind::Ne => ast::BinOpKind::Ne,
1297 BinOpKind::Ge => ast::BinOpKind::Ge,
1298 BinOpKind::Gt => ast::BinOpKind::Gt,
1303 pub type BinOp = Spanned<BinOpKind>;
1305 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1307 /// The `*` operator (dereferencing).
1309 /// The `!` operator (logical negation).
1311 /// The `-` operator (negation).
1316 pub fn as_str(self) -> &'static str {
1324 /// Returns `true` if the unary operator takes its argument by value.
1325 pub fn is_by_value(self) -> bool {
1326 matches!(self, Self::Neg | Self::Not)
1331 #[derive(Debug, HashStable_Generic)]
1332 pub struct Stmt<'hir> {
1334 pub kind: StmtKind<'hir>,
1338 /// The contents of a statement.
1339 #[derive(Debug, HashStable_Generic)]
1340 pub enum StmtKind<'hir> {
1341 /// A local (`let`) binding.
1342 Local(&'hir Local<'hir>),
1344 /// An item binding.
1347 /// An expression without a trailing semi-colon (must have unit type).
1348 Expr(&'hir Expr<'hir>),
1350 /// An expression with a trailing semi-colon (may have any type).
1351 Semi(&'hir Expr<'hir>),
1354 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <init>;`).
1355 #[derive(Debug, HashStable_Generic)]
1356 pub struct Local<'hir> {
1357 pub pat: &'hir Pat<'hir>,
1358 /// Type annotation, if any (otherwise the type will be inferred).
1359 pub ty: Option<&'hir Ty<'hir>>,
1360 /// Initializer expression to set the value, if any.
1361 pub init: Option<&'hir Expr<'hir>>,
1362 /// Else block for a `let...else` binding.
1363 pub els: Option<&'hir Block<'hir>>,
1366 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1367 /// desugaring. Otherwise will be `Normal`.
1368 pub source: LocalSource,
1371 /// Represents a single arm of a `match` expression, e.g.
1372 /// `<pat> (if <guard>) => <body>`.
1373 #[derive(Debug, HashStable_Generic)]
1374 pub struct Arm<'hir> {
1375 #[stable_hasher(ignore)]
1378 /// If this pattern and the optional guard matches, then `body` is evaluated.
1379 pub pat: &'hir Pat<'hir>,
1380 /// Optional guard clause.
1381 pub guard: Option<Guard<'hir>>,
1382 /// The expression the arm evaluates to if this arm matches.
1383 pub body: &'hir Expr<'hir>,
1386 /// Represents a `let <pat>[: <ty>] = <expr>` expression (not a Local), occurring in an `if-let` or
1387 /// `let-else`, evaluating to a boolean. Typically the pattern is refutable.
1389 /// In an if-let, imagine it as `if (let <pat> = <expr>) { ... }`; in a let-else, it is part of the
1390 /// desugaring to if-let. Only let-else supports the type annotation at present.
1391 #[derive(Debug, HashStable_Generic)]
1392 pub struct Let<'hir> {
1395 pub pat: &'hir Pat<'hir>,
1396 pub ty: Option<&'hir Ty<'hir>>,
1397 pub init: &'hir Expr<'hir>,
1400 #[derive(Debug, HashStable_Generic)]
1401 pub enum Guard<'hir> {
1402 If(&'hir Expr<'hir>),
1403 IfLet(&'hir Let<'hir>),
1406 impl<'hir> Guard<'hir> {
1407 /// Returns the body of the guard
1409 /// In other words, returns the e in either of the following:
1412 /// - `if let x = e`
1413 pub fn body(&self) -> &'hir Expr<'hir> {
1415 Guard::If(e) | Guard::IfLet(Let { init: e, .. }) => e,
1420 #[derive(Debug, HashStable_Generic)]
1421 pub struct ExprField<'hir> {
1422 #[stable_hasher(ignore)]
1425 pub expr: &'hir Expr<'hir>,
1427 pub is_shorthand: bool,
1430 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1431 pub enum BlockCheckMode {
1433 UnsafeBlock(UnsafeSource),
1436 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1437 pub enum UnsafeSource {
1442 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
1447 /// The body of a function, closure, or constant value. In the case of
1448 /// a function, the body contains not only the function body itself
1449 /// (which is an expression), but also the argument patterns, since
1450 /// those are something that the caller doesn't really care about.
1455 /// fn foo((x, y): (u32, u32)) -> u32 {
1460 /// Here, the `Body` associated with `foo()` would contain:
1462 /// - an `params` array containing the `(x, y)` pattern
1463 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1464 /// - `generator_kind` would be `None`
1466 /// All bodies have an **owner**, which can be accessed via the HIR
1467 /// map using `body_owner_def_id()`.
1468 #[derive(Debug, HashStable_Generic)]
1469 pub struct Body<'hir> {
1470 pub params: &'hir [Param<'hir>],
1471 pub value: &'hir Expr<'hir>,
1472 pub generator_kind: Option<GeneratorKind>,
1475 impl<'hir> Body<'hir> {
1476 pub fn id(&self) -> BodyId {
1477 BodyId { hir_id: self.value.hir_id }
1480 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1485 /// The type of source expression that caused this generator to be created.
1486 #[derive(Clone, PartialEq, PartialOrd, Eq, Hash, Debug, Copy)]
1487 #[derive(HashStable_Generic, Encodable, Decodable)]
1488 pub enum GeneratorKind {
1489 /// An explicit `async` block or the body of an async function.
1490 Async(AsyncGeneratorKind),
1492 /// A generator literal created via a `yield` inside a closure.
1496 impl fmt::Display for GeneratorKind {
1497 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1499 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1500 GeneratorKind::Gen => f.write_str("generator"),
1505 impl GeneratorKind {
1506 pub fn descr(&self) -> &'static str {
1508 GeneratorKind::Async(ask) => ask.descr(),
1509 GeneratorKind::Gen => "generator",
1514 /// In the case of a generator created as part of an async construct,
1515 /// which kind of async construct caused it to be created?
1517 /// This helps error messages but is also used to drive coercions in
1518 /// type-checking (see #60424).
1519 #[derive(Clone, PartialEq, PartialOrd, Eq, Hash, Debug, Copy)]
1520 #[derive(HashStable_Generic, Encodable, Decodable)]
1521 pub enum AsyncGeneratorKind {
1522 /// An explicit `async` block written by the user.
1525 /// An explicit `async` closure written by the user.
1528 /// The `async` block generated as the body of an async function.
1532 impl fmt::Display for AsyncGeneratorKind {
1533 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1534 f.write_str(match self {
1535 AsyncGeneratorKind::Block => "async block",
1536 AsyncGeneratorKind::Closure => "async closure body",
1537 AsyncGeneratorKind::Fn => "async fn body",
1542 impl AsyncGeneratorKind {
1543 pub fn descr(&self) -> &'static str {
1545 AsyncGeneratorKind::Block => "`async` block",
1546 AsyncGeneratorKind::Closure => "`async` closure body",
1547 AsyncGeneratorKind::Fn => "`async fn` body",
1552 #[derive(Copy, Clone, Debug)]
1553 pub enum BodyOwnerKind {
1554 /// Functions and methods.
1560 /// Constants and associated constants.
1563 /// Initializer of a `static` item.
1567 impl BodyOwnerKind {
1568 pub fn is_fn_or_closure(self) -> bool {
1570 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1571 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1576 /// The kind of an item that requires const-checking.
1577 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1578 pub enum ConstContext {
1582 /// A `static` or `static mut`.
1585 /// A `const`, associated `const`, or other const context.
1587 /// Other contexts include:
1588 /// - Array length expressions
1589 /// - Enum discriminants
1590 /// - Const generics
1592 /// For the most part, other contexts are treated just like a regular `const`, so they are
1593 /// lumped into the same category.
1598 /// A description of this const context that can appear between backticks in an error message.
1600 /// E.g. `const` or `static mut`.
1601 pub fn keyword_name(self) -> &'static str {
1603 Self::Const => "const",
1604 Self::Static(Mutability::Not) => "static",
1605 Self::Static(Mutability::Mut) => "static mut",
1606 Self::ConstFn => "const fn",
1611 /// A colloquial, trivially pluralizable description of this const context for use in error
1613 impl fmt::Display for ConstContext {
1614 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1616 Self::Const => write!(f, "constant"),
1617 Self::Static(_) => write!(f, "static"),
1618 Self::ConstFn => write!(f, "constant function"),
1623 // NOTE: `IntoDiagnosticArg` impl for `ConstContext` lives in `rustc_errors`
1624 // due to a cyclical dependency between hir that crate.
1627 pub type Lit = Spanned<LitKind>;
1629 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1636 pub fn hir_id(&self) -> HirId {
1638 &ArrayLen::Infer(hir_id, _) | &ArrayLen::Body(AnonConst { hir_id, .. }) => hir_id,
1643 /// A constant (expression) that's not an item or associated item,
1644 /// but needs its own `DefId` for type-checking, const-eval, etc.
1645 /// These are usually found nested inside types (e.g., array lengths)
1646 /// or expressions (e.g., repeat counts), and also used to define
1647 /// explicit discriminant values for enum variants.
1649 /// You can check if this anon const is a default in a const param
1650 /// `const N: usize = { ... }` with `tcx.hir().opt_const_param_default_param_def_id(..)`
1651 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1652 pub struct AnonConst {
1654 pub def_id: LocalDefId,
1659 #[derive(Debug, HashStable_Generic)]
1660 pub struct Expr<'hir> {
1662 pub kind: ExprKind<'hir>,
1667 pub fn precedence(&self) -> ExprPrecedence {
1669 ExprKind::Box(_) => ExprPrecedence::Box,
1670 ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1671 ExprKind::Array(_) => ExprPrecedence::Array,
1672 ExprKind::Call(..) => ExprPrecedence::Call,
1673 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1674 ExprKind::Tup(_) => ExprPrecedence::Tup,
1675 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1676 ExprKind::Unary(..) => ExprPrecedence::Unary,
1677 ExprKind::Lit(_) => ExprPrecedence::Lit,
1678 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1679 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1680 ExprKind::If(..) => ExprPrecedence::If,
1681 ExprKind::Let(..) => ExprPrecedence::Let,
1682 ExprKind::Loop(..) => ExprPrecedence::Loop,
1683 ExprKind::Match(..) => ExprPrecedence::Match,
1684 ExprKind::Closure { .. } => ExprPrecedence::Closure,
1685 ExprKind::Block(..) => ExprPrecedence::Block,
1686 ExprKind::Assign(..) => ExprPrecedence::Assign,
1687 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1688 ExprKind::Field(..) => ExprPrecedence::Field,
1689 ExprKind::Index(..) => ExprPrecedence::Index,
1690 ExprKind::Path(..) => ExprPrecedence::Path,
1691 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1692 ExprKind::Break(..) => ExprPrecedence::Break,
1693 ExprKind::Continue(..) => ExprPrecedence::Continue,
1694 ExprKind::Ret(..) => ExprPrecedence::Ret,
1695 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1696 ExprKind::Struct(..) => ExprPrecedence::Struct,
1697 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1698 ExprKind::Yield(..) => ExprPrecedence::Yield,
1699 ExprKind::Err => ExprPrecedence::Err,
1703 /// Whether this looks like a place expr, without checking for deref
1705 /// This will return `true` in some potentially surprising cases such as
1706 /// `CONSTANT.field`.
1707 pub fn is_syntactic_place_expr(&self) -> bool {
1708 self.is_place_expr(|_| true)
1711 /// Whether this is a place expression.
1713 /// `allow_projections_from` should return `true` if indexing a field or index expression based
1714 /// on the given expression should be considered a place expression.
1715 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1717 ExprKind::Path(QPath::Resolved(_, ref path)) => {
1718 matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static(_), _) | Res::Err)
1721 // Type ascription inherits its place expression kind from its
1723 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1724 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1726 ExprKind::Unary(UnOp::Deref, _) => true,
1728 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1729 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1732 // Lang item paths cannot currently be local variables or statics.
1733 ExprKind::Path(QPath::LangItem(..)) => false,
1735 // Partially qualified paths in expressions can only legally
1736 // refer to associated items which are always rvalues.
1737 ExprKind::Path(QPath::TypeRelative(..))
1738 | ExprKind::Call(..)
1739 | ExprKind::MethodCall(..)
1740 | ExprKind::Struct(..)
1743 | ExprKind::Match(..)
1744 | ExprKind::Closure { .. }
1745 | ExprKind::Block(..)
1746 | ExprKind::Repeat(..)
1747 | ExprKind::Array(..)
1748 | ExprKind::Break(..)
1749 | ExprKind::Continue(..)
1752 | ExprKind::Loop(..)
1753 | ExprKind::Assign(..)
1754 | ExprKind::InlineAsm(..)
1755 | ExprKind::AssignOp(..)
1757 | ExprKind::ConstBlock(..)
1758 | ExprKind::Unary(..)
1760 | ExprKind::AddrOf(..)
1761 | ExprKind::Binary(..)
1762 | ExprKind::Yield(..)
1763 | ExprKind::Cast(..)
1764 | ExprKind::DropTemps(..)
1765 | ExprKind::Err => false,
1769 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1770 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1771 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1772 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1773 /// beyond remembering to call this function before doing analysis on it.
1774 pub fn peel_drop_temps(&self) -> &Self {
1775 let mut expr = self;
1776 while let ExprKind::DropTemps(inner) = &expr.kind {
1782 pub fn peel_blocks(&self) -> &Self {
1783 let mut expr = self;
1784 while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind {
1790 pub fn peel_borrows(&self) -> &Self {
1791 let mut expr = self;
1792 while let ExprKind::AddrOf(.., inner) = &expr.kind {
1798 pub fn can_have_side_effects(&self) -> bool {
1799 match self.peel_drop_temps().kind {
1800 ExprKind::Path(_) | ExprKind::Lit(_) => false,
1801 ExprKind::Type(base, _)
1802 | ExprKind::Unary(_, base)
1803 | ExprKind::Field(base, _)
1804 | ExprKind::Index(base, _)
1805 | ExprKind::AddrOf(.., base)
1806 | ExprKind::Cast(base, _) => {
1807 // This isn't exactly true for `Index` and all `Unary`, but we are using this
1808 // method exclusively for diagnostics and there's a *cultural* pressure against
1809 // them being used only for its side-effects.
1810 base.can_have_side_effects()
1812 ExprKind::Struct(_, fields, init) => fields
1814 .map(|field| field.expr)
1815 .chain(init.into_iter())
1816 .all(|e| e.can_have_side_effects()),
1818 ExprKind::Array(args)
1819 | ExprKind::Tup(args)
1823 ExprKind::Path(QPath::Resolved(
1825 Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. },
1830 ) => args.iter().all(|arg| arg.can_have_side_effects()),
1832 | ExprKind::Match(..)
1833 | ExprKind::MethodCall(..)
1834 | ExprKind::Call(..)
1835 | ExprKind::Closure { .. }
1836 | ExprKind::Block(..)
1837 | ExprKind::Repeat(..)
1838 | ExprKind::Break(..)
1839 | ExprKind::Continue(..)
1842 | ExprKind::Loop(..)
1843 | ExprKind::Assign(..)
1844 | ExprKind::InlineAsm(..)
1845 | ExprKind::AssignOp(..)
1846 | ExprKind::ConstBlock(..)
1848 | ExprKind::Binary(..)
1849 | ExprKind::Yield(..)
1850 | ExprKind::DropTemps(..)
1851 | ExprKind::Err => true,
1855 /// To a first-order approximation, is this a pattern?
1856 pub fn is_approximately_pattern(&self) -> bool {
1859 | ExprKind::Array(_)
1860 | ExprKind::Call(..)
1864 | ExprKind::Struct(..) => true,
1869 pub fn method_ident(&self) -> Option<Ident> {
1871 ExprKind::MethodCall(receiver_method, ..) => Some(receiver_method.ident),
1872 ExprKind::Unary(_, expr) | ExprKind::AddrOf(.., expr) => expr.method_ident(),
1878 /// Checks if the specified expression is a built-in range literal.
1879 /// (See: `LoweringContext::lower_expr()`).
1880 pub fn is_range_literal(expr: &Expr<'_>) -> bool {
1882 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1883 ExprKind::Struct(ref qpath, _, _) => matches!(
1888 | LangItem::RangeFrom
1889 | LangItem::RangeFull
1890 | LangItem::RangeToInclusive,
1895 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1896 ExprKind::Call(ref func, _) => {
1897 matches!(func.kind, ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, ..)))
1904 #[derive(Debug, HashStable_Generic)]
1905 pub enum ExprKind<'hir> {
1906 /// A `box x` expression.
1907 Box(&'hir Expr<'hir>),
1908 /// Allow anonymous constants from an inline `const` block
1909 ConstBlock(AnonConst),
1910 /// An array (e.g., `[a, b, c, d]`).
1911 Array(&'hir [Expr<'hir>]),
1912 /// A function call.
1914 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1915 /// and the second field is the list of arguments.
1916 /// This also represents calling the constructor of
1917 /// tuple-like ADTs such as tuple structs and enum variants.
1918 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1919 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1921 /// The `PathSegment` represents the method name and its generic arguments
1922 /// (within the angle brackets).
1923 /// The `&Expr` is the expression that evaluates
1924 /// to the object on which the method is being called on (the receiver),
1925 /// and the `&[Expr]` is the rest of the arguments.
1926 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1927 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, x, [a, b, c, d], span)`.
1928 /// The final `Span` represents the span of the function and arguments
1929 /// (e.g. `foo::<Bar, Baz>(a, b, c, d)` in `x.foo::<Bar, Baz>(a, b, c, d)`
1931 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1932 /// the `hir_id` of the `MethodCall` node itself.
1934 /// [`type_dependent_def_id`]: ../../rustc_middle/ty/struct.TypeckResults.html#method.type_dependent_def_id
1935 MethodCall(&'hir PathSegment<'hir>, &'hir Expr<'hir>, &'hir [Expr<'hir>], Span),
1936 /// A tuple (e.g., `(a, b, c, d)`).
1937 Tup(&'hir [Expr<'hir>]),
1938 /// A binary operation (e.g., `a + b`, `a * b`).
1939 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1940 /// A unary operation (e.g., `!x`, `*x`).
1941 Unary(UnOp, &'hir Expr<'hir>),
1942 /// A literal (e.g., `1`, `"foo"`).
1944 /// A cast (e.g., `foo as f64`).
1945 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1946 /// A type reference (e.g., `Foo`).
1947 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1948 /// Wraps the expression in a terminating scope.
1949 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1951 /// This construct only exists to tweak the drop order in HIR lowering.
1952 /// An example of that is the desugaring of `for` loops.
1953 DropTemps(&'hir Expr<'hir>),
1954 /// A `let $pat = $expr` expression.
1956 /// These are not `Local` and only occur as expressions.
1957 /// The `let Some(x) = foo()` in `if let Some(x) = foo()` is an example of `Let(..)`.
1958 Let(&'hir Let<'hir>),
1959 /// An `if` block, with an optional else block.
1961 /// I.e., `if <expr> { <expr> } else { <expr> }`.
1962 If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
1963 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1965 /// I.e., `'label: loop { <block> }`.
1967 /// The `Span` is the loop header (`for x in y`/`while let pat = expr`).
1968 Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span),
1969 /// A `match` block, with a source that indicates whether or not it is
1970 /// the result of a desugaring, and if so, which kind.
1971 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1972 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1974 /// The `Span` is the argument block `|...|`.
1976 /// This may also be a generator literal or an `async block` as indicated by the
1977 /// `Option<Movability>`.
1978 Closure(&'hir Closure<'hir>),
1979 /// A block (e.g., `'label: { ... }`).
1980 Block(&'hir Block<'hir>, Option<Label>),
1982 /// An assignment (e.g., `a = foo()`).
1983 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1984 /// An assignment with an operator.
1987 AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1988 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1989 Field(&'hir Expr<'hir>, Ident),
1990 /// An indexing operation (`foo[2]`).
1991 Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1993 /// Path to a definition, possibly containing lifetime or type parameters.
1996 /// A referencing operation (i.e., `&a` or `&mut a`).
1997 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1998 /// A `break`, with an optional label to break.
1999 Break(Destination, Option<&'hir Expr<'hir>>),
2000 /// A `continue`, with an optional label.
2001 Continue(Destination),
2002 /// A `return`, with an optional value to be returned.
2003 Ret(Option<&'hir Expr<'hir>>),
2005 /// Inline assembly (from `asm!`), with its outputs and inputs.
2006 InlineAsm(&'hir InlineAsm<'hir>),
2008 /// A struct or struct-like variant literal expression.
2010 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
2011 /// where `base` is the `Option<Expr>`.
2012 Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], Option<&'hir Expr<'hir>>),
2014 /// An array literal constructed from one repeated element.
2016 /// E.g., `[1; 5]`. The first expression is the element
2017 /// to be repeated; the second is the number of times to repeat it.
2018 Repeat(&'hir Expr<'hir>, ArrayLen),
2020 /// A suspension point for generators (i.e., `yield <expr>`).
2021 Yield(&'hir Expr<'hir>, YieldSource),
2023 /// A placeholder for an expression that wasn't syntactically well formed in some way.
2027 /// Represents an optionally `Self`-qualified value/type path or associated extension.
2029 /// To resolve the path to a `DefId`, call [`qpath_res`].
2031 /// [`qpath_res`]: ../../rustc_middle/ty/struct.TypeckResults.html#method.qpath_res
2032 #[derive(Debug, HashStable_Generic)]
2033 pub enum QPath<'hir> {
2034 /// Path to a definition, optionally "fully-qualified" with a `Self`
2035 /// type, if the path points to an associated item in a trait.
2037 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
2038 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
2039 /// even though they both have the same two-segment `Clone::clone` `Path`.
2040 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
2042 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
2043 /// Will be resolved by type-checking to an associated item.
2045 /// UFCS source paths can desugar into this, with `Vec::new` turning into
2046 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
2047 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
2048 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
2050 /// Reference to a `#[lang = "foo"]` item. `HirId` of the inner expr.
2051 LangItem(LangItem, Span, Option<HirId>),
2054 impl<'hir> QPath<'hir> {
2055 /// Returns the span of this `QPath`.
2056 pub fn span(&self) -> Span {
2058 QPath::Resolved(_, path) => path.span,
2059 QPath::TypeRelative(qself, ps) => qself.span.to(ps.ident.span),
2060 QPath::LangItem(_, span, _) => span,
2064 /// Returns the span of the qself of this `QPath`. For example, `()` in
2065 /// `<() as Trait>::method`.
2066 pub fn qself_span(&self) -> Span {
2068 QPath::Resolved(_, path) => path.span,
2069 QPath::TypeRelative(qself, _) => qself.span,
2070 QPath::LangItem(_, span, _) => span,
2074 /// Returns the span of the last segment of this `QPath`. For example, `method` in
2075 /// `<() as Trait>::method`.
2076 pub fn last_segment_span(&self) -> Span {
2078 QPath::Resolved(_, path) => path.segments.last().unwrap().ident.span,
2079 QPath::TypeRelative(_, segment) => segment.ident.span,
2080 QPath::LangItem(_, span, _) => span,
2085 /// Hints at the original code for a let statement.
2086 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2087 pub enum LocalSource {
2088 /// A `match _ { .. }`.
2090 /// When lowering async functions, we create locals within the `async move` so that
2091 /// all parameters are dropped after the future is polled.
2093 /// ```ignore (pseudo-Rust)
2094 /// async fn foo(<pattern> @ x: Type) {
2096 /// let <pattern> = x;
2101 /// A desugared `<expr>.await`.
2103 /// A desugared `expr = expr`, where the LHS is a tuple, struct or array.
2104 /// The span is that of the `=` sign.
2105 AssignDesugar(Span),
2108 /// Hints at the original code for a `match _ { .. }`.
2109 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
2110 #[derive(HashStable_Generic)]
2111 pub enum MatchSource {
2112 /// A `match _ { .. }`.
2114 /// A desugared `for _ in _ { .. }` loop.
2116 /// A desugared `?` operator.
2118 /// A desugared `<expr>.await`.
2124 pub const fn name(self) -> &'static str {
2128 ForLoopDesugar => "for",
2130 AwaitDesugar => ".await",
2135 /// The loop type that yielded an `ExprKind::Loop`.
2136 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2137 pub enum LoopSource {
2138 /// A `loop { .. }` loop.
2140 /// A `while _ { .. }` loop.
2142 /// A `for _ in _ { .. }` loop.
2147 pub fn name(self) -> &'static str {
2149 LoopSource::Loop => "loop",
2150 LoopSource::While => "while",
2151 LoopSource::ForLoop => "for",
2156 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2157 pub enum LoopIdError {
2159 UnlabeledCfInWhileCondition,
2163 impl fmt::Display for LoopIdError {
2164 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2165 f.write_str(match self {
2166 LoopIdError::OutsideLoopScope => "not inside loop scope",
2167 LoopIdError::UnlabeledCfInWhileCondition => {
2168 "unlabeled control flow (break or continue) in while condition"
2170 LoopIdError::UnresolvedLabel => "label not found",
2175 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2176 pub struct Destination {
2177 /// This is `Some(_)` iff there is an explicit user-specified 'label
2178 pub label: Option<Label>,
2180 /// These errors are caught and then reported during the diagnostics pass in
2181 /// `librustc_passes/loops.rs`
2182 pub target_id: Result<HirId, LoopIdError>,
2185 /// The yield kind that caused an `ExprKind::Yield`.
2186 #[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
2187 pub enum YieldSource {
2188 /// An `<expr>.await`.
2189 Await { expr: Option<HirId> },
2190 /// A plain `yield`.
2195 pub fn is_await(&self) -> bool {
2196 matches!(self, YieldSource::Await { .. })
2200 impl fmt::Display for YieldSource {
2201 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2202 f.write_str(match self {
2203 YieldSource::Await { .. } => "`await`",
2204 YieldSource::Yield => "`yield`",
2209 impl From<GeneratorKind> for YieldSource {
2210 fn from(kind: GeneratorKind) -> Self {
2212 // Guess based on the kind of the current generator.
2213 GeneratorKind::Gen => Self::Yield,
2214 GeneratorKind::Async(_) => Self::Await { expr: None },
2219 // N.B., if you change this, you'll probably want to change the corresponding
2220 // type structure in middle/ty.rs as well.
2221 #[derive(Debug, HashStable_Generic)]
2222 pub struct MutTy<'hir> {
2223 pub ty: &'hir Ty<'hir>,
2224 pub mutbl: Mutability,
2227 /// Represents a function's signature in a trait declaration,
2228 /// trait implementation, or a free function.
2229 #[derive(Debug, HashStable_Generic)]
2230 pub struct FnSig<'hir> {
2231 pub header: FnHeader,
2232 pub decl: &'hir FnDecl<'hir>,
2236 // The bodies for items are stored "out of line", in a separate
2237 // hashmap in the `Crate`. Here we just record the hir-id of the item
2238 // so it can fetched later.
2239 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2240 pub struct TraitItemId {
2241 pub owner_id: OwnerId,
2246 pub fn hir_id(&self) -> HirId {
2247 // Items are always HIR owners.
2248 HirId::make_owner(self.owner_id.def_id)
2252 /// Represents an item declaration within a trait declaration,
2253 /// possibly including a default implementation. A trait item is
2254 /// either required (meaning it doesn't have an implementation, just a
2255 /// signature) or provided (meaning it has a default implementation).
2256 #[derive(Debug, HashStable_Generic)]
2257 pub struct TraitItem<'hir> {
2259 pub owner_id: OwnerId,
2260 pub generics: &'hir Generics<'hir>,
2261 pub kind: TraitItemKind<'hir>,
2263 pub defaultness: Defaultness,
2266 impl TraitItem<'_> {
2268 pub fn hir_id(&self) -> HirId {
2269 // Items are always HIR owners.
2270 HirId::make_owner(self.owner_id.def_id)
2273 pub fn trait_item_id(&self) -> TraitItemId {
2274 TraitItemId { owner_id: self.owner_id }
2278 /// Represents a trait method's body (or just argument names).
2279 #[derive(Encodable, Debug, HashStable_Generic)]
2280 pub enum TraitFn<'hir> {
2281 /// No default body in the trait, just a signature.
2282 Required(&'hir [Ident]),
2284 /// Both signature and body are provided in the trait.
2288 /// Represents a trait method or associated constant or type
2289 #[derive(Debug, HashStable_Generic)]
2290 pub enum TraitItemKind<'hir> {
2291 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
2292 Const(&'hir Ty<'hir>, Option<BodyId>),
2293 /// An associated function with an optional body.
2294 Fn(FnSig<'hir>, TraitFn<'hir>),
2295 /// An associated type with (possibly empty) bounds and optional concrete
2297 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
2300 // The bodies for items are stored "out of line", in a separate
2301 // hashmap in the `Crate`. Here we just record the hir-id of the item
2302 // so it can fetched later.
2303 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2304 pub struct ImplItemId {
2305 pub owner_id: OwnerId,
2310 pub fn hir_id(&self) -> HirId {
2311 // Items are always HIR owners.
2312 HirId::make_owner(self.owner_id.def_id)
2316 /// Represents anything within an `impl` block.
2317 #[derive(Debug, HashStable_Generic)]
2318 pub struct ImplItem<'hir> {
2320 pub owner_id: OwnerId,
2321 pub generics: &'hir Generics<'hir>,
2322 pub kind: ImplItemKind<'hir>,
2323 pub defaultness: Defaultness,
2330 pub fn hir_id(&self) -> HirId {
2331 // Items are always HIR owners.
2332 HirId::make_owner(self.owner_id.def_id)
2335 pub fn impl_item_id(&self) -> ImplItemId {
2336 ImplItemId { owner_id: self.owner_id }
2340 /// Represents various kinds of content within an `impl`.
2341 #[derive(Debug, HashStable_Generic)]
2342 pub enum ImplItemKind<'hir> {
2343 /// An associated constant of the given type, set to the constant result
2344 /// of the expression.
2345 Const(&'hir Ty<'hir>, BodyId),
2346 /// An associated function implementation with the given signature and body.
2347 Fn(FnSig<'hir>, BodyId),
2348 /// An associated type.
2349 Type(&'hir Ty<'hir>),
2352 /// The name of the associated type for `Fn` return types.
2353 pub const FN_OUTPUT_NAME: Symbol = sym::Output;
2355 /// Bind a type to an associated type (i.e., `A = Foo`).
2357 /// Bindings like `A: Debug` are represented as a special type `A =
2358 /// $::Debug` that is understood by the astconv code.
2360 /// FIXME(alexreg): why have a separate type for the binding case,
2361 /// wouldn't it be better to make the `ty` field an enum like the
2364 /// ```ignore (pseudo-rust)
2365 /// enum TypeBindingKind {
2370 #[derive(Debug, HashStable_Generic)]
2371 pub struct TypeBinding<'hir> {
2374 pub gen_args: &'hir GenericArgs<'hir>,
2375 pub kind: TypeBindingKind<'hir>,
2379 #[derive(Debug, HashStable_Generic)]
2380 pub enum Term<'hir> {
2385 impl<'hir> From<&'hir Ty<'hir>> for Term<'hir> {
2386 fn from(ty: &'hir Ty<'hir>) -> Self {
2391 impl<'hir> From<AnonConst> for Term<'hir> {
2392 fn from(c: AnonConst) -> Self {
2397 // Represents the two kinds of type bindings.
2398 #[derive(Debug, HashStable_Generic)]
2399 pub enum TypeBindingKind<'hir> {
2400 /// E.g., `Foo<Bar: Send>`.
2401 Constraint { bounds: &'hir [GenericBound<'hir>] },
2402 /// E.g., `Foo<Bar = ()>`, `Foo<Bar = ()>`
2403 Equality { term: Term<'hir> },
2406 impl TypeBinding<'_> {
2407 pub fn ty(&self) -> &Ty<'_> {
2409 TypeBindingKind::Equality { term: Term::Ty(ref ty) } => ty,
2410 _ => panic!("expected equality type binding for parenthesized generic args"),
2413 pub fn opt_const(&self) -> Option<&'_ AnonConst> {
2415 TypeBindingKind::Equality { term: Term::Const(ref c) } => Some(c),
2421 #[derive(Debug, HashStable_Generic)]
2422 pub struct Ty<'hir> {
2424 pub kind: TyKind<'hir>,
2428 impl<'hir> Ty<'hir> {
2429 /// Returns `true` if `param_def_id` matches the `bounded_ty` of this predicate.
2430 pub fn as_generic_param(&self) -> Option<(DefId, Ident)> {
2431 let TyKind::Path(QPath::Resolved(None, path)) = self.kind else {
2434 let [segment] = &path.segments else {
2438 Res::Def(DefKind::TyParam, def_id) | Res::SelfTyParam { trait_: def_id } => {
2439 Some((def_id, segment.ident))
2445 pub fn peel_refs(&self) -> &Self {
2446 let mut final_ty = self;
2447 while let TyKind::Ref(_, MutTy { ty, .. }) = &final_ty.kind {
2453 pub fn find_self_aliases(&self) -> Vec<Span> {
2454 use crate::intravisit::Visitor;
2455 struct MyVisitor(Vec<Span>);
2456 impl<'v> Visitor<'v> for MyVisitor {
2457 fn visit_ty(&mut self, t: &'v Ty<'v>) {
2460 TyKind::Path(QPath::Resolved(
2462 Path { res: crate::def::Res::SelfTyAlias { .. }, .. },
2465 self.0.push(t.span);
2468 crate::intravisit::walk_ty(self, t);
2472 let mut my_visitor = MyVisitor(vec![]);
2473 my_visitor.visit_ty(self);
2478 /// Not represented directly in the AST; referred to by name through a `ty_path`.
2479 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
2480 #[derive(HashStable_Generic)]
2491 /// All of the primitive types
2492 pub const ALL: [Self; 17] = [
2493 // any changes here should also be reflected in `PrimTy::from_name`
2494 Self::Int(IntTy::I8),
2495 Self::Int(IntTy::I16),
2496 Self::Int(IntTy::I32),
2497 Self::Int(IntTy::I64),
2498 Self::Int(IntTy::I128),
2499 Self::Int(IntTy::Isize),
2500 Self::Uint(UintTy::U8),
2501 Self::Uint(UintTy::U16),
2502 Self::Uint(UintTy::U32),
2503 Self::Uint(UintTy::U64),
2504 Self::Uint(UintTy::U128),
2505 Self::Uint(UintTy::Usize),
2506 Self::Float(FloatTy::F32),
2507 Self::Float(FloatTy::F64),
2513 /// Like [`PrimTy::name`], but returns a &str instead of a symbol.
2516 pub fn name_str(self) -> &'static str {
2518 PrimTy::Int(i) => i.name_str(),
2519 PrimTy::Uint(u) => u.name_str(),
2520 PrimTy::Float(f) => f.name_str(),
2521 PrimTy::Str => "str",
2522 PrimTy::Bool => "bool",
2523 PrimTy::Char => "char",
2527 pub fn name(self) -> Symbol {
2529 PrimTy::Int(i) => i.name(),
2530 PrimTy::Uint(u) => u.name(),
2531 PrimTy::Float(f) => f.name(),
2532 PrimTy::Str => sym::str,
2533 PrimTy::Bool => sym::bool,
2534 PrimTy::Char => sym::char,
2538 /// Returns the matching `PrimTy` for a `Symbol` such as "str" or "i32".
2539 /// Returns `None` if no matching type is found.
2540 pub fn from_name(name: Symbol) -> Option<Self> {
2541 let ty = match name {
2542 // any changes here should also be reflected in `PrimTy::ALL`
2543 sym::i8 => Self::Int(IntTy::I8),
2544 sym::i16 => Self::Int(IntTy::I16),
2545 sym::i32 => Self::Int(IntTy::I32),
2546 sym::i64 => Self::Int(IntTy::I64),
2547 sym::i128 => Self::Int(IntTy::I128),
2548 sym::isize => Self::Int(IntTy::Isize),
2549 sym::u8 => Self::Uint(UintTy::U8),
2550 sym::u16 => Self::Uint(UintTy::U16),
2551 sym::u32 => Self::Uint(UintTy::U32),
2552 sym::u64 => Self::Uint(UintTy::U64),
2553 sym::u128 => Self::Uint(UintTy::U128),
2554 sym::usize => Self::Uint(UintTy::Usize),
2555 sym::f32 => Self::Float(FloatTy::F32),
2556 sym::f64 => Self::Float(FloatTy::F64),
2557 sym::bool => Self::Bool,
2558 sym::char => Self::Char,
2559 sym::str => Self::Str,
2566 #[derive(Debug, HashStable_Generic)]
2567 pub struct BareFnTy<'hir> {
2568 pub unsafety: Unsafety,
2570 pub generic_params: &'hir [GenericParam<'hir>],
2571 pub decl: &'hir FnDecl<'hir>,
2572 pub param_names: &'hir [Ident],
2575 #[derive(Debug, HashStable_Generic)]
2576 pub struct OpaqueTy<'hir> {
2577 pub generics: &'hir Generics<'hir>,
2578 pub bounds: GenericBounds<'hir>,
2579 pub origin: OpaqueTyOrigin,
2583 /// From whence the opaque type came.
2584 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2585 pub enum OpaqueTyOrigin {
2587 FnReturn(LocalDefId),
2589 AsyncFn(LocalDefId),
2590 /// type aliases: `type Foo = impl Trait;`
2594 /// The various kinds of types recognized by the compiler.
2595 #[derive(Debug, HashStable_Generic)]
2596 pub enum TyKind<'hir> {
2597 /// A variable length slice (i.e., `[T]`).
2598 Slice(&'hir Ty<'hir>),
2599 /// A fixed length array (i.e., `[T; n]`).
2600 Array(&'hir Ty<'hir>, ArrayLen),
2601 /// A raw pointer (i.e., `*const T` or `*mut T`).
2603 /// A reference (i.e., `&'a T` or `&'a mut T`).
2604 Ref(&'hir Lifetime, MutTy<'hir>),
2605 /// A bare function (e.g., `fn(usize) -> bool`).
2606 BareFn(&'hir BareFnTy<'hir>),
2607 /// The never type (`!`).
2609 /// A tuple (`(A, B, C, D, ...)`).
2610 Tup(&'hir [Ty<'hir>]),
2611 /// A path to a type definition (`module::module::...::Type`), or an
2612 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2614 /// Type parameters may be stored in each `PathSegment`.
2616 /// An opaque type definition itself. This is only used for `impl Trait`.
2618 /// The generic argument list contains the lifetimes (and in the future
2619 /// possibly parameters) that are actually bound on the `impl Trait`.
2621 /// The last parameter specifies whether this opaque appears in a trait definition.
2622 OpaqueDef(ItemId, &'hir [GenericArg<'hir>], bool),
2623 /// A trait object type `Bound1 + Bound2 + Bound3`
2624 /// where `Bound` is a trait or a lifetime.
2625 TraitObject(&'hir [PolyTraitRef<'hir>], &'hir Lifetime, TraitObjectSyntax),
2628 /// `TyKind::Infer` means the type should be inferred instead of it having been
2629 /// specified. This can appear anywhere in a type.
2631 /// Placeholder for a type that has failed to be defined.
2635 #[derive(Debug, HashStable_Generic)]
2636 pub enum InlineAsmOperand<'hir> {
2638 reg: InlineAsmRegOrRegClass,
2639 expr: &'hir Expr<'hir>,
2642 reg: InlineAsmRegOrRegClass,
2644 expr: Option<&'hir Expr<'hir>>,
2647 reg: InlineAsmRegOrRegClass,
2649 expr: &'hir Expr<'hir>,
2652 reg: InlineAsmRegOrRegClass,
2654 in_expr: &'hir Expr<'hir>,
2655 out_expr: Option<&'hir Expr<'hir>>,
2658 anon_const: AnonConst,
2661 anon_const: AnonConst,
2669 impl<'hir> InlineAsmOperand<'hir> {
2670 pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
2672 Self::In { reg, .. }
2673 | Self::Out { reg, .. }
2674 | Self::InOut { reg, .. }
2675 | Self::SplitInOut { reg, .. } => Some(reg),
2676 Self::Const { .. } | Self::SymFn { .. } | Self::SymStatic { .. } => None,
2680 pub fn is_clobber(&self) -> bool {
2683 InlineAsmOperand::Out { reg: InlineAsmRegOrRegClass::Reg(_), late: _, expr: None }
2688 #[derive(Debug, HashStable_Generic)]
2689 pub struct InlineAsm<'hir> {
2690 pub template: &'hir [InlineAsmTemplatePiece],
2691 pub template_strs: &'hir [(Symbol, Option<Symbol>, Span)],
2692 pub operands: &'hir [(InlineAsmOperand<'hir>, Span)],
2693 pub options: InlineAsmOptions,
2694 pub line_spans: &'hir [Span],
2697 /// Represents a parameter in a function header.
2698 #[derive(Debug, HashStable_Generic)]
2699 pub struct Param<'hir> {
2701 pub pat: &'hir Pat<'hir>,
2706 /// Represents the header (not the body) of a function declaration.
2707 #[derive(Debug, HashStable_Generic)]
2708 pub struct FnDecl<'hir> {
2709 /// The types of the function's parameters.
2711 /// Additional argument data is stored in the function's [body](Body::params).
2712 pub inputs: &'hir [Ty<'hir>],
2713 pub output: FnRetTy<'hir>,
2714 pub c_variadic: bool,
2715 /// Does the function have an implicit self?
2716 pub implicit_self: ImplicitSelfKind,
2717 /// Is lifetime elision allowed.
2718 pub lifetime_elision_allowed: bool,
2721 /// Represents what type of implicit self a function has, if any.
2722 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2723 pub enum ImplicitSelfKind {
2724 /// Represents a `fn x(self);`.
2726 /// Represents a `fn x(mut self);`.
2728 /// Represents a `fn x(&self);`.
2730 /// Represents a `fn x(&mut self);`.
2732 /// Represents when a function does not have a self argument or
2733 /// when a function has a `self: X` argument.
2737 impl ImplicitSelfKind {
2738 /// Does this represent an implicit self?
2739 pub fn has_implicit_self(&self) -> bool {
2740 !matches!(*self, ImplicitSelfKind::None)
2744 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable, Debug)]
2745 #[derive(HashStable_Generic)]
2752 pub fn is_async(self) -> bool {
2753 self == IsAsync::Async
2757 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable, HashStable_Generic)]
2758 pub enum Defaultness {
2759 Default { has_value: bool },
2764 pub fn has_value(&self) -> bool {
2766 Defaultness::Default { has_value } => has_value,
2767 Defaultness::Final => true,
2771 pub fn is_final(&self) -> bool {
2772 *self == Defaultness::Final
2775 pub fn is_default(&self) -> bool {
2776 matches!(*self, Defaultness::Default { .. })
2780 #[derive(Debug, HashStable_Generic)]
2781 pub enum FnRetTy<'hir> {
2782 /// Return type is not specified.
2784 /// Functions default to `()` and
2785 /// closures default to inference. Span points to where return
2786 /// type would be inserted.
2787 DefaultReturn(Span),
2788 /// Everything else.
2789 Return(&'hir Ty<'hir>),
2794 pub fn span(&self) -> Span {
2796 Self::DefaultReturn(span) => span,
2797 Self::Return(ref ty) => ty.span,
2802 /// Represents `for<...>` binder before a closure
2803 #[derive(Copy, Clone, Debug, HashStable_Generic)]
2804 pub enum ClosureBinder {
2805 /// Binder is not specified.
2807 /// Binder is specified.
2809 /// Span points to the whole `for<...>`.
2813 #[derive(Encodable, Debug, HashStable_Generic)]
2814 pub struct Mod<'hir> {
2815 pub spans: ModSpans,
2816 pub item_ids: &'hir [ItemId],
2819 #[derive(Copy, Clone, Debug, HashStable_Generic, Encodable)]
2820 pub struct ModSpans {
2821 /// A span from the first token past `{` to the last token until `}`.
2822 /// For `mod foo;`, the inner span ranges from the first token
2823 /// to the last token in the external file.
2824 pub inner_span: Span,
2825 pub inject_use_span: Span,
2828 #[derive(Debug, HashStable_Generic)]
2829 pub struct EnumDef<'hir> {
2830 pub variants: &'hir [Variant<'hir>],
2833 #[derive(Debug, HashStable_Generic)]
2834 pub struct Variant<'hir> {
2835 /// Name of the variant.
2837 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2839 pub def_id: LocalDefId,
2840 /// Fields and constructor id of the variant.
2841 pub data: VariantData<'hir>,
2842 /// Explicit discriminant (e.g., `Foo = 1`).
2843 pub disr_expr: Option<AnonConst>,
2848 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2850 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2851 /// Also produced for each element of a list `use`, e.g.
2852 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2855 /// Glob import, e.g., `use foo::*`.
2858 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2859 /// an additional `use foo::{}` for performing checks such as
2860 /// unstable feature gating. May be removed in the future.
2864 /// References to traits in impls.
2866 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2867 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2868 /// trait being referred to but just a unique `HirId` that serves as a key
2869 /// within the resolution map.
2870 #[derive(Clone, Debug, HashStable_Generic)]
2871 pub struct TraitRef<'hir> {
2872 pub path: &'hir Path<'hir>,
2873 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2874 #[stable_hasher(ignore)]
2875 pub hir_ref_id: HirId,
2879 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2880 pub fn trait_def_id(&self) -> Option<DefId> {
2881 match self.path.res {
2882 Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
2884 _ => unreachable!(),
2889 #[derive(Clone, Debug, HashStable_Generic)]
2890 pub struct PolyTraitRef<'hir> {
2891 /// The `'a` in `for<'a> Foo<&'a T>`.
2892 pub bound_generic_params: &'hir [GenericParam<'hir>],
2894 /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
2895 pub trait_ref: TraitRef<'hir>,
2900 #[derive(Debug, HashStable_Generic)]
2901 pub struct FieldDef<'hir> {
2906 pub def_id: LocalDefId,
2907 pub ty: &'hir Ty<'hir>,
2911 // Still necessary in couple of places
2912 pub fn is_positional(&self) -> bool {
2913 let first = self.ident.as_str().as_bytes()[0];
2914 (b'0'..=b'9').contains(&first)
2918 /// Fields and constructor IDs of enum variants and structs.
2919 #[derive(Debug, HashStable_Generic)]
2920 pub enum VariantData<'hir> {
2921 /// A struct variant.
2923 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2924 Struct(&'hir [FieldDef<'hir>], /* recovered */ bool),
2925 /// A tuple variant.
2927 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2928 Tuple(&'hir [FieldDef<'hir>], HirId, LocalDefId),
2931 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2932 Unit(HirId, LocalDefId),
2935 impl<'hir> VariantData<'hir> {
2936 /// Return the fields of this variant.
2937 pub fn fields(&self) -> &'hir [FieldDef<'hir>] {
2939 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2944 pub fn ctor(&self) -> Option<(CtorKind, HirId, LocalDefId)> {
2946 VariantData::Tuple(_, hir_id, def_id) => Some((CtorKind::Fn, hir_id, def_id)),
2947 VariantData::Unit(hir_id, def_id) => Some((CtorKind::Const, hir_id, def_id)),
2948 VariantData::Struct(..) => None,
2953 pub fn ctor_kind(&self) -> Option<CtorKind> {
2954 self.ctor().map(|(kind, ..)| kind)
2957 /// Return the `HirId` of this variant's constructor, if it has one.
2959 pub fn ctor_hir_id(&self) -> Option<HirId> {
2960 self.ctor().map(|(_, hir_id, _)| hir_id)
2963 /// Return the `LocalDefId` of this variant's constructor, if it has one.
2965 pub fn ctor_def_id(&self) -> Option<LocalDefId> {
2966 self.ctor().map(|(.., def_id)| def_id)
2970 // The bodies for items are stored "out of line", in a separate
2971 // hashmap in the `Crate`. Here we just record the hir-id of the item
2972 // so it can fetched later.
2973 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
2975 pub owner_id: OwnerId,
2980 pub fn hir_id(&self) -> HirId {
2981 // Items are always HIR owners.
2982 HirId::make_owner(self.owner_id.def_id)
2988 /// The name might be a dummy name in case of anonymous items
2989 #[derive(Debug, HashStable_Generic)]
2990 pub struct Item<'hir> {
2992 pub owner_id: OwnerId,
2993 pub kind: ItemKind<'hir>,
3000 pub fn hir_id(&self) -> HirId {
3001 // Items are always HIR owners.
3002 HirId::make_owner(self.owner_id.def_id)
3005 pub fn item_id(&self) -> ItemId {
3006 ItemId { owner_id: self.owner_id }
3010 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
3011 #[derive(Encodable, Decodable, HashStable_Generic)]
3018 pub fn prefix_str(&self) -> &'static str {
3020 Self::Unsafe => "unsafe ",
3026 impl fmt::Display for Unsafety {
3027 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3028 f.write_str(match *self {
3029 Self::Unsafe => "unsafe",
3030 Self::Normal => "normal",
3035 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
3036 #[derive(Encodable, Decodable, HashStable_Generic)]
3037 pub enum Constness {
3042 impl fmt::Display for Constness {
3043 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3044 f.write_str(match *self {
3045 Self::Const => "const",
3046 Self::NotConst => "non-const",
3051 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
3052 pub struct FnHeader {
3053 pub unsafety: Unsafety,
3054 pub constness: Constness,
3055 pub asyncness: IsAsync,
3060 pub fn is_async(&self) -> bool {
3061 matches!(&self.asyncness, IsAsync::Async)
3064 pub fn is_const(&self) -> bool {
3065 matches!(&self.constness, Constness::Const)
3068 pub fn is_unsafe(&self) -> bool {
3069 matches!(&self.unsafety, Unsafety::Unsafe)
3073 #[derive(Debug, HashStable_Generic)]
3074 pub enum ItemKind<'hir> {
3075 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
3077 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
3078 ExternCrate(Option<Symbol>),
3080 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
3084 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
3085 Use(&'hir UsePath<'hir>, UseKind),
3087 /// A `static` item.
3088 Static(&'hir Ty<'hir>, Mutability, BodyId),
3090 Const(&'hir Ty<'hir>, BodyId),
3091 /// A function declaration.
3092 Fn(FnSig<'hir>, &'hir Generics<'hir>, BodyId),
3093 /// A MBE macro definition (`macro_rules!` or `macro`).
3094 Macro(ast::MacroDef, MacroKind),
3096 Mod(&'hir Mod<'hir>),
3097 /// An external module, e.g. `extern { .. }`.
3098 ForeignMod { abi: Abi, items: &'hir [ForeignItemRef] },
3099 /// Module-level inline assembly (from `global_asm!`).
3100 GlobalAsm(&'hir InlineAsm<'hir>),
3101 /// A type alias, e.g., `type Foo = Bar<u8>`.
3102 TyAlias(&'hir Ty<'hir>, &'hir Generics<'hir>),
3103 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
3104 OpaqueTy(OpaqueTy<'hir>),
3105 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
3106 Enum(EnumDef<'hir>, &'hir Generics<'hir>),
3107 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
3108 Struct(VariantData<'hir>, &'hir Generics<'hir>),
3109 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
3110 Union(VariantData<'hir>, &'hir Generics<'hir>),
3111 /// A trait definition.
3112 Trait(IsAuto, Unsafety, &'hir Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
3114 TraitAlias(&'hir Generics<'hir>, GenericBounds<'hir>),
3116 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
3117 Impl(&'hir Impl<'hir>),
3120 #[derive(Debug, HashStable_Generic)]
3121 pub struct Impl<'hir> {
3122 pub unsafety: Unsafety,
3123 pub polarity: ImplPolarity,
3124 pub defaultness: Defaultness,
3125 // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata
3126 // decoding as `Span`s cannot be decoded when a `Session` is not available.
3127 pub defaultness_span: Option<Span>,
3128 pub constness: Constness,
3129 pub generics: &'hir Generics<'hir>,
3131 /// The trait being implemented, if any.
3132 pub of_trait: Option<TraitRef<'hir>>,
3134 pub self_ty: &'hir Ty<'hir>,
3135 pub items: &'hir [ImplItemRef],
3139 pub fn generics(&self) -> Option<&Generics<'_>> {
3141 ItemKind::Fn(_, ref generics, _)
3142 | ItemKind::TyAlias(_, ref generics)
3143 | ItemKind::OpaqueTy(OpaqueTy { ref generics, .. })
3144 | ItemKind::Enum(_, ref generics)
3145 | ItemKind::Struct(_, ref generics)
3146 | ItemKind::Union(_, ref generics)
3147 | ItemKind::Trait(_, _, ref generics, _, _)
3148 | ItemKind::TraitAlias(ref generics, _)
3149 | ItemKind::Impl(Impl { ref generics, .. }) => generics,
3154 pub fn descr(&self) -> &'static str {
3156 ItemKind::ExternCrate(..) => "extern crate",
3157 ItemKind::Use(..) => "`use` import",
3158 ItemKind::Static(..) => "static item",
3159 ItemKind::Const(..) => "constant item",
3160 ItemKind::Fn(..) => "function",
3161 ItemKind::Macro(..) => "macro",
3162 ItemKind::Mod(..) => "module",
3163 ItemKind::ForeignMod { .. } => "extern block",
3164 ItemKind::GlobalAsm(..) => "global asm item",
3165 ItemKind::TyAlias(..) => "type alias",
3166 ItemKind::OpaqueTy(..) => "opaque type",
3167 ItemKind::Enum(..) => "enum",
3168 ItemKind::Struct(..) => "struct",
3169 ItemKind::Union(..) => "union",
3170 ItemKind::Trait(..) => "trait",
3171 ItemKind::TraitAlias(..) => "trait alias",
3172 ItemKind::Impl(..) => "implementation",
3177 /// A reference from an trait to one of its associated items. This
3178 /// contains the item's id, naturally, but also the item's name and
3179 /// some other high-level details (like whether it is an associated
3180 /// type or method, and whether it is public). This allows other
3181 /// passes to find the impl they want without loading the ID (which
3182 /// means fewer edges in the incremental compilation graph).
3183 #[derive(Encodable, Debug, HashStable_Generic)]
3184 pub struct TraitItemRef {
3185 pub id: TraitItemId,
3187 pub kind: AssocItemKind,
3191 /// A reference from an impl to one of its associated items. This
3192 /// contains the item's ID, naturally, but also the item's name and
3193 /// some other high-level details (like whether it is an associated
3194 /// type or method, and whether it is public). This allows other
3195 /// passes to find the impl they want without loading the ID (which
3196 /// means fewer edges in the incremental compilation graph).
3197 #[derive(Debug, HashStable_Generic)]
3198 pub struct ImplItemRef {
3201 pub kind: AssocItemKind,
3203 /// When we are in a trait impl, link to the trait-item's id.
3204 pub trait_item_def_id: Option<DefId>,
3207 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
3208 pub enum AssocItemKind {
3210 Fn { has_self: bool },
3214 // The bodies for items are stored "out of line", in a separate
3215 // hashmap in the `Crate`. Here we just record the hir-id of the item
3216 // so it can fetched later.
3217 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3218 pub struct ForeignItemId {
3219 pub owner_id: OwnerId,
3222 impl ForeignItemId {
3224 pub fn hir_id(&self) -> HirId {
3225 // Items are always HIR owners.
3226 HirId::make_owner(self.owner_id.def_id)
3230 /// A reference from a foreign block to one of its items. This
3231 /// contains the item's ID, naturally, but also the item's name and
3232 /// some other high-level details (like whether it is an associated
3233 /// type or method, and whether it is public). This allows other
3234 /// passes to find the impl they want without loading the ID (which
3235 /// means fewer edges in the incremental compilation graph).
3236 #[derive(Debug, HashStable_Generic)]
3237 pub struct ForeignItemRef {
3238 pub id: ForeignItemId,
3243 #[derive(Debug, HashStable_Generic)]
3244 pub struct ForeignItem<'hir> {
3246 pub kind: ForeignItemKind<'hir>,
3247 pub owner_id: OwnerId,
3252 impl ForeignItem<'_> {
3254 pub fn hir_id(&self) -> HirId {
3255 // Items are always HIR owners.
3256 HirId::make_owner(self.owner_id.def_id)
3259 pub fn foreign_item_id(&self) -> ForeignItemId {
3260 ForeignItemId { owner_id: self.owner_id }
3264 /// An item within an `extern` block.
3265 #[derive(Debug, HashStable_Generic)]
3266 pub enum ForeignItemKind<'hir> {
3267 /// A foreign function.
3268 Fn(&'hir FnDecl<'hir>, &'hir [Ident], &'hir Generics<'hir>),
3269 /// A foreign static item (`static ext: u8`).
3270 Static(&'hir Ty<'hir>, Mutability),
3275 /// A variable captured by a closure.
3276 #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)]
3278 /// First span where it is accessed (there can be multiple).
3282 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
3283 // has length > 0 if the trait is found through an chain of imports, starting with the
3284 // import/use statement in the scope where the trait is used.
3285 #[derive(Encodable, Decodable, Clone, Debug, HashStable_Generic)]
3286 pub struct TraitCandidate {
3288 pub import_ids: SmallVec<[LocalDefId; 1]>,
3291 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3292 pub enum OwnerNode<'hir> {
3293 Item(&'hir Item<'hir>),
3294 ForeignItem(&'hir ForeignItem<'hir>),
3295 TraitItem(&'hir TraitItem<'hir>),
3296 ImplItem(&'hir ImplItem<'hir>),
3297 Crate(&'hir Mod<'hir>),
3300 impl<'hir> OwnerNode<'hir> {
3301 pub fn ident(&self) -> Option<Ident> {
3303 OwnerNode::Item(Item { ident, .. })
3304 | OwnerNode::ForeignItem(ForeignItem { ident, .. })
3305 | OwnerNode::ImplItem(ImplItem { ident, .. })
3306 | OwnerNode::TraitItem(TraitItem { ident, .. }) => Some(*ident),
3307 OwnerNode::Crate(..) => None,
3311 pub fn span(&self) -> Span {
3313 OwnerNode::Item(Item { span, .. })
3314 | OwnerNode::ForeignItem(ForeignItem { span, .. })
3315 | OwnerNode::ImplItem(ImplItem { span, .. })
3316 | OwnerNode::TraitItem(TraitItem { span, .. }) => *span,
3317 OwnerNode::Crate(Mod { spans: ModSpans { inner_span, .. }, .. }) => *inner_span,
3321 pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
3323 OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3324 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3325 | OwnerNode::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3326 OwnerNode::ForeignItem(ForeignItem {
3327 kind: ForeignItemKind::Fn(fn_decl, _, _),
3329 }) => Some(fn_decl),
3334 pub fn body_id(&self) -> Option<BodyId> {
3336 OwnerNode::TraitItem(TraitItem {
3337 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3340 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3341 | OwnerNode::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3346 pub fn generics(self) -> Option<&'hir Generics<'hir>> {
3347 Node::generics(self.into())
3350 pub fn def_id(self) -> OwnerId {
3352 OwnerNode::Item(Item { owner_id, .. })
3353 | OwnerNode::TraitItem(TraitItem { owner_id, .. })
3354 | OwnerNode::ImplItem(ImplItem { owner_id, .. })
3355 | OwnerNode::ForeignItem(ForeignItem { owner_id, .. }) => *owner_id,
3356 OwnerNode::Crate(..) => crate::CRATE_HIR_ID.owner,
3360 pub fn expect_item(self) -> &'hir Item<'hir> {
3362 OwnerNode::Item(n) => n,
3367 pub fn expect_foreign_item(self) -> &'hir ForeignItem<'hir> {
3369 OwnerNode::ForeignItem(n) => n,
3374 pub fn expect_impl_item(self) -> &'hir ImplItem<'hir> {
3376 OwnerNode::ImplItem(n) => n,
3381 pub fn expect_trait_item(self) -> &'hir TraitItem<'hir> {
3383 OwnerNode::TraitItem(n) => n,
3389 impl<'hir> Into<OwnerNode<'hir>> for &'hir Item<'hir> {
3390 fn into(self) -> OwnerNode<'hir> {
3391 OwnerNode::Item(self)
3395 impl<'hir> Into<OwnerNode<'hir>> for &'hir ForeignItem<'hir> {
3396 fn into(self) -> OwnerNode<'hir> {
3397 OwnerNode::ForeignItem(self)
3401 impl<'hir> Into<OwnerNode<'hir>> for &'hir ImplItem<'hir> {
3402 fn into(self) -> OwnerNode<'hir> {
3403 OwnerNode::ImplItem(self)
3407 impl<'hir> Into<OwnerNode<'hir>> for &'hir TraitItem<'hir> {
3408 fn into(self) -> OwnerNode<'hir> {
3409 OwnerNode::TraitItem(self)
3413 impl<'hir> Into<Node<'hir>> for OwnerNode<'hir> {
3414 fn into(self) -> Node<'hir> {
3416 OwnerNode::Item(n) => Node::Item(n),
3417 OwnerNode::ForeignItem(n) => Node::ForeignItem(n),
3418 OwnerNode::ImplItem(n) => Node::ImplItem(n),
3419 OwnerNode::TraitItem(n) => Node::TraitItem(n),
3420 OwnerNode::Crate(n) => Node::Crate(n),
3425 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3426 pub enum Node<'hir> {
3427 Param(&'hir Param<'hir>),
3428 Item(&'hir Item<'hir>),
3429 ForeignItem(&'hir ForeignItem<'hir>),
3430 TraitItem(&'hir TraitItem<'hir>),
3431 ImplItem(&'hir ImplItem<'hir>),
3432 Variant(&'hir Variant<'hir>),
3433 Field(&'hir FieldDef<'hir>),
3434 AnonConst(&'hir AnonConst),
3435 Expr(&'hir Expr<'hir>),
3436 ExprField(&'hir ExprField<'hir>),
3437 Stmt(&'hir Stmt<'hir>),
3438 PathSegment(&'hir PathSegment<'hir>),
3440 TypeBinding(&'hir TypeBinding<'hir>),
3441 TraitRef(&'hir TraitRef<'hir>),
3442 Pat(&'hir Pat<'hir>),
3443 PatField(&'hir PatField<'hir>),
3444 Arm(&'hir Arm<'hir>),
3445 Block(&'hir Block<'hir>),
3446 Local(&'hir Local<'hir>),
3448 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
3449 /// with synthesized constructors.
3450 Ctor(&'hir VariantData<'hir>),
3452 Lifetime(&'hir Lifetime),
3453 GenericParam(&'hir GenericParam<'hir>),
3455 Crate(&'hir Mod<'hir>),
3457 Infer(&'hir InferArg),
3460 impl<'hir> Node<'hir> {
3461 /// Get the identifier of this `Node`, if applicable.
3465 /// Calling `.ident()` on a [`Node::Ctor`] will return `None`
3466 /// because `Ctor`s do not have identifiers themselves.
3467 /// Instead, call `.ident()` on the parent struct/variant, like so:
3469 /// ```ignore (illustrative)
3472 /// .and_then(|ctor_id| tcx.hir().find_parent(ctor_id))
3473 /// .and_then(|parent| parent.ident())
3475 pub fn ident(&self) -> Option<Ident> {
3477 Node::TraitItem(TraitItem { ident, .. })
3478 | Node::ImplItem(ImplItem { ident, .. })
3479 | Node::ForeignItem(ForeignItem { ident, .. })
3480 | Node::Field(FieldDef { ident, .. })
3481 | Node::Variant(Variant { ident, .. })
3482 | Node::Item(Item { ident, .. })
3483 | Node::PathSegment(PathSegment { ident, .. }) => Some(*ident),
3484 Node::Lifetime(lt) => Some(lt.ident),
3485 Node::GenericParam(p) => Some(p.name.ident()),
3486 Node::TypeBinding(b) => Some(b.ident),
3488 | Node::AnonConst(..)
3494 | Node::PatField(..)
3495 | Node::ExprField(..)
3500 | Node::TraitRef(..)
3501 | Node::Infer(..) => None,
3505 pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
3507 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3508 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3509 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3510 Node::Expr(Expr { kind: ExprKind::Closure(Closure { fn_decl, .. }), .. })
3511 | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
3518 pub fn fn_sig(self) -> Option<&'hir FnSig<'hir>> {
3520 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3521 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3522 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig),
3527 pub fn alias_ty(self) -> Option<&'hir Ty<'hir>> {
3529 Node::Item(Item { kind: ItemKind::TyAlias(ty, ..), .. }) => Some(ty),
3534 pub fn body_id(&self) -> Option<BodyId> {
3536 Node::TraitItem(TraitItem {
3537 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3540 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3541 | Node::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3546 pub fn generics(self) -> Option<&'hir Generics<'hir>> {
3548 Node::ForeignItem(ForeignItem {
3549 kind: ForeignItemKind::Fn(_, _, generics), ..
3551 | Node::TraitItem(TraitItem { generics, .. })
3552 | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
3553 Node::Item(item) => item.kind.generics(),
3558 pub fn as_owner(self) -> Option<OwnerNode<'hir>> {
3560 Node::Item(i) => Some(OwnerNode::Item(i)),
3561 Node::ForeignItem(i) => Some(OwnerNode::ForeignItem(i)),
3562 Node::TraitItem(i) => Some(OwnerNode::TraitItem(i)),
3563 Node::ImplItem(i) => Some(OwnerNode::ImplItem(i)),
3564 Node::Crate(i) => Some(OwnerNode::Crate(i)),
3569 pub fn fn_kind(self) -> Option<FnKind<'hir>> {
3571 Node::Item(i) => match i.kind {
3572 ItemKind::Fn(ref sig, ref generics, _) => {
3573 Some(FnKind::ItemFn(i.ident, generics, sig.header))
3577 Node::TraitItem(ti) => match ti.kind {
3578 TraitItemKind::Fn(ref sig, TraitFn::Provided(_)) => {
3579 Some(FnKind::Method(ti.ident, sig))
3583 Node::ImplItem(ii) => match ii.kind {
3584 ImplItemKind::Fn(ref sig, _) => Some(FnKind::Method(ii.ident, sig)),
3587 Node::Expr(e) => match e.kind {
3588 ExprKind::Closure { .. } => Some(FnKind::Closure),
3595 /// Get the fields for the tuple-constructor,
3596 /// if this node is a tuple constructor, otherwise None
3597 pub fn tuple_fields(&self) -> Option<&'hir [FieldDef<'hir>]> {
3598 if let Node::Ctor(&VariantData::Tuple(fields, _, _)) = self { Some(fields) } else { None }
3602 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3603 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
3606 // tidy-alphabetical-start
3607 static_assert_size!(Block<'_>, 48);
3608 static_assert_size!(Body<'_>, 32);
3609 static_assert_size!(Expr<'_>, 64);
3610 static_assert_size!(ExprKind<'_>, 48);
3611 static_assert_size!(FnDecl<'_>, 40);
3612 static_assert_size!(ForeignItem<'_>, 72);
3613 static_assert_size!(ForeignItemKind<'_>, 40);
3614 static_assert_size!(GenericArg<'_>, 32);
3615 static_assert_size!(GenericBound<'_>, 48);
3616 static_assert_size!(Generics<'_>, 56);
3617 static_assert_size!(Impl<'_>, 80);
3618 static_assert_size!(ImplItem<'_>, 80);
3619 static_assert_size!(ImplItemKind<'_>, 32);
3620 static_assert_size!(Item<'_>, 80);
3621 static_assert_size!(ItemKind<'_>, 48);
3622 static_assert_size!(Local<'_>, 64);
3623 static_assert_size!(Param<'_>, 32);
3624 static_assert_size!(Pat<'_>, 72);
3625 static_assert_size!(Path<'_>, 40);
3626 static_assert_size!(PathSegment<'_>, 48);
3627 static_assert_size!(PatKind<'_>, 48);
3628 static_assert_size!(QPath<'_>, 24);
3629 static_assert_size!(Res, 12);
3630 static_assert_size!(Stmt<'_>, 32);
3631 static_assert_size!(StmtKind<'_>, 16);
3632 static_assert_size!(TraitItem<'_>, 80);
3633 static_assert_size!(TraitItemKind<'_>, 40);
3634 static_assert_size!(Ty<'_>, 48);
3635 static_assert_size!(TyKind<'_>, 32);
3636 // tidy-alphabetical-end
3639 fn debug_fn(f: impl Fn(&mut fmt::Formatter<'_>) -> fmt::Result) -> impl fmt::Debug {
3640 struct DebugFn<F>(F);
3641 impl<F: Fn(&mut fmt::Formatter<'_>) -> fmt::Result> fmt::Debug for DebugFn<F> {
3642 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {