1 use crate::def
::{CtorKind, DefKind, Res}
;
2 use crate::def_id
::DefId
;
3 pub(crate) use crate::hir_id
::{HirId, ItemLocalId}
;
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)]
34 /// Either "`'a`", referring to a named lifetime definition,
35 /// or "``" (i.e., `kw::Empty`), for elision placeholders.
37 /// HIR lowering inserts these placeholders in type paths that
38 /// refer to type definitions needing lifetime parameters,
39 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
40 pub name
: LifetimeName
,
43 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
44 #[derive(HashStable_Generic)]
46 /// Some user-given name like `T` or `'x`.
49 /// Synthetic name generated when user elided a lifetime in an impl header.
51 /// E.g., the lifetimes in cases like these:
52 /// ```ignore (fragment)
54 /// impl Foo<'_> for u32
56 /// in that case, we rewrite to
57 /// ```ignore (fragment)
58 /// impl<'f> Foo for &'f u32
59 /// impl<'f> Foo<'f> for u32
61 /// where `'f` is something like `Fresh(0)`. The indices are
62 /// unique per impl, but not necessarily continuous.
65 /// Indicates an illegal name was given and an error has been
66 /// reported (so we should squelch other derived errors). Occurs
67 /// when, e.g., `'_` is used in the wrong place.
72 pub fn ident(&self) -> Ident
{
74 ParamName
::Plain(ident
) => ident
,
75 ParamName
::Fresh
| ParamName
::Error
=> Ident
::with_dummy_span(kw
::UnderscoreLifetime
),
79 pub fn normalize_to_macros_2_0(&self) -> ParamName
{
81 ParamName
::Plain(ident
) => ParamName
::Plain(ident
.normalize_to_macros_2_0()),
82 param_name
=> param_name
,
87 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
88 #[derive(HashStable_Generic)]
89 pub enum LifetimeName
{
90 /// User-given names or fresh (synthetic) names.
91 Param(LocalDefId
, ParamName
),
93 /// Implicit lifetime in a context like `dyn Foo`. This is
94 /// distinguished from implicit lifetimes elsewhere because the
95 /// lifetime that they default to must appear elsewhere within the
96 /// enclosing type. This means that, in an `impl Trait` context, we
97 /// don't have to create a parameter for them. That is, `impl
98 /// Trait<Item = &u32>` expands to an opaque type like `type
99 /// Foo<'a> = impl Trait<Item = &'a u32>`, but `impl Trait<item =
100 /// dyn Bar>` expands to `type Foo = impl Trait<Item = dyn Bar +
101 /// 'static>`. The latter uses `ImplicitObjectLifetimeDefault` so
102 /// that surrounding code knows not to create a lifetime
104 ImplicitObjectLifetimeDefault
,
106 /// Indicates an error during lowering (usually `'_` in wrong place)
107 /// that was already reported.
110 /// User wrote an anonymous lifetime, either `'_` or nothing.
111 /// The semantics of this lifetime should be inferred by typechecking code.
114 /// User wrote `'static`.
119 pub fn ident(&self) -> Ident
{
121 LifetimeName
::ImplicitObjectLifetimeDefault
| LifetimeName
::Error
=> Ident
::empty(),
122 LifetimeName
::Infer
=> Ident
::with_dummy_span(kw
::UnderscoreLifetime
),
123 LifetimeName
::Static
=> Ident
::with_dummy_span(kw
::StaticLifetime
),
124 LifetimeName
::Param(_
, param_name
) => param_name
.ident(),
128 pub fn is_anonymous(&self) -> bool
{
130 LifetimeName
::ImplicitObjectLifetimeDefault
131 | LifetimeName
::Infer
132 | LifetimeName
::Param(_
, ParamName
::Fresh
)
133 | LifetimeName
::Error
=> true,
134 LifetimeName
::Static
| LifetimeName
::Param(..) => false,
138 pub fn is_elided(&self) -> bool
{
140 LifetimeName
::ImplicitObjectLifetimeDefault
| LifetimeName
::Infer
=> true,
142 // It might seem surprising that `Fresh` counts as not *elided*
143 // -- but this is because, as far as the code in the compiler is
144 // concerned -- `Fresh` variants act equivalently to "some fresh name".
145 // They correspond to early-bound regions on an impl, in other words.
146 LifetimeName
::Error
| LifetimeName
::Param(..) | LifetimeName
::Static
=> false,
150 fn is_static(&self) -> bool
{
151 self == &LifetimeName
::Static
154 pub fn normalize_to_macros_2_0(&self) -> LifetimeName
{
156 LifetimeName
::Param(def_id
, param_name
) => {
157 LifetimeName
::Param(def_id
, param_name
.normalize_to_macros_2_0())
159 lifetime_name
=> lifetime_name
,
164 impl fmt
::Display
for Lifetime
{
165 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
166 self.name
.ident().fmt(f
)
171 pub fn is_elided(&self) -> bool
{
172 self.name
.is_elided()
175 pub fn is_static(&self) -> bool
{
176 self.name
.is_static()
180 /// A `Path` is essentially Rust's notion of a name; for instance,
181 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
182 /// along with a bunch of supporting information.
183 #[derive(Debug, HashStable_Generic)]
184 pub struct Path
<'hir
> {
186 /// The resolution for the path.
188 /// The segments in the path: the things separated by `::`.
189 pub segments
: &'hir
[PathSegment
<'hir
>],
193 pub fn is_global(&self) -> bool
{
194 !self.segments
.is_empty() && self.segments
[0].ident
.name
== kw
::PathRoot
198 /// A segment of a path: an identifier, an optional lifetime, and a set of
200 #[derive(Debug, HashStable_Generic)]
201 pub struct PathSegment
<'hir
> {
202 /// The identifier portion of this path segment.
207 /// Type/lifetime parameters attached to this path. They come in
208 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
209 /// this is more than just simple syntactic sugar; the use of
210 /// parens affects the region binding rules, so we preserve the
212 pub args
: Option
<&'hir GenericArgs
<'hir
>>,
214 /// Whether to infer remaining type parameters, if any.
215 /// This only applies to expression and pattern paths, and
216 /// out of those only the segments with no type parameters
217 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
218 pub infer_args
: bool
,
221 impl<'hir
> PathSegment
<'hir
> {
222 /// Converts an identifier to the corresponding segment.
223 pub fn new(ident
: Ident
, hir_id
: HirId
, res
: Res
) -> PathSegment
<'hir
> {
224 PathSegment { ident, hir_id, res, infer_args: true, args: None }
227 pub fn invalid() -> Self {
228 Self::new(Ident
::empty(), HirId
::INVALID
, Res
::Err
)
231 pub fn args(&self) -> &GenericArgs
<'hir
> {
232 if let Some(ref args
) = self.args
{
235 const DUMMY
: &GenericArgs
<'_
> = &GenericArgs
::none();
241 #[derive(Encodable, Debug, HashStable_Generic)]
242 pub struct ConstArg
{
243 pub value
: AnonConst
,
247 #[derive(Encodable, Debug, HashStable_Generic)]
248 pub struct InferArg
{
254 pub fn to_ty(&self) -> Ty
<'_
> {
255 Ty { kind: TyKind::Infer, span: self.span, hir_id: self.hir_id }
259 #[derive(Debug, HashStable_Generic)]
260 pub enum GenericArg
<'hir
> {
261 Lifetime(&'hir Lifetime
),
262 Type(&'hir Ty
<'hir
>),
267 impl GenericArg
<'_
> {
268 pub fn span(&self) -> Span
{
270 GenericArg
::Lifetime(l
) => l
.span
,
271 GenericArg
::Type(t
) => t
.span
,
272 GenericArg
::Const(c
) => c
.span
,
273 GenericArg
::Infer(i
) => i
.span
,
277 pub fn hir_id(&self) -> HirId
{
279 GenericArg
::Lifetime(l
) => l
.hir_id
,
280 GenericArg
::Type(t
) => t
.hir_id
,
281 GenericArg
::Const(c
) => c
.value
.hir_id
,
282 GenericArg
::Infer(i
) => i
.hir_id
,
286 pub fn is_synthetic(&self) -> bool
{
287 matches
!(self, GenericArg
::Lifetime(lifetime
) if lifetime
.name
.ident() == Ident
::empty())
290 pub fn descr(&self) -> &'
static str {
292 GenericArg
::Lifetime(_
) => "lifetime",
293 GenericArg
::Type(_
) => "type",
294 GenericArg
::Const(_
) => "constant",
295 GenericArg
::Infer(_
) => "inferred",
299 pub fn to_ord(&self) -> ast
::ParamKindOrd
{
301 GenericArg
::Lifetime(_
) => ast
::ParamKindOrd
::Lifetime
,
302 GenericArg
::Type(_
) | GenericArg
::Const(_
) | GenericArg
::Infer(_
) => {
303 ast
::ParamKindOrd
::TypeOrConst
308 pub fn is_ty_or_const(&self) -> bool
{
310 GenericArg
::Lifetime(_
) => false,
311 GenericArg
::Type(_
) | GenericArg
::Const(_
) | GenericArg
::Infer(_
) => true,
316 #[derive(Debug, HashStable_Generic)]
317 pub struct GenericArgs
<'hir
> {
318 /// The generic arguments for this path segment.
319 pub args
: &'hir
[GenericArg
<'hir
>],
320 /// Bindings (equality constraints) on associated types, if present.
321 /// E.g., `Foo<A = Bar>`.
322 pub bindings
: &'hir
[TypeBinding
<'hir
>],
323 /// Were arguments written in parenthesized form `Fn(T) -> U`?
324 /// This is required mostly for pretty-printing and diagnostics,
325 /// but also for changing lifetime elision rules to be "function-like".
326 pub parenthesized
: bool
,
327 /// The span encompassing arguments and the surrounding brackets `<>` or `()`
328 /// Foo<A, B, AssocTy = D> Fn(T, U, V) -> W
329 /// ^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^
330 /// Note that this may be:
331 /// - empty, if there are no generic brackets (but there may be hidden lifetimes)
332 /// - dummy, if this was generated while desugaring
336 impl<'hir
> GenericArgs
<'hir
> {
337 pub const fn none() -> Self {
338 Self { args: &[], bindings: &[], parenthesized: false, span_ext: DUMMY_SP }
341 pub fn inputs(&self) -> &[Ty
<'hir
>] {
342 if self.parenthesized
{
343 for arg
in self.args
{
345 GenericArg
::Lifetime(_
) => {}
346 GenericArg
::Type(ref ty
) => {
347 if let TyKind
::Tup(ref tys
) = ty
.kind
{
352 GenericArg
::Const(_
) => {}
353 GenericArg
::Infer(_
) => {}
357 panic
!("GenericArgs::inputs: not a `Fn(T) -> U`");
361 pub fn has_type_params(&self) -> bool
{
362 self.args
.iter().any(|arg
| matches
!(arg
, GenericArg
::Type(_
)))
365 pub fn has_err(&self) -> bool
{
366 self.args
.iter().any(|arg
| match arg
{
367 GenericArg
::Type(ty
) => matches
!(ty
.kind
, TyKind
::Err
),
369 }) || self.bindings
.iter().any(|arg
| match arg
.kind
{
370 TypeBindingKind
::Equality { term: Term::Ty(ty) }
=> matches
!(ty
.kind
, TyKind
::Err
),
376 pub fn num_type_params(&self) -> usize {
377 self.args
.iter().filter(|arg
| matches
!(arg
, GenericArg
::Type(_
))).count()
381 pub fn num_lifetime_params(&self) -> usize {
382 self.args
.iter().filter(|arg
| matches
!(arg
, GenericArg
::Lifetime(_
))).count()
386 pub fn has_lifetime_params(&self) -> bool
{
387 self.args
.iter().any(|arg
| matches
!(arg
, GenericArg
::Lifetime(_
)))
391 pub fn num_generic_params(&self) -> usize {
392 self.args
.iter().filter(|arg
| !matches
!(arg
, GenericArg
::Lifetime(_
))).count()
395 /// The span encompassing the text inside the surrounding brackets.
396 /// It will also include bindings if they aren't in the form `-> Ret`
397 /// Returns `None` if the span is empty (e.g. no brackets) or dummy
398 pub fn span(&self) -> Option
<Span
> {
399 let span_ext
= self.span_ext()?
;
400 Some(span_ext
.with_lo(span_ext
.lo() + BytePos(1)).with_hi(span_ext
.hi() - BytePos(1)))
403 /// Returns span encompassing arguments and their surrounding `<>` or `()`
404 pub fn span_ext(&self) -> Option
<Span
> {
405 Some(self.span_ext
).filter(|span
| !span
.is_empty())
408 pub fn is_empty(&self) -> bool
{
413 /// A modifier on a bound, currently this is only used for `?Sized`, where the
414 /// modifier is `Maybe`. Negative bounds should also be handled here.
415 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
416 #[derive(HashStable_Generic)]
417 pub enum TraitBoundModifier
{
423 /// The AST represents all type param bounds as types.
424 /// `typeck::collect::compute_bounds` matches these against
425 /// the "special" built-in traits (see `middle::lang_items`) and
426 /// detects `Copy`, `Send` and `Sync`.
427 #[derive(Clone, Debug, HashStable_Generic)]
428 pub enum GenericBound
<'hir
> {
429 Trait(PolyTraitRef
<'hir
>, TraitBoundModifier
),
430 // FIXME(davidtwco): Introduce `PolyTraitRef::LangItem`
431 LangItemTrait(LangItem
, Span
, HirId
, &'hir GenericArgs
<'hir
>),
432 Outlives(&'hir Lifetime
),
435 impl GenericBound
<'_
> {
436 pub fn trait_ref(&self) -> Option
<&TraitRef
<'_
>> {
438 GenericBound
::Trait(data
, _
) => Some(&data
.trait_ref
),
443 pub fn span(&self) -> Span
{
445 GenericBound
::Trait(t
, ..) => t
.span
,
446 GenericBound
::LangItemTrait(_
, span
, ..) => *span
,
447 GenericBound
::Outlives(l
) => l
.span
,
452 pub type GenericBounds
<'hir
> = &'hir
[GenericBound
<'hir
>];
454 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
455 pub enum LifetimeParamKind
{
456 // Indicates that the lifetime definition was explicitly declared (e.g., in
457 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
460 // Indication that the lifetime was elided (e.g., in both cases in
461 // `fn foo(x: &u8) -> &'_ u8 { x }`).
464 // Indication that the lifetime name was somehow in error.
468 #[derive(Debug, HashStable_Generic)]
469 pub enum GenericParamKind
<'hir
> {
470 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
472 kind
: LifetimeParamKind
,
475 default: Option
<&'hir Ty
<'hir
>>,
480 /// Optional default value for the const generic param
481 default: Option
<AnonConst
>,
485 #[derive(Debug, HashStable_Generic)]
486 pub struct GenericParam
<'hir
> {
490 pub pure_wrt_drop
: bool
,
491 pub kind
: GenericParamKind
<'hir
>,
492 pub colon_span
: Option
<Span
>,
495 impl<'hir
> GenericParam
<'hir
> {
496 /// Synthetic type-parameters are inserted after normal ones.
497 /// In order for normal parameters to be able to refer to synthetic ones,
498 /// scans them first.
499 pub fn is_impl_trait(&self) -> bool
{
500 matches
!(self.kind
, GenericParamKind
::Type { synthetic: true, .. }
)
503 /// This can happen for `async fn`, e.g. `async fn f<'_>(&'_ self)`.
505 /// See `lifetime_to_generic_param` in `rustc_ast_lowering` for more information.
506 pub fn is_elided_lifetime(&self) -> bool
{
507 matches
!(self.kind
, GenericParamKind
::Lifetime { kind: LifetimeParamKind::Elided }
)
512 pub struct GenericParamCount
{
513 pub lifetimes
: usize,
519 /// Represents lifetimes and type parameters attached to a declaration
520 /// of a function, enum, trait, etc.
521 #[derive(Debug, HashStable_Generic)]
522 pub struct Generics
<'hir
> {
523 pub params
: &'hir
[GenericParam
<'hir
>],
524 pub predicates
: &'hir
[WherePredicate
<'hir
>],
525 pub has_where_clause_predicates
: bool
,
526 pub where_clause_span
: Span
,
530 impl<'hir
> Generics
<'hir
> {
531 pub const fn empty() -> &'hir Generics
<'hir
> {
532 const NOPE
: Generics
<'_
> = Generics
{
535 has_where_clause_predicates
: false,
536 where_clause_span
: DUMMY_SP
,
542 pub fn get_named(&self, name
: Symbol
) -> Option
<&GenericParam
<'hir
>> {
543 for param
in self.params
{
544 if name
== param
.name
.ident().name
{
551 pub fn spans(&self) -> MultiSpan
{
552 if self.params
.is_empty() {
555 self.params
.iter().map(|p
| p
.span
).collect
::<Vec
<Span
>>().into()
559 /// If there are generic parameters, return where to introduce a new one.
560 pub fn span_for_param_suggestion(&self) -> Option
<Span
> {
561 if self.params
.iter().any(|p
| self.span
.contains(p
.span
)) {
562 // `fn foo<A>(t: impl Trait)`
563 // ^ suggest `, T: Trait` here
564 let span
= self.span
.with_lo(self.span
.hi() - BytePos(1)).shrink_to_lo();
571 /// `Span` where further predicates would be suggested, accounting for trailing commas, like
572 /// in `fn foo<T>(t: T) where T: Foo,` so we don't suggest two trailing commas.
573 pub fn tail_span_for_predicate_suggestion(&self) -> Span
{
574 let end
= self.where_clause_span
.shrink_to_hi();
575 if self.has_where_clause_predicates
{
578 .rfind(|&p
| p
.in_where_clause())
579 .map_or(end
, |p
| p
.span())
587 pub fn add_where_or_trailing_comma(&self) -> &'
static str {
588 if self.has_where_clause_predicates
{
590 } else if self.where_clause_span
.is_empty() {
593 // No where clause predicates, but we have `where` token
598 pub fn bounds_for_param(
600 param_def_id
: LocalDefId
,
601 ) -> impl Iterator
<Item
= &WhereBoundPredicate
<'hir
>> {
602 self.predicates
.iter().filter_map(move |pred
| match pred
{
603 WherePredicate
::BoundPredicate(bp
) if bp
.is_param_bound(param_def_id
.to_def_id()) => {
610 pub fn outlives_for_param(
612 param_def_id
: LocalDefId
,
613 ) -> impl Iterator
<Item
= &WhereRegionPredicate
<'_
>> {
614 self.predicates
.iter().filter_map(move |pred
| match pred
{
615 WherePredicate
::RegionPredicate(rp
) if rp
.is_param_bound(param_def_id
) => Some(rp
),
620 pub fn bounds_span_for_suggestions(&self, param_def_id
: LocalDefId
) -> Option
<Span
> {
621 self.bounds_for_param(param_def_id
).flat_map(|bp
| bp
.bounds
.iter().rev()).find_map(
623 // We include bounds that come from a `#[derive(_)]` but point at the user's code,
624 // as we use this method to get a span appropriate for suggestions.
625 let bs
= bound
.span();
626 if bs
.can_be_used_for_suggestions() { Some(bs.shrink_to_hi()) }
else { None }
631 pub fn span_for_predicate_removal(&self, pos
: usize) -> Span
{
632 let predicate
= &self.predicates
[pos
];
633 let span
= predicate
.span();
635 if !predicate
.in_where_clause() {
641 // We need to find out which comma to remove.
642 if pos
< self.predicates
.len() - 1 {
643 let next_pred
= &self.predicates
[pos
+ 1];
644 if next_pred
.in_where_clause() {
645 // where T: ?Sized, Foo: Bar,
647 return span
.until(next_pred
.span());
652 let prev_pred
= &self.predicates
[pos
- 1];
653 if prev_pred
.in_where_clause() {
654 // where Foo: Bar, T: ?Sized,
656 return prev_pred
.span().shrink_to_hi().to(span
);
660 // This is the only predicate in the where clause.
663 self.where_clause_span
666 pub fn span_for_bound_removal(&self, predicate_pos
: usize, bound_pos
: usize) -> Span
{
667 let predicate
= &self.predicates
[predicate_pos
];
668 let bounds
= predicate
.bounds();
670 if bounds
.len() == 1 {
671 return self.span_for_predicate_removal(predicate_pos
);
674 let span
= bounds
[bound_pos
].span();
676 // where T: ?Sized + Bar, Foo: Bar,
678 span
.to(bounds
[1].span().shrink_to_lo())
680 // where T: Bar + ?Sized, Foo: Bar,
682 bounds
[bound_pos
- 1].span().shrink_to_hi().to(span
)
687 /// A single predicate in a where-clause.
688 #[derive(Debug, HashStable_Generic)]
689 pub enum WherePredicate
<'hir
> {
690 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
691 BoundPredicate(WhereBoundPredicate
<'hir
>),
692 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
693 RegionPredicate(WhereRegionPredicate
<'hir
>),
694 /// An equality predicate (unsupported).
695 EqPredicate(WhereEqPredicate
<'hir
>),
698 impl<'hir
> WherePredicate
<'hir
> {
699 pub fn span(&self) -> Span
{
701 WherePredicate
::BoundPredicate(p
) => p
.span
,
702 WherePredicate
::RegionPredicate(p
) => p
.span
,
703 WherePredicate
::EqPredicate(p
) => p
.span
,
707 pub fn in_where_clause(&self) -> bool
{
709 WherePredicate
::BoundPredicate(p
) => p
.origin
== PredicateOrigin
::WhereClause
,
710 WherePredicate
::RegionPredicate(p
) => p
.in_where_clause
,
711 WherePredicate
::EqPredicate(_
) => false,
715 pub fn bounds(&self) -> GenericBounds
<'hir
> {
717 WherePredicate
::BoundPredicate(p
) => p
.bounds
,
718 WherePredicate
::RegionPredicate(p
) => p
.bounds
,
719 WherePredicate
::EqPredicate(_
) => &[],
724 #[derive(Copy, Clone, Debug, HashStable_Generic, PartialEq, Eq)]
725 pub enum PredicateOrigin
{
731 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
732 #[derive(Debug, HashStable_Generic)]
733 pub struct WhereBoundPredicate
<'hir
> {
735 /// Origin of the predicate.
736 pub origin
: PredicateOrigin
,
737 /// Any generics from a `for` binding.
738 pub bound_generic_params
: &'hir
[GenericParam
<'hir
>],
739 /// The type being bounded.
740 pub bounded_ty
: &'hir Ty
<'hir
>,
741 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
742 pub bounds
: GenericBounds
<'hir
>,
745 impl<'hir
> WhereBoundPredicate
<'hir
> {
746 /// Returns `true` if `param_def_id` matches the `bounded_ty` of this predicate.
747 pub fn is_param_bound(&self, param_def_id
: DefId
) -> bool
{
748 self.bounded_ty
.as_generic_param().map_or(false, |(def_id
, _
)| def_id
== param_def_id
)
752 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
753 #[derive(Debug, HashStable_Generic)]
754 pub struct WhereRegionPredicate
<'hir
> {
756 pub in_where_clause
: bool
,
757 pub lifetime
: &'hir Lifetime
,
758 pub bounds
: GenericBounds
<'hir
>,
761 impl<'hir
> WhereRegionPredicate
<'hir
> {
762 /// Returns `true` if `param_def_id` matches the `lifetime` of this predicate.
763 pub fn is_param_bound(&self, param_def_id
: LocalDefId
) -> bool
{
764 match self.lifetime
.name
{
765 LifetimeName
::Param(id
, _
) => id
== param_def_id
,
771 /// An equality predicate (e.g., `T = int`); currently unsupported.
772 #[derive(Debug, HashStable_Generic)]
773 pub struct WhereEqPredicate
<'hir
> {
775 pub lhs_ty
: &'hir Ty
<'hir
>,
776 pub rhs_ty
: &'hir Ty
<'hir
>,
779 /// HIR node coupled with its parent's id in the same HIR owner.
781 /// The parent is trash when the node is a HIR owner.
782 #[derive(Clone, Debug)]
783 pub struct ParentedNode
<'tcx
> {
784 pub parent
: ItemLocalId
,
785 pub node
: Node
<'tcx
>,
788 /// Attributes owned by a HIR owner.
790 pub struct AttributeMap
<'tcx
> {
791 pub map
: SortedMap
<ItemLocalId
, &'tcx
[Attribute
]>,
792 pub hash
: Fingerprint
,
795 impl<'tcx
> AttributeMap
<'tcx
> {
796 pub const EMPTY
: &'
static AttributeMap
<'
static> =
797 &AttributeMap { map: SortedMap::new(), hash: Fingerprint::ZERO }
;
800 pub fn get(&self, id
: ItemLocalId
) -> &'tcx
[Attribute
] {
801 self.map
.get(&id
).copied().unwrap_or(&[])
805 /// Map of all HIR nodes inside the current owner.
806 /// These nodes are mapped by `ItemLocalId` alongside the index of their parent node.
807 /// The HIR tree, including bodies, is pre-hashed.
808 pub struct OwnerNodes
<'tcx
> {
809 /// Pre-computed hash of the full HIR.
810 pub hash_including_bodies
: Fingerprint
,
811 /// Pre-computed hash of the item signature, sithout recursing into the body.
812 pub hash_without_bodies
: Fingerprint
,
813 /// Full HIR for the current owner.
814 // The zeroth node's parent should never be accessed: the owner's parent is computed by the
815 // hir_owner_parent query. It is set to `ItemLocalId::INVALID` to force an ICE if accidentally
817 pub nodes
: IndexVec
<ItemLocalId
, Option
<ParentedNode
<'tcx
>>>,
818 /// Content of local bodies.
819 pub bodies
: SortedMap
<ItemLocalId
, &'tcx Body
<'tcx
>>,
820 /// Non-owning definitions contained in this owner.
821 pub local_id_to_def_id
: SortedMap
<ItemLocalId
, LocalDefId
>,
824 impl<'tcx
> OwnerNodes
<'tcx
> {
825 pub fn node(&self) -> OwnerNode
<'tcx
> {
826 use rustc_index
::vec
::Idx
;
827 let node
= self.nodes
[ItemLocalId
::new(0)].as_ref().unwrap().node
;
828 let node
= node
.as_owner().unwrap(); // Indexing must ensure it is an OwnerNode.
833 impl fmt
::Debug
for OwnerNodes
<'_
> {
834 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
835 f
.debug_struct("OwnerNodes")
836 // Do not print all the pointers to all the nodes, as it would be unreadable.
837 .field("node", &self.nodes
[ItemLocalId
::from_u32(0)])
843 .map(|(id
, parented_node
)| (id
, parented_node
.as_ref().map(|node
| node
.parent
)))
844 .collect
::<Vec
<_
>>(),
846 .field("bodies", &self.bodies
)
847 .field("local_id_to_def_id", &self.local_id_to_def_id
)
848 .field("hash_without_bodies", &self.hash_without_bodies
)
849 .field("hash_including_bodies", &self.hash_including_bodies
)
854 /// Full information resulting from lowering an AST node.
855 #[derive(Debug, HashStable_Generic)]
856 pub struct OwnerInfo
<'hir
> {
857 /// Contents of the HIR.
858 pub nodes
: OwnerNodes
<'hir
>,
859 /// Map from each nested owner to its parent's local id.
860 pub parenting
: FxHashMap
<LocalDefId
, ItemLocalId
>,
861 /// Collected attributes of the HIR nodes.
862 pub attrs
: AttributeMap
<'hir
>,
863 /// Map indicating what traits are in scope for places where this
864 /// is relevant; generated by resolve.
865 pub trait_map
: FxHashMap
<ItemLocalId
, Box
<[TraitCandidate
]>>,
868 impl<'tcx
> OwnerInfo
<'tcx
> {
870 pub fn node(&self) -> OwnerNode
<'tcx
> {
875 #[derive(Copy, Clone, Debug, HashStable_Generic)]
876 pub enum MaybeOwner
<T
> {
879 /// Used as a placeholder for unused LocalDefId.
883 impl<T
> MaybeOwner
<T
> {
884 pub fn as_owner(self) -> Option
<T
> {
886 MaybeOwner
::Owner(i
) => Some(i
),
887 MaybeOwner
::NonOwner(_
) | MaybeOwner
::Phantom
=> None
,
891 pub fn map
<U
>(self, f
: impl FnOnce(T
) -> U
) -> MaybeOwner
<U
> {
893 MaybeOwner
::Owner(i
) => MaybeOwner
::Owner(f(i
)),
894 MaybeOwner
::NonOwner(hir_id
) => MaybeOwner
::NonOwner(hir_id
),
895 MaybeOwner
::Phantom
=> MaybeOwner
::Phantom
,
899 pub fn unwrap(self) -> T
{
901 MaybeOwner
::Owner(i
) => i
,
902 MaybeOwner
::NonOwner(_
) | MaybeOwner
::Phantom
=> panic
!("Not a HIR owner"),
907 /// The top-level data structure that stores the entire contents of
908 /// the crate currently being compiled.
910 /// For more details, see the [rustc dev guide].
912 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
914 pub struct Crate
<'hir
> {
915 pub owners
: IndexVec
<LocalDefId
, MaybeOwner
<&'hir OwnerInfo
<'hir
>>>,
916 pub hir_hash
: Fingerprint
,
919 #[derive(Debug, HashStable_Generic)]
920 pub struct Closure
<'hir
> {
921 pub binder
: ClosureBinder
,
922 pub capture_clause
: CaptureBy
,
923 pub bound_generic_params
: &'hir
[GenericParam
<'hir
>],
924 pub fn_decl
: &'hir FnDecl
<'hir
>,
926 pub fn_decl_span
: Span
,
927 pub movability
: Option
<Movability
>,
930 /// A block of statements `{ .. }`, which may have a label (in this case the
931 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
932 /// the `rules` being anything but `DefaultBlock`.
933 #[derive(Debug, HashStable_Generic)]
934 pub struct Block
<'hir
> {
935 /// Statements in a block.
936 pub stmts
: &'hir
[Stmt
<'hir
>],
937 /// An expression at the end of the block
938 /// without a semicolon, if any.
939 pub expr
: Option
<&'hir Expr
<'hir
>>,
940 #[stable_hasher(ignore)]
942 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
943 pub rules
: BlockCheckMode
,
945 /// If true, then there may exist `break 'a` values that aim to
946 /// break out of this block early.
947 /// Used by `'label: {}` blocks and by `try {}` blocks.
948 pub targeted_by_break
: bool
,
951 impl<'hir
> Block
<'hir
> {
952 pub fn innermost_block(&self) -> &Block
<'hir
> {
953 let mut block
= self;
954 while let Some(Expr { kind: ExprKind::Block(inner_block, _), .. }
) = block
.expr
{
961 #[derive(Debug, HashStable_Generic)]
962 pub struct Pat
<'hir
> {
963 #[stable_hasher(ignore)]
965 pub kind
: PatKind
<'hir
>,
967 // Whether to use default binding modes.
968 // At present, this is false only for destructuring assignment.
969 pub default_binding_modes
: bool
,
972 impl<'hir
> Pat
<'hir
> {
973 // FIXME(#19596) this is a workaround, but there should be a better way
974 fn walk_short_(&self, it
: &mut impl FnMut(&Pat
<'hir
>) -> bool
) -> bool
{
981 Wild
| Lit(_
) | Range(..) | Binding(.., None
) | Path(_
) => true,
982 Box(s
) | Ref(s
, _
) | Binding(.., Some(s
)) => s
.walk_short_(it
),
983 Struct(_
, fields
, _
) => fields
.iter().all(|field
| field
.pat
.walk_short_(it
)),
984 TupleStruct(_
, s
, _
) | Tuple(s
, _
) | Or(s
) => s
.iter().all(|p
| p
.walk_short_(it
)),
985 Slice(before
, slice
, after
) => {
986 before
.iter().chain(slice
).chain(after
.iter()).all(|p
| p
.walk_short_(it
))
991 /// Walk the pattern in left-to-right order,
992 /// short circuiting (with `.all(..)`) if `false` is returned.
994 /// Note that when visiting e.g. `Tuple(ps)`,
995 /// if visiting `ps[0]` returns `false`,
996 /// then `ps[1]` will not be visited.
997 pub fn walk_short(&self, mut it
: impl FnMut(&Pat
<'hir
>) -> bool
) -> bool
{
998 self.walk_short_(&mut it
)
1001 // FIXME(#19596) this is a workaround, but there should be a better way
1002 fn walk_(&self, it
: &mut impl FnMut(&Pat
<'hir
>) -> bool
) {
1009 Wild
| Lit(_
) | Range(..) | Binding(.., None
) | Path(_
) => {}
1010 Box(s
) | Ref(s
, _
) | Binding(.., Some(s
)) => s
.walk_(it
),
1011 Struct(_
, fields
, _
) => fields
.iter().for_each(|field
| field
.pat
.walk_(it
)),
1012 TupleStruct(_
, s
, _
) | Tuple(s
, _
) | Or(s
) => s
.iter().for_each(|p
| p
.walk_(it
)),
1013 Slice(before
, slice
, after
) => {
1014 before
.iter().chain(slice
).chain(after
.iter()).for_each(|p
| p
.walk_(it
))
1019 /// Walk the pattern in left-to-right order.
1021 /// If `it(pat)` returns `false`, the children are not visited.
1022 pub fn walk(&self, mut it
: impl FnMut(&Pat
<'hir
>) -> bool
) {
1026 /// Walk the pattern in left-to-right order.
1028 /// If you always want to recurse, prefer this method over `walk`.
1029 pub fn walk_always(&self, mut it
: impl FnMut(&Pat
<'_
>)) {
1037 /// A single field in a struct pattern.
1039 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
1040 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
1041 /// except `is_shorthand` is true.
1042 #[derive(Debug, HashStable_Generic)]
1043 pub struct PatField
<'hir
> {
1044 #[stable_hasher(ignore)]
1046 /// The identifier for the field.
1048 /// The pattern the field is destructured to.
1049 pub pat
: &'hir Pat
<'hir
>,
1050 pub is_shorthand
: bool
,
1054 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1060 impl fmt
::Display
for RangeEnd
{
1061 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1062 f
.write_str(match self {
1063 RangeEnd
::Included
=> "..=",
1064 RangeEnd
::Excluded
=> "..",
1069 // Equivalent to `Option<usize>`. That type takes up 16 bytes on 64-bit, but
1070 // this type only takes up 4 bytes, at the cost of being restricted to a
1071 // maximum value of `u32::MAX - 1`. In practice, this is more than enough.
1072 #[derive(Clone, Copy, PartialEq, Eq, Hash, HashStable_Generic)]
1073 pub struct DotDotPos(u32);
1076 // Panics if n >= u32::MAX.
1077 pub fn new(n
: Option
<usize>) -> Self {
1080 assert
!(n
< u32::MAX
as usize);
1083 None
=> Self(u32::MAX
),
1087 pub fn as_opt_usize(&self) -> Option
<usize> {
1088 if self.0 == u32::MAX { None }
else { Some(self.0 as usize) }
1092 impl fmt
::Debug
for DotDotPos
{
1093 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1094 self.as_opt_usize().fmt(f
)
1098 #[derive(Debug, HashStable_Generic)]
1099 pub enum PatKind
<'hir
> {
1100 /// Represents a wildcard pattern (i.e., `_`).
1103 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
1104 /// The `HirId` is the canonical ID for the variable being bound,
1105 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
1106 /// which is the pattern ID of the first `x`.
1107 Binding(BindingAnnotation
, HirId
, Ident
, Option
<&'hir Pat
<'hir
>>),
1109 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
1110 /// The `bool` is `true` in the presence of a `..`.
1111 Struct(QPath
<'hir
>, &'hir
[PatField
<'hir
>], bool
),
1113 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
1114 /// If the `..` pattern fragment is present, then `DotDotPos` denotes its position.
1115 /// `0 <= position <= subpats.len()`
1116 TupleStruct(QPath
<'hir
>, &'hir
[Pat
<'hir
>], DotDotPos
),
1118 /// An or-pattern `A | B | C`.
1119 /// Invariant: `pats.len() >= 2`.
1120 Or(&'hir
[Pat
<'hir
>]),
1122 /// A path pattern for a unit struct/variant or a (maybe-associated) constant.
1125 /// A tuple pattern (e.g., `(a, b)`).
1126 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
1127 /// `0 <= position <= subpats.len()`
1128 Tuple(&'hir
[Pat
<'hir
>], DotDotPos
),
1130 /// A `box` pattern.
1131 Box(&'hir Pat
<'hir
>),
1133 /// A reference pattern (e.g., `&mut (a, b)`).
1134 Ref(&'hir Pat
<'hir
>, Mutability
),
1137 Lit(&'hir Expr
<'hir
>),
1139 /// A range pattern (e.g., `1..=2` or `1..2`).
1140 Range(Option
<&'hir Expr
<'hir
>>, Option
<&'hir Expr
<'hir
>>, RangeEnd
),
1142 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
1144 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
1145 /// If `slice` exists, then `after` can be non-empty.
1147 /// The representation for e.g., `[a, b, .., c, d]` is:
1148 /// ```ignore (illustrative)
1149 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
1151 Slice(&'hir
[Pat
<'hir
>], Option
<&'hir Pat
<'hir
>>, &'hir
[Pat
<'hir
>]),
1154 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1155 pub enum BinOpKind
{
1156 /// The `+` operator (addition).
1158 /// The `-` operator (subtraction).
1160 /// The `*` operator (multiplication).
1162 /// The `/` operator (division).
1164 /// The `%` operator (modulus).
1166 /// The `&&` operator (logical and).
1168 /// The `||` operator (logical or).
1170 /// The `^` operator (bitwise xor).
1172 /// The `&` operator (bitwise and).
1174 /// The `|` operator (bitwise or).
1176 /// The `<<` operator (shift left).
1178 /// The `>>` operator (shift right).
1180 /// The `==` operator (equality).
1182 /// The `<` operator (less than).
1184 /// The `<=` operator (less than or equal to).
1186 /// The `!=` operator (not equal to).
1188 /// The `>=` operator (greater than or equal to).
1190 /// The `>` operator (greater than).
1195 pub fn as_str(self) -> &'
static str {
1197 BinOpKind
::Add
=> "+",
1198 BinOpKind
::Sub
=> "-",
1199 BinOpKind
::Mul
=> "*",
1200 BinOpKind
::Div
=> "/",
1201 BinOpKind
::Rem
=> "%",
1202 BinOpKind
::And
=> "&&",
1203 BinOpKind
::Or
=> "||",
1204 BinOpKind
::BitXor
=> "^",
1205 BinOpKind
::BitAnd
=> "&",
1206 BinOpKind
::BitOr
=> "|",
1207 BinOpKind
::Shl
=> "<<",
1208 BinOpKind
::Shr
=> ">>",
1209 BinOpKind
::Eq
=> "==",
1210 BinOpKind
::Lt
=> "<",
1211 BinOpKind
::Le
=> "<=",
1212 BinOpKind
::Ne
=> "!=",
1213 BinOpKind
::Ge
=> ">=",
1214 BinOpKind
::Gt
=> ">",
1218 pub fn is_lazy(self) -> bool
{
1219 matches
!(self, BinOpKind
::And
| BinOpKind
::Or
)
1222 pub fn is_shift(self) -> bool
{
1223 matches
!(self, BinOpKind
::Shl
| BinOpKind
::Shr
)
1226 pub fn is_comparison(self) -> bool
{
1233 | BinOpKind
::Ge
=> true,
1245 | BinOpKind
::Shr
=> false,
1249 /// Returns `true` if the binary operator takes its arguments by value.
1250 pub fn is_by_value(self) -> bool
{
1251 !self.is_comparison()
1255 impl Into
<ast
::BinOpKind
> for BinOpKind
{
1256 fn into(self) -> ast
::BinOpKind
{
1258 BinOpKind
::Add
=> ast
::BinOpKind
::Add
,
1259 BinOpKind
::Sub
=> ast
::BinOpKind
::Sub
,
1260 BinOpKind
::Mul
=> ast
::BinOpKind
::Mul
,
1261 BinOpKind
::Div
=> ast
::BinOpKind
::Div
,
1262 BinOpKind
::Rem
=> ast
::BinOpKind
::Rem
,
1263 BinOpKind
::And
=> ast
::BinOpKind
::And
,
1264 BinOpKind
::Or
=> ast
::BinOpKind
::Or
,
1265 BinOpKind
::BitXor
=> ast
::BinOpKind
::BitXor
,
1266 BinOpKind
::BitAnd
=> ast
::BinOpKind
::BitAnd
,
1267 BinOpKind
::BitOr
=> ast
::BinOpKind
::BitOr
,
1268 BinOpKind
::Shl
=> ast
::BinOpKind
::Shl
,
1269 BinOpKind
::Shr
=> ast
::BinOpKind
::Shr
,
1270 BinOpKind
::Eq
=> ast
::BinOpKind
::Eq
,
1271 BinOpKind
::Lt
=> ast
::BinOpKind
::Lt
,
1272 BinOpKind
::Le
=> ast
::BinOpKind
::Le
,
1273 BinOpKind
::Ne
=> ast
::BinOpKind
::Ne
,
1274 BinOpKind
::Ge
=> ast
::BinOpKind
::Ge
,
1275 BinOpKind
::Gt
=> ast
::BinOpKind
::Gt
,
1280 pub type BinOp
= Spanned
<BinOpKind
>;
1282 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1284 /// The `*` operator (dereferencing).
1286 /// The `!` operator (logical negation).
1288 /// The `-` operator (negation).
1293 pub fn as_str(self) -> &'
static str {
1301 /// Returns `true` if the unary operator takes its argument by value.
1302 pub fn is_by_value(self) -> bool
{
1303 matches
!(self, Self::Neg
| Self::Not
)
1308 #[derive(Debug, HashStable_Generic)]
1309 pub struct Stmt
<'hir
> {
1311 pub kind
: StmtKind
<'hir
>,
1315 /// The contents of a statement.
1316 #[derive(Debug, HashStable_Generic)]
1317 pub enum StmtKind
<'hir
> {
1318 /// A local (`let`) binding.
1319 Local(&'hir Local
<'hir
>),
1321 /// An item binding.
1324 /// An expression without a trailing semi-colon (must have unit type).
1325 Expr(&'hir Expr
<'hir
>),
1327 /// An expression with a trailing semi-colon (may have any type).
1328 Semi(&'hir Expr
<'hir
>),
1331 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <init>;`).
1332 #[derive(Debug, HashStable_Generic)]
1333 pub struct Local
<'hir
> {
1334 pub pat
: &'hir Pat
<'hir
>,
1335 /// Type annotation, if any (otherwise the type will be inferred).
1336 pub ty
: Option
<&'hir Ty
<'hir
>>,
1337 /// Initializer expression to set the value, if any.
1338 pub init
: Option
<&'hir Expr
<'hir
>>,
1339 /// Else block for a `let...else` binding.
1340 pub els
: Option
<&'hir Block
<'hir
>>,
1343 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1344 /// desugaring. Otherwise will be `Normal`.
1345 pub source
: LocalSource
,
1348 /// Represents a single arm of a `match` expression, e.g.
1349 /// `<pat> (if <guard>) => <body>`.
1350 #[derive(Debug, HashStable_Generic)]
1351 pub struct Arm
<'hir
> {
1352 #[stable_hasher(ignore)]
1355 /// If this pattern and the optional guard matches, then `body` is evaluated.
1356 pub pat
: &'hir Pat
<'hir
>,
1357 /// Optional guard clause.
1358 pub guard
: Option
<Guard
<'hir
>>,
1359 /// The expression the arm evaluates to if this arm matches.
1360 pub body
: &'hir Expr
<'hir
>,
1363 /// Represents a `let <pat>[: <ty>] = <expr>` expression (not a Local), occurring in an `if-let` or
1364 /// `let-else`, evaluating to a boolean. Typically the pattern is refutable.
1366 /// In an if-let, imagine it as `if (let <pat> = <expr>) { ... }`; in a let-else, it is part of the
1367 /// desugaring to if-let. Only let-else supports the type annotation at present.
1368 #[derive(Debug, HashStable_Generic)]
1369 pub struct Let
<'hir
> {
1372 pub pat
: &'hir Pat
<'hir
>,
1373 pub ty
: Option
<&'hir Ty
<'hir
>>,
1374 pub init
: &'hir Expr
<'hir
>,
1377 #[derive(Debug, HashStable_Generic)]
1378 pub enum Guard
<'hir
> {
1379 If(&'hir Expr
<'hir
>),
1380 IfLet(&'hir Let
<'hir
>),
1383 impl<'hir
> Guard
<'hir
> {
1384 /// Returns the body of the guard
1386 /// In other words, returns the e in either of the following:
1389 /// - `if let x = e`
1390 pub fn body(&self) -> &'hir Expr
<'hir
> {
1392 Guard
::If(e
) | Guard
::IfLet(Let { init: e, .. }
) => e
,
1397 #[derive(Debug, HashStable_Generic)]
1398 pub struct ExprField
<'hir
> {
1399 #[stable_hasher(ignore)]
1402 pub expr
: &'hir Expr
<'hir
>,
1404 pub is_shorthand
: bool
,
1407 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1408 pub enum BlockCheckMode
{
1410 UnsafeBlock(UnsafeSource
),
1413 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1414 pub enum UnsafeSource
{
1419 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
1424 /// The body of a function, closure, or constant value. In the case of
1425 /// a function, the body contains not only the function body itself
1426 /// (which is an expression), but also the argument patterns, since
1427 /// those are something that the caller doesn't really care about.
1432 /// fn foo((x, y): (u32, u32)) -> u32 {
1437 /// Here, the `Body` associated with `foo()` would contain:
1439 /// - an `params` array containing the `(x, y)` pattern
1440 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1441 /// - `generator_kind` would be `None`
1443 /// All bodies have an **owner**, which can be accessed via the HIR
1444 /// map using `body_owner_def_id()`.
1445 #[derive(Debug, HashStable_Generic)]
1446 pub struct Body
<'hir
> {
1447 pub params
: &'hir
[Param
<'hir
>],
1448 pub value
: &'hir Expr
<'hir
>,
1449 pub generator_kind
: Option
<GeneratorKind
>,
1452 impl<'hir
> Body
<'hir
> {
1453 pub fn id(&self) -> BodyId
{
1454 BodyId { hir_id: self.value.hir_id }
1457 pub fn generator_kind(&self) -> Option
<GeneratorKind
> {
1462 /// The type of source expression that caused this generator to be created.
1463 #[derive(Clone, PartialEq, PartialOrd, Eq, Hash, Debug, Copy)]
1464 #[derive(HashStable_Generic, Encodable, Decodable)]
1465 pub enum GeneratorKind
{
1466 /// An explicit `async` block or the body of an async function.
1467 Async(AsyncGeneratorKind
),
1469 /// A generator literal created via a `yield` inside a closure.
1473 impl fmt
::Display
for GeneratorKind
{
1474 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1476 GeneratorKind
::Async(k
) => fmt
::Display
::fmt(k
, f
),
1477 GeneratorKind
::Gen
=> f
.write_str("generator"),
1482 impl GeneratorKind
{
1483 pub fn descr(&self) -> &'
static str {
1485 GeneratorKind
::Async(ask
) => ask
.descr(),
1486 GeneratorKind
::Gen
=> "generator",
1491 /// In the case of a generator created as part of an async construct,
1492 /// which kind of async construct caused it to be created?
1494 /// This helps error messages but is also used to drive coercions in
1495 /// type-checking (see #60424).
1496 #[derive(Clone, PartialEq, PartialOrd, Eq, Hash, Debug, Copy)]
1497 #[derive(HashStable_Generic, Encodable, Decodable)]
1498 pub enum AsyncGeneratorKind
{
1499 /// An explicit `async` block written by the user.
1502 /// An explicit `async` closure written by the user.
1505 /// The `async` block generated as the body of an async function.
1509 impl fmt
::Display
for AsyncGeneratorKind
{
1510 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1511 f
.write_str(match self {
1512 AsyncGeneratorKind
::Block
=> "`async` block",
1513 AsyncGeneratorKind
::Closure
=> "`async` closure body",
1514 AsyncGeneratorKind
::Fn
=> "`async fn` body",
1519 impl AsyncGeneratorKind
{
1520 pub fn descr(&self) -> &'
static str {
1522 AsyncGeneratorKind
::Block
=> "`async` block",
1523 AsyncGeneratorKind
::Closure
=> "`async` closure body",
1524 AsyncGeneratorKind
::Fn
=> "`async fn` body",
1529 #[derive(Copy, Clone, Debug)]
1530 pub enum BodyOwnerKind
{
1531 /// Functions and methods.
1537 /// Constants and associated constants.
1540 /// Initializer of a `static` item.
1544 impl BodyOwnerKind
{
1545 pub fn is_fn_or_closure(self) -> bool
{
1547 BodyOwnerKind
::Fn
| BodyOwnerKind
::Closure
=> true,
1548 BodyOwnerKind
::Const
| BodyOwnerKind
::Static(_
) => false,
1553 /// The kind of an item that requires const-checking.
1554 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1555 pub enum ConstContext
{
1559 /// A `static` or `static mut`.
1562 /// A `const`, associated `const`, or other const context.
1564 /// Other contexts include:
1565 /// - Array length expressions
1566 /// - Enum discriminants
1567 /// - Const generics
1569 /// For the most part, other contexts are treated just like a regular `const`, so they are
1570 /// lumped into the same category.
1575 /// A description of this const context that can appear between backticks in an error message.
1577 /// E.g. `const` or `static mut`.
1578 pub fn keyword_name(self) -> &'
static str {
1580 Self::Const
=> "const",
1581 Self::Static(Mutability
::Not
) => "static",
1582 Self::Static(Mutability
::Mut
) => "static mut",
1583 Self::ConstFn
=> "const fn",
1588 /// A colloquial, trivially pluralizable description of this const context for use in error
1590 impl fmt
::Display
for ConstContext
{
1591 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1593 Self::Const
=> write
!(f
, "constant"),
1594 Self::Static(_
) => write
!(f
, "static"),
1595 Self::ConstFn
=> write
!(f
, "constant function"),
1600 // NOTE: `IntoDiagnosticArg` impl for `ConstContext` lives in `rustc_errors`
1601 // due to a cyclical dependency between hir that crate.
1604 pub type Lit
= Spanned
<LitKind
>;
1606 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1613 pub fn hir_id(&self) -> HirId
{
1615 &ArrayLen
::Infer(hir_id
, _
) | &ArrayLen
::Body(AnonConst { hir_id, body: _ }
) => hir_id
,
1620 /// A constant (expression) that's not an item or associated item,
1621 /// but needs its own `DefId` for type-checking, const-eval, etc.
1622 /// These are usually found nested inside types (e.g., array lengths)
1623 /// or expressions (e.g., repeat counts), and also used to define
1624 /// explicit discriminant values for enum variants.
1626 /// You can check if this anon const is a default in a const param
1627 /// `const N: usize = { ... }` with `tcx.hir().opt_const_param_default_param_hir_id(..)`
1628 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1629 pub struct AnonConst
{
1635 #[derive(Debug, HashStable_Generic)]
1636 pub struct Expr
<'hir
> {
1638 pub kind
: ExprKind
<'hir
>,
1643 pub fn precedence(&self) -> ExprPrecedence
{
1645 ExprKind
::Box(_
) => ExprPrecedence
::Box
,
1646 ExprKind
::ConstBlock(_
) => ExprPrecedence
::ConstBlock
,
1647 ExprKind
::Array(_
) => ExprPrecedence
::Array
,
1648 ExprKind
::Call(..) => ExprPrecedence
::Call
,
1649 ExprKind
::MethodCall(..) => ExprPrecedence
::MethodCall
,
1650 ExprKind
::Tup(_
) => ExprPrecedence
::Tup
,
1651 ExprKind
::Binary(op
, ..) => ExprPrecedence
::Binary(op
.node
.into()),
1652 ExprKind
::Unary(..) => ExprPrecedence
::Unary
,
1653 ExprKind
::Lit(_
) => ExprPrecedence
::Lit
,
1654 ExprKind
::Type(..) | ExprKind
::Cast(..) => ExprPrecedence
::Cast
,
1655 ExprKind
::DropTemps(ref expr
, ..) => expr
.precedence(),
1656 ExprKind
::If(..) => ExprPrecedence
::If
,
1657 ExprKind
::Let(..) => ExprPrecedence
::Let
,
1658 ExprKind
::Loop(..) => ExprPrecedence
::Loop
,
1659 ExprKind
::Match(..) => ExprPrecedence
::Match
,
1660 ExprKind
::Closure { .. }
=> ExprPrecedence
::Closure
,
1661 ExprKind
::Block(..) => ExprPrecedence
::Block
,
1662 ExprKind
::Assign(..) => ExprPrecedence
::Assign
,
1663 ExprKind
::AssignOp(..) => ExprPrecedence
::AssignOp
,
1664 ExprKind
::Field(..) => ExprPrecedence
::Field
,
1665 ExprKind
::Index(..) => ExprPrecedence
::Index
,
1666 ExprKind
::Path(..) => ExprPrecedence
::Path
,
1667 ExprKind
::AddrOf(..) => ExprPrecedence
::AddrOf
,
1668 ExprKind
::Break(..) => ExprPrecedence
::Break
,
1669 ExprKind
::Continue(..) => ExprPrecedence
::Continue
,
1670 ExprKind
::Ret(..) => ExprPrecedence
::Ret
,
1671 ExprKind
::InlineAsm(..) => ExprPrecedence
::InlineAsm
,
1672 ExprKind
::Struct(..) => ExprPrecedence
::Struct
,
1673 ExprKind
::Repeat(..) => ExprPrecedence
::Repeat
,
1674 ExprKind
::Yield(..) => ExprPrecedence
::Yield
,
1675 ExprKind
::Err
=> ExprPrecedence
::Err
,
1679 // Whether this looks like a place expr, without checking for deref
1681 // This will return `true` in some potentially surprising cases such as
1682 // `CONSTANT.field`.
1683 pub fn is_syntactic_place_expr(&self) -> bool
{
1684 self.is_place_expr(|_
| true)
1687 /// Whether this is a place expression.
1689 /// `allow_projections_from` should return `true` if indexing a field or index expression based
1690 /// on the given expression should be considered a place expression.
1691 pub fn is_place_expr(&self, mut allow_projections_from
: impl FnMut(&Self) -> bool
) -> bool
{
1693 ExprKind
::Path(QPath
::Resolved(_
, ref path
)) => {
1694 matches
!(path
.res
, Res
::Local(..) | Res
::Def(DefKind
::Static(_
), _
) | Res
::Err
)
1697 // Type ascription inherits its place expression kind from its
1699 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1700 ExprKind
::Type(ref e
, _
) => e
.is_place_expr(allow_projections_from
),
1702 ExprKind
::Unary(UnOp
::Deref
, _
) => true,
1704 ExprKind
::Field(ref base
, _
) | ExprKind
::Index(ref base
, _
) => {
1705 allow_projections_from(base
) || base
.is_place_expr(allow_projections_from
)
1708 // Lang item paths cannot currently be local variables or statics.
1709 ExprKind
::Path(QPath
::LangItem(..)) => false,
1711 // Partially qualified paths in expressions can only legally
1712 // refer to associated items which are always rvalues.
1713 ExprKind
::Path(QPath
::TypeRelative(..))
1714 | ExprKind
::Call(..)
1715 | ExprKind
::MethodCall(..)
1716 | ExprKind
::Struct(..)
1719 | ExprKind
::Match(..)
1720 | ExprKind
::Closure { .. }
1721 | ExprKind
::Block(..)
1722 | ExprKind
::Repeat(..)
1723 | ExprKind
::Array(..)
1724 | ExprKind
::Break(..)
1725 | ExprKind
::Continue(..)
1728 | ExprKind
::Loop(..)
1729 | ExprKind
::Assign(..)
1730 | ExprKind
::InlineAsm(..)
1731 | ExprKind
::AssignOp(..)
1733 | ExprKind
::ConstBlock(..)
1734 | ExprKind
::Unary(..)
1736 | ExprKind
::AddrOf(..)
1737 | ExprKind
::Binary(..)
1738 | ExprKind
::Yield(..)
1739 | ExprKind
::Cast(..)
1740 | ExprKind
::DropTemps(..)
1741 | ExprKind
::Err
=> false,
1745 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1746 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1747 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1748 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1749 /// beyond remembering to call this function before doing analysis on it.
1750 pub fn peel_drop_temps(&self) -> &Self {
1751 let mut expr
= self;
1752 while let ExprKind
::DropTemps(inner
) = &expr
.kind
{
1758 pub fn peel_blocks(&self) -> &Self {
1759 let mut expr
= self;
1760 while let ExprKind
::Block(Block { expr: Some(inner), .. }
, _
) = &expr
.kind
{
1766 pub fn can_have_side_effects(&self) -> bool
{
1767 match self.peel_drop_temps().kind
{
1768 ExprKind
::Path(_
) | ExprKind
::Lit(_
) => false,
1769 ExprKind
::Type(base
, _
)
1770 | ExprKind
::Unary(_
, base
)
1771 | ExprKind
::Field(base
, _
)
1772 | ExprKind
::Index(base
, _
)
1773 | ExprKind
::AddrOf(.., base
)
1774 | ExprKind
::Cast(base
, _
) => {
1775 // This isn't exactly true for `Index` and all `Unary`, but we are using this
1776 // method exclusively for diagnostics and there's a *cultural* pressure against
1777 // them being used only for its side-effects.
1778 base
.can_have_side_effects()
1780 ExprKind
::Struct(_
, fields
, init
) => fields
1782 .map(|field
| field
.expr
)
1783 .chain(init
.into_iter())
1784 .all(|e
| e
.can_have_side_effects()),
1786 ExprKind
::Array(args
)
1787 | ExprKind
::Tup(args
)
1791 ExprKind
::Path(QPath
::Resolved(
1793 Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. }
,
1798 ) => args
.iter().all(|arg
| arg
.can_have_side_effects()),
1800 | ExprKind
::Match(..)
1801 | ExprKind
::MethodCall(..)
1802 | ExprKind
::Call(..)
1803 | ExprKind
::Closure { .. }
1804 | ExprKind
::Block(..)
1805 | ExprKind
::Repeat(..)
1806 | ExprKind
::Break(..)
1807 | ExprKind
::Continue(..)
1810 | ExprKind
::Loop(..)
1811 | ExprKind
::Assign(..)
1812 | ExprKind
::InlineAsm(..)
1813 | ExprKind
::AssignOp(..)
1814 | ExprKind
::ConstBlock(..)
1816 | ExprKind
::Binary(..)
1817 | ExprKind
::Yield(..)
1818 | ExprKind
::DropTemps(..)
1819 | ExprKind
::Err
=> true,
1823 // To a first-order approximation, is this a pattern
1824 pub fn is_approximately_pattern(&self) -> bool
{
1827 | ExprKind
::Array(_
)
1828 | ExprKind
::Call(..)
1832 | ExprKind
::Struct(..) => true,
1837 pub fn method_ident(&self) -> Option
<Ident
> {
1839 ExprKind
::MethodCall(receiver_method
, ..) => Some(receiver_method
.ident
),
1840 ExprKind
::Unary(_
, expr
) | ExprKind
::AddrOf(.., expr
) => expr
.method_ident(),
1846 /// Checks if the specified expression is a built-in range literal.
1847 /// (See: `LoweringContext::lower_expr()`).
1848 pub fn is_range_literal(expr
: &Expr
<'_
>) -> bool
{
1850 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1851 ExprKind
::Struct(ref qpath
, _
, _
) => matches
!(
1856 | LangItem
::RangeFrom
1857 | LangItem
::RangeFull
1858 | LangItem
::RangeToInclusive
,
1863 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1864 ExprKind
::Call(ref func
, _
) => {
1865 matches
!(func
.kind
, ExprKind
::Path(QPath
::LangItem(LangItem
::RangeInclusiveNew
, ..)))
1872 #[derive(Debug, HashStable_Generic)]
1873 pub enum ExprKind
<'hir
> {
1874 /// A `box x` expression.
1875 Box(&'hir Expr
<'hir
>),
1876 /// Allow anonymous constants from an inline `const` block
1877 ConstBlock(AnonConst
),
1878 /// An array (e.g., `[a, b, c, d]`).
1879 Array(&'hir
[Expr
<'hir
>]),
1880 /// A function call.
1882 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1883 /// and the second field is the list of arguments.
1884 /// This also represents calling the constructor of
1885 /// tuple-like ADTs such as tuple structs and enum variants.
1886 Call(&'hir Expr
<'hir
>, &'hir
[Expr
<'hir
>]),
1887 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1889 /// The `PathSegment` represents the method name and its generic arguments
1890 /// (within the angle brackets).
1891 /// The `&Expr` is the expression that evaluates
1892 /// to the object on which the method is being called on (the receiver),
1893 /// and the `&[Expr]` is the rest of the arguments.
1894 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1895 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, x, [a, b, c, d], span)`.
1896 /// The final `Span` represents the span of the function and arguments
1897 /// (e.g. `foo::<Bar, Baz>(a, b, c, d)` in `x.foo::<Bar, Baz>(a, b, c, d)`
1899 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1900 /// the `hir_id` of the `MethodCall` node itself.
1902 /// [`type_dependent_def_id`]: ../../rustc_middle/ty/struct.TypeckResults.html#method.type_dependent_def_id
1903 MethodCall(&'hir PathSegment
<'hir
>, &'hir Expr
<'hir
>, &'hir
[Expr
<'hir
>], Span
),
1904 /// A tuple (e.g., `(a, b, c, d)`).
1905 Tup(&'hir
[Expr
<'hir
>]),
1906 /// A binary operation (e.g., `a + b`, `a * b`).
1907 Binary(BinOp
, &'hir Expr
<'hir
>, &'hir Expr
<'hir
>),
1908 /// A unary operation (e.g., `!x`, `*x`).
1909 Unary(UnOp
, &'hir Expr
<'hir
>),
1910 /// A literal (e.g., `1`, `"foo"`).
1912 /// A cast (e.g., `foo as f64`).
1913 Cast(&'hir Expr
<'hir
>, &'hir Ty
<'hir
>),
1914 /// A type reference (e.g., `Foo`).
1915 Type(&'hir Expr
<'hir
>, &'hir Ty
<'hir
>),
1916 /// Wraps the expression in a terminating scope.
1917 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1919 /// This construct only exists to tweak the drop order in HIR lowering.
1920 /// An example of that is the desugaring of `for` loops.
1921 DropTemps(&'hir Expr
<'hir
>),
1922 /// A `let $pat = $expr` expression.
1924 /// These are not `Local` and only occur as expressions.
1925 /// The `let Some(x) = foo()` in `if let Some(x) = foo()` is an example of `Let(..)`.
1926 Let(&'hir Let
<'hir
>),
1927 /// An `if` block, with an optional else block.
1929 /// I.e., `if <expr> { <expr> } else { <expr> }`.
1930 If(&'hir Expr
<'hir
>, &'hir Expr
<'hir
>, Option
<&'hir Expr
<'hir
>>),
1931 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1933 /// I.e., `'label: loop { <block> }`.
1935 /// The `Span` is the loop header (`for x in y`/`while let pat = expr`).
1936 Loop(&'hir Block
<'hir
>, Option
<Label
>, LoopSource
, Span
),
1937 /// A `match` block, with a source that indicates whether or not it is
1938 /// the result of a desugaring, and if so, which kind.
1939 Match(&'hir Expr
<'hir
>, &'hir
[Arm
<'hir
>], MatchSource
),
1940 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1942 /// The `Span` is the argument block `|...|`.
1944 /// This may also be a generator literal or an `async block` as indicated by the
1945 /// `Option<Movability>`.
1946 Closure(&'hir Closure
<'hir
>),
1947 /// A block (e.g., `'label: { ... }`).
1948 Block(&'hir Block
<'hir
>, Option
<Label
>),
1950 /// An assignment (e.g., `a = foo()`).
1951 Assign(&'hir Expr
<'hir
>, &'hir Expr
<'hir
>, Span
),
1952 /// An assignment with an operator.
1955 AssignOp(BinOp
, &'hir Expr
<'hir
>, &'hir Expr
<'hir
>),
1956 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1957 Field(&'hir Expr
<'hir
>, Ident
),
1958 /// An indexing operation (`foo[2]`).
1959 Index(&'hir Expr
<'hir
>, &'hir Expr
<'hir
>),
1961 /// Path to a definition, possibly containing lifetime or type parameters.
1964 /// A referencing operation (i.e., `&a` or `&mut a`).
1965 AddrOf(BorrowKind
, Mutability
, &'hir Expr
<'hir
>),
1966 /// A `break`, with an optional label to break.
1967 Break(Destination
, Option
<&'hir Expr
<'hir
>>),
1968 /// A `continue`, with an optional label.
1969 Continue(Destination
),
1970 /// A `return`, with an optional value to be returned.
1971 Ret(Option
<&'hir Expr
<'hir
>>),
1973 /// Inline assembly (from `asm!`), with its outputs and inputs.
1974 InlineAsm(&'hir InlineAsm
<'hir
>),
1976 /// A struct or struct-like variant literal expression.
1978 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1979 /// where `base` is the `Option<Expr>`.
1980 Struct(&'hir QPath
<'hir
>, &'hir
[ExprField
<'hir
>], Option
<&'hir Expr
<'hir
>>),
1982 /// An array literal constructed from one repeated element.
1984 /// E.g., `[1; 5]`. The first expression is the element
1985 /// to be repeated; the second is the number of times to repeat it.
1986 Repeat(&'hir Expr
<'hir
>, ArrayLen
),
1988 /// A suspension point for generators (i.e., `yield <expr>`).
1989 Yield(&'hir Expr
<'hir
>, YieldSource
),
1991 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1995 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1997 /// To resolve the path to a `DefId`, call [`qpath_res`].
1999 /// [`qpath_res`]: ../../rustc_middle/ty/struct.TypeckResults.html#method.qpath_res
2000 #[derive(Debug, HashStable_Generic)]
2001 pub enum QPath
<'hir
> {
2002 /// Path to a definition, optionally "fully-qualified" with a `Self`
2003 /// type, if the path points to an associated item in a trait.
2005 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
2006 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
2007 /// even though they both have the same two-segment `Clone::clone` `Path`.
2008 Resolved(Option
<&'hir Ty
<'hir
>>, &'hir Path
<'hir
>),
2010 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
2011 /// Will be resolved by type-checking to an associated item.
2013 /// UFCS source paths can desugar into this, with `Vec::new` turning into
2014 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
2015 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
2016 TypeRelative(&'hir Ty
<'hir
>, &'hir PathSegment
<'hir
>),
2018 /// Reference to a `#[lang = "foo"]` item. `HirId` of the inner expr.
2019 LangItem(LangItem
, Span
, Option
<HirId
>),
2022 impl<'hir
> QPath
<'hir
> {
2023 /// Returns the span of this `QPath`.
2024 pub fn span(&self) -> Span
{
2026 QPath
::Resolved(_
, path
) => path
.span
,
2027 QPath
::TypeRelative(qself
, ps
) => qself
.span
.to(ps
.ident
.span
),
2028 QPath
::LangItem(_
, span
, _
) => span
,
2032 /// Returns the span of the qself of this `QPath`. For example, `()` in
2033 /// `<() as Trait>::method`.
2034 pub fn qself_span(&self) -> Span
{
2036 QPath
::Resolved(_
, path
) => path
.span
,
2037 QPath
::TypeRelative(qself
, _
) => qself
.span
,
2038 QPath
::LangItem(_
, span
, _
) => span
,
2042 /// Returns the span of the last segment of this `QPath`. For example, `method` in
2043 /// `<() as Trait>::method`.
2044 pub fn last_segment_span(&self) -> Span
{
2046 QPath
::Resolved(_
, path
) => path
.segments
.last().unwrap().ident
.span
,
2047 QPath
::TypeRelative(_
, segment
) => segment
.ident
.span
,
2048 QPath
::LangItem(_
, span
, _
) => span
,
2053 /// Hints at the original code for a let statement.
2054 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2055 pub enum LocalSource
{
2056 /// A `match _ { .. }`.
2058 /// When lowering async functions, we create locals within the `async move` so that
2059 /// all parameters are dropped after the future is polled.
2061 /// ```ignore (pseudo-Rust)
2062 /// async fn foo(<pattern> @ x: Type) {
2064 /// let <pattern> = x;
2069 /// A desugared `<expr>.await`.
2071 /// A desugared `expr = expr`, where the LHS is a tuple, struct or array.
2072 /// The span is that of the `=` sign.
2073 AssignDesugar(Span
),
2076 /// Hints at the original code for a `match _ { .. }`.
2077 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
2078 #[derive(HashStable_Generic)]
2079 pub enum MatchSource
{
2080 /// A `match _ { .. }`.
2082 /// A desugared `for _ in _ { .. }` loop.
2084 /// A desugared `?` operator.
2086 /// A desugared `<expr>.await`.
2092 pub const fn name(self) -> &'
static str {
2096 ForLoopDesugar
=> "for",
2098 AwaitDesugar
=> ".await",
2103 /// The loop type that yielded an `ExprKind::Loop`.
2104 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2105 pub enum LoopSource
{
2106 /// A `loop { .. }` loop.
2108 /// A `while _ { .. }` loop.
2110 /// A `for _ in _ { .. }` loop.
2115 pub fn name(self) -> &'
static str {
2117 LoopSource
::Loop
=> "loop",
2118 LoopSource
::While
=> "while",
2119 LoopSource
::ForLoop
=> "for",
2124 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2125 pub enum LoopIdError
{
2127 UnlabeledCfInWhileCondition
,
2131 impl fmt
::Display
for LoopIdError
{
2132 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2133 f
.write_str(match self {
2134 LoopIdError
::OutsideLoopScope
=> "not inside loop scope",
2135 LoopIdError
::UnlabeledCfInWhileCondition
=> {
2136 "unlabeled control flow (break or continue) in while condition"
2138 LoopIdError
::UnresolvedLabel
=> "label not found",
2143 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2144 pub struct Destination
{
2145 // This is `Some(_)` iff there is an explicit user-specified `label
2146 pub label
: Option
<Label
>,
2148 // These errors are caught and then reported during the diagnostics pass in
2149 // librustc_passes/loops.rs
2150 pub target_id
: Result
<HirId
, LoopIdError
>,
2153 /// The yield kind that caused an `ExprKind::Yield`.
2154 #[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
2155 pub enum YieldSource
{
2156 /// An `<expr>.await`.
2157 Await { expr: Option<HirId> }
,
2158 /// A plain `yield`.
2163 pub fn is_await(&self) -> bool
{
2164 matches
!(self, YieldSource
::Await { .. }
)
2168 impl fmt
::Display
for YieldSource
{
2169 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2170 f
.write_str(match self {
2171 YieldSource
::Await { .. }
=> "`await`",
2172 YieldSource
::Yield
=> "`yield`",
2177 impl From
<GeneratorKind
> for YieldSource
{
2178 fn from(kind
: GeneratorKind
) -> Self {
2180 // Guess based on the kind of the current generator.
2181 GeneratorKind
::Gen
=> Self::Yield
,
2182 GeneratorKind
::Async(_
) => Self::Await { expr: None }
,
2187 // N.B., if you change this, you'll probably want to change the corresponding
2188 // type structure in middle/ty.rs as well.
2189 #[derive(Debug, HashStable_Generic)]
2190 pub struct MutTy
<'hir
> {
2191 pub ty
: &'hir Ty
<'hir
>,
2192 pub mutbl
: Mutability
,
2195 /// Represents a function's signature in a trait declaration,
2196 /// trait implementation, or a free function.
2197 #[derive(Debug, HashStable_Generic)]
2198 pub struct FnSig
<'hir
> {
2199 pub header
: FnHeader
,
2200 pub decl
: &'hir FnDecl
<'hir
>,
2204 // The bodies for items are stored "out of line", in a separate
2205 // hashmap in the `Crate`. Here we just record the hir-id of the item
2206 // so it can fetched later.
2207 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2208 pub struct TraitItemId
{
2209 pub def_id
: LocalDefId
,
2214 pub fn hir_id(&self) -> HirId
{
2215 // Items are always HIR owners.
2216 HirId
::make_owner(self.def_id
)
2220 /// Represents an item declaration within a trait declaration,
2221 /// possibly including a default implementation. A trait item is
2222 /// either required (meaning it doesn't have an implementation, just a
2223 /// signature) or provided (meaning it has a default implementation).
2224 #[derive(Debug, HashStable_Generic)]
2225 pub struct TraitItem
<'hir
> {
2227 pub def_id
: LocalDefId
,
2228 pub generics
: &'hir Generics
<'hir
>,
2229 pub kind
: TraitItemKind
<'hir
>,
2231 pub defaultness
: Defaultness
,
2234 impl TraitItem
<'_
> {
2236 pub fn hir_id(&self) -> HirId
{
2237 // Items are always HIR owners.
2238 HirId
::make_owner(self.def_id
)
2241 pub fn trait_item_id(&self) -> TraitItemId
{
2242 TraitItemId { def_id: self.def_id }
2246 /// Represents a trait method's body (or just argument names).
2247 #[derive(Encodable, Debug, HashStable_Generic)]
2248 pub enum TraitFn
<'hir
> {
2249 /// No default body in the trait, just a signature.
2250 Required(&'hir
[Ident
]),
2252 /// Both signature and body are provided in the trait.
2256 /// Represents a trait method or associated constant or type
2257 #[derive(Debug, HashStable_Generic)]
2258 pub enum TraitItemKind
<'hir
> {
2259 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
2260 Const(&'hir Ty
<'hir
>, Option
<BodyId
>),
2261 /// An associated function with an optional body.
2262 Fn(FnSig
<'hir
>, TraitFn
<'hir
>),
2263 /// An associated type with (possibly empty) bounds and optional concrete
2265 Type(GenericBounds
<'hir
>, Option
<&'hir Ty
<'hir
>>),
2268 // The bodies for items are stored "out of line", in a separate
2269 // hashmap in the `Crate`. Here we just record the hir-id of the item
2270 // so it can fetched later.
2271 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2272 pub struct ImplItemId
{
2273 pub def_id
: LocalDefId
,
2278 pub fn hir_id(&self) -> HirId
{
2279 // Items are always HIR owners.
2280 HirId
::make_owner(self.def_id
)
2284 /// Represents anything within an `impl` block.
2285 #[derive(Debug, HashStable_Generic)]
2286 pub struct ImplItem
<'hir
> {
2288 pub def_id
: LocalDefId
,
2289 pub generics
: &'hir Generics
<'hir
>,
2290 pub kind
: ImplItemKind
<'hir
>,
2291 pub defaultness
: Defaultness
,
2298 pub fn hir_id(&self) -> HirId
{
2299 // Items are always HIR owners.
2300 HirId
::make_owner(self.def_id
)
2303 pub fn impl_item_id(&self) -> ImplItemId
{
2304 ImplItemId { def_id: self.def_id }
2308 /// Represents various kinds of content within an `impl`.
2309 #[derive(Debug, HashStable_Generic)]
2310 pub enum ImplItemKind
<'hir
> {
2311 /// An associated constant of the given type, set to the constant result
2312 /// of the expression.
2313 Const(&'hir Ty
<'hir
>, BodyId
),
2314 /// An associated function implementation with the given signature and body.
2315 Fn(FnSig
<'hir
>, BodyId
),
2316 /// An associated type.
2317 TyAlias(&'hir Ty
<'hir
>),
2320 // The name of the associated type for `Fn` return types.
2321 pub const FN_OUTPUT_NAME
: Symbol
= sym
::Output
;
2323 /// Bind a type to an associated type (i.e., `A = Foo`).
2325 /// Bindings like `A: Debug` are represented as a special type `A =
2326 /// $::Debug` that is understood by the astconv code.
2328 /// FIXME(alexreg): why have a separate type for the binding case,
2329 /// wouldn't it be better to make the `ty` field an enum like the
2332 /// ```ignore (pseudo-rust)
2333 /// enum TypeBindingKind {
2338 #[derive(Debug, HashStable_Generic)]
2339 pub struct TypeBinding
<'hir
> {
2342 pub gen_args
: &'hir GenericArgs
<'hir
>,
2343 pub kind
: TypeBindingKind
<'hir
>,
2347 #[derive(Debug, HashStable_Generic)]
2348 pub enum Term
<'hir
> {
2353 impl<'hir
> From
<&'hir Ty
<'hir
>> for Term
<'hir
> {
2354 fn from(ty
: &'hir Ty
<'hir
>) -> Self {
2359 impl<'hir
> From
<AnonConst
> for Term
<'hir
> {
2360 fn from(c
: AnonConst
) -> Self {
2365 // Represents the two kinds of type bindings.
2366 #[derive(Debug, HashStable_Generic)]
2367 pub enum TypeBindingKind
<'hir
> {
2368 /// E.g., `Foo<Bar: Send>`.
2369 Constraint { bounds: &'hir [GenericBound<'hir>] }
,
2370 /// E.g., `Foo<Bar = ()>`, `Foo<Bar = ()>`
2371 Equality { term: Term<'hir> }
,
2374 impl TypeBinding
<'_
> {
2375 pub fn ty(&self) -> &Ty
<'_
> {
2377 TypeBindingKind
::Equality { term: Term::Ty(ref ty) }
=> ty
,
2378 _
=> panic
!("expected equality type binding for parenthesized generic args"),
2381 pub fn opt_const(&self) -> Option
<&'_ AnonConst
> {
2383 TypeBindingKind
::Equality { term: Term::Const(ref c) }
=> Some(c
),
2389 #[derive(Debug, HashStable_Generic)]
2390 pub struct Ty
<'hir
> {
2392 pub kind
: TyKind
<'hir
>,
2396 impl<'hir
> Ty
<'hir
> {
2397 /// Returns `true` if `param_def_id` matches the `bounded_ty` of this predicate.
2398 pub fn as_generic_param(&self) -> Option
<(DefId
, Ident
)> {
2399 let TyKind
::Path(QPath
::Resolved(None
, path
)) = self.kind
else {
2402 let [segment
] = &path
.segments
else {
2406 Res
::Def(DefKind
::TyParam
, def_id
)
2407 | Res
::SelfTy { trait_: Some(def_id), alias_to: None }
=> Some((def_id
, segment
.ident
)),
2412 pub fn peel_refs(&self) -> &Self {
2413 let mut final_ty
= self;
2414 while let TyKind
::Rptr(_
, MutTy { ty, .. }
) = &final_ty
.kind
{
2421 /// Not represented directly in the AST; referred to by name through a `ty_path`.
2422 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
2423 #[derive(HashStable_Generic)]
2434 /// All of the primitive types
2435 pub const ALL
: [Self; 17] = [
2436 // any changes here should also be reflected in `PrimTy::from_name`
2437 Self::Int(IntTy
::I8
),
2438 Self::Int(IntTy
::I16
),
2439 Self::Int(IntTy
::I32
),
2440 Self::Int(IntTy
::I64
),
2441 Self::Int(IntTy
::I128
),
2442 Self::Int(IntTy
::Isize
),
2443 Self::Uint(UintTy
::U8
),
2444 Self::Uint(UintTy
::U16
),
2445 Self::Uint(UintTy
::U32
),
2446 Self::Uint(UintTy
::U64
),
2447 Self::Uint(UintTy
::U128
),
2448 Self::Uint(UintTy
::Usize
),
2449 Self::Float(FloatTy
::F32
),
2450 Self::Float(FloatTy
::F64
),
2456 /// Like [`PrimTy::name`], but returns a &str instead of a symbol.
2459 pub fn name_str(self) -> &'
static str {
2461 PrimTy
::Int(i
) => i
.name_str(),
2462 PrimTy
::Uint(u
) => u
.name_str(),
2463 PrimTy
::Float(f
) => f
.name_str(),
2464 PrimTy
::Str
=> "str",
2465 PrimTy
::Bool
=> "bool",
2466 PrimTy
::Char
=> "char",
2470 pub fn name(self) -> Symbol
{
2472 PrimTy
::Int(i
) => i
.name(),
2473 PrimTy
::Uint(u
) => u
.name(),
2474 PrimTy
::Float(f
) => f
.name(),
2475 PrimTy
::Str
=> sym
::str,
2476 PrimTy
::Bool
=> sym
::bool
,
2477 PrimTy
::Char
=> sym
::char,
2481 /// Returns the matching `PrimTy` for a `Symbol` such as "str" or "i32".
2482 /// Returns `None` if no matching type is found.
2483 pub fn from_name(name
: Symbol
) -> Option
<Self> {
2484 let ty
= match name
{
2485 // any changes here should also be reflected in `PrimTy::ALL`
2486 sym
::i8 => Self::Int(IntTy
::I8
),
2487 sym
::i16 => Self::Int(IntTy
::I16
),
2488 sym
::i32 => Self::Int(IntTy
::I32
),
2489 sym
::i64 => Self::Int(IntTy
::I64
),
2490 sym
::i128
=> Self::Int(IntTy
::I128
),
2491 sym
::isize => Self::Int(IntTy
::Isize
),
2492 sym
::u8 => Self::Uint(UintTy
::U8
),
2493 sym
::u16 => Self::Uint(UintTy
::U16
),
2494 sym
::u32 => Self::Uint(UintTy
::U32
),
2495 sym
::u64 => Self::Uint(UintTy
::U64
),
2496 sym
::u128
=> Self::Uint(UintTy
::U128
),
2497 sym
::usize => Self::Uint(UintTy
::Usize
),
2498 sym
::f32 => Self::Float(FloatTy
::F32
),
2499 sym
::f64 => Self::Float(FloatTy
::F64
),
2500 sym
::bool
=> Self::Bool
,
2501 sym
::char => Self::Char
,
2502 sym
::str => Self::Str
,
2509 #[derive(Debug, HashStable_Generic)]
2510 pub struct BareFnTy
<'hir
> {
2511 pub unsafety
: Unsafety
,
2513 pub generic_params
: &'hir
[GenericParam
<'hir
>],
2514 pub decl
: &'hir FnDecl
<'hir
>,
2515 pub param_names
: &'hir
[Ident
],
2518 #[derive(Debug, HashStable_Generic)]
2519 pub struct OpaqueTy
<'hir
> {
2520 pub generics
: &'hir Generics
<'hir
>,
2521 pub bounds
: GenericBounds
<'hir
>,
2522 pub origin
: OpaqueTyOrigin
,
2526 /// From whence the opaque type came.
2527 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2528 pub enum OpaqueTyOrigin
{
2530 FnReturn(LocalDefId
),
2532 AsyncFn(LocalDefId
),
2533 /// type aliases: `type Foo = impl Trait;`
2537 /// The various kinds of types recognized by the compiler.
2538 #[derive(Debug, HashStable_Generic)]
2539 pub enum TyKind
<'hir
> {
2540 /// A variable length slice (i.e., `[T]`).
2541 Slice(&'hir Ty
<'hir
>),
2542 /// A fixed length array (i.e., `[T; n]`).
2543 Array(&'hir Ty
<'hir
>, ArrayLen
),
2544 /// A raw pointer (i.e., `*const T` or `*mut T`).
2546 /// A reference (i.e., `&'a T` or `&'a mut T`).
2547 Rptr(&'hir Lifetime
, MutTy
<'hir
>),
2548 /// A bare function (e.g., `fn(usize) -> bool`).
2549 BareFn(&'hir BareFnTy
<'hir
>),
2550 /// The never type (`!`).
2552 /// A tuple (`(A, B, C, D, ...)`).
2553 Tup(&'hir
[Ty
<'hir
>]),
2554 /// A path to a type definition (`module::module::...::Type`), or an
2555 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2557 /// Type parameters may be stored in each `PathSegment`.
2559 /// An opaque type definition itself. This is only used for `impl Trait`.
2561 /// The generic argument list contains the lifetimes (and in the future
2562 /// possibly parameters) that are actually bound on the `impl Trait`.
2564 /// The last parameter specifies whether this opaque appears in a trait definition.
2565 OpaqueDef(ItemId
, &'hir
[GenericArg
<'hir
>], bool
),
2566 /// A trait object type `Bound1 + Bound2 + Bound3`
2567 /// where `Bound` is a trait or a lifetime.
2568 TraitObject(&'hir
[PolyTraitRef
<'hir
>], &'hir Lifetime
, TraitObjectSyntax
),
2571 /// `TyKind::Infer` means the type should be inferred instead of it having been
2572 /// specified. This can appear anywhere in a type.
2574 /// Placeholder for a type that has failed to be defined.
2578 #[derive(Debug, HashStable_Generic)]
2579 pub enum InlineAsmOperand
<'hir
> {
2581 reg
: InlineAsmRegOrRegClass
,
2582 expr
: &'hir Expr
<'hir
>,
2585 reg
: InlineAsmRegOrRegClass
,
2587 expr
: Option
<&'hir Expr
<'hir
>>,
2590 reg
: InlineAsmRegOrRegClass
,
2592 expr
: &'hir Expr
<'hir
>,
2595 reg
: InlineAsmRegOrRegClass
,
2597 in_expr
: &'hir Expr
<'hir
>,
2598 out_expr
: Option
<&'hir Expr
<'hir
>>,
2601 anon_const
: AnonConst
,
2604 anon_const
: AnonConst
,
2612 impl<'hir
> InlineAsmOperand
<'hir
> {
2613 pub fn reg(&self) -> Option
<InlineAsmRegOrRegClass
> {
2615 Self::In { reg, .. }
2616 | Self::Out { reg, .. }
2617 | Self::InOut { reg, .. }
2618 | Self::SplitInOut { reg, .. }
=> Some(reg
),
2619 Self::Const { .. }
| Self::SymFn { .. }
| Self::SymStatic { .. }
=> None
,
2623 pub fn is_clobber(&self) -> bool
{
2626 InlineAsmOperand
::Out { reg: InlineAsmRegOrRegClass::Reg(_), late: _, expr: None }
2631 #[derive(Debug, HashStable_Generic)]
2632 pub struct InlineAsm
<'hir
> {
2633 pub template
: &'hir
[InlineAsmTemplatePiece
],
2634 pub template_strs
: &'hir
[(Symbol
, Option
<Symbol
>, Span
)],
2635 pub operands
: &'hir
[(InlineAsmOperand
<'hir
>, Span
)],
2636 pub options
: InlineAsmOptions
,
2637 pub line_spans
: &'hir
[Span
],
2640 /// Represents a parameter in a function header.
2641 #[derive(Debug, HashStable_Generic)]
2642 pub struct Param
<'hir
> {
2644 pub pat
: &'hir Pat
<'hir
>,
2649 /// Represents the header (not the body) of a function declaration.
2650 #[derive(Debug, HashStable_Generic)]
2651 pub struct FnDecl
<'hir
> {
2652 /// The types of the function's parameters.
2654 /// Additional argument data is stored in the function's [body](Body::params).
2655 pub inputs
: &'hir
[Ty
<'hir
>],
2656 pub output
: FnRetTy
<'hir
>,
2657 pub c_variadic
: bool
,
2658 /// Does the function have an implicit self?
2659 pub implicit_self
: ImplicitSelfKind
,
2662 /// Represents what type of implicit self a function has, if any.
2663 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2664 pub enum ImplicitSelfKind
{
2665 /// Represents a `fn x(self);`.
2667 /// Represents a `fn x(mut self);`.
2669 /// Represents a `fn x(&self);`.
2671 /// Represents a `fn x(&mut self);`.
2673 /// Represents when a function does not have a self argument or
2674 /// when a function has a `self: X` argument.
2678 impl ImplicitSelfKind
{
2679 /// Does this represent an implicit self?
2680 pub fn has_implicit_self(&self) -> bool
{
2681 !matches
!(*self, ImplicitSelfKind
::None
)
2685 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable, Debug)]
2686 #[derive(HashStable_Generic)]
2692 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable, HashStable_Generic)]
2693 pub enum Defaultness
{
2694 Default { has_value: bool }
,
2699 pub fn has_value(&self) -> bool
{
2701 Defaultness
::Default { has_value }
=> has_value
,
2702 Defaultness
::Final
=> true,
2706 pub fn is_final(&self) -> bool
{
2707 *self == Defaultness
::Final
2710 pub fn is_default(&self) -> bool
{
2711 matches
!(*self, Defaultness
::Default { .. }
)
2715 #[derive(Debug, HashStable_Generic)]
2716 pub enum FnRetTy
<'hir
> {
2717 /// Return type is not specified.
2719 /// Functions default to `()` and
2720 /// closures default to inference. Span points to where return
2721 /// type would be inserted.
2722 DefaultReturn(Span
),
2723 /// Everything else.
2724 Return(&'hir Ty
<'hir
>),
2729 pub fn span(&self) -> Span
{
2731 Self::DefaultReturn(span
) => span
,
2732 Self::Return(ref ty
) => ty
.span
,
2737 /// Represents `for<...>` binder before a closure
2738 #[derive(Copy, Clone, Debug, HashStable_Generic)]
2739 pub enum ClosureBinder
{
2740 /// Binder is not specified.
2742 /// Binder is specified.
2744 /// Span points to the whole `for<...>`.
2748 #[derive(Encodable, Debug, HashStable_Generic)]
2749 pub struct Mod
<'hir
> {
2750 pub spans
: ModSpans
,
2751 pub item_ids
: &'hir
[ItemId
],
2754 #[derive(Copy, Clone, Debug, HashStable_Generic, Encodable)]
2755 pub struct ModSpans
{
2756 /// A span from the first token past `{` to the last token until `}`.
2757 /// For `mod foo;`, the inner span ranges from the first token
2758 /// to the last token in the external file.
2759 pub inner_span
: Span
,
2760 pub inject_use_span
: Span
,
2763 #[derive(Debug, HashStable_Generic)]
2764 pub struct EnumDef
<'hir
> {
2765 pub variants
: &'hir
[Variant
<'hir
>],
2768 #[derive(Debug, HashStable_Generic)]
2769 pub struct Variant
<'hir
> {
2770 /// Name of the variant.
2772 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2774 /// Fields and constructor id of the variant.
2775 pub data
: VariantData
<'hir
>,
2776 /// Explicit discriminant (e.g., `Foo = 1`).
2777 pub disr_expr
: Option
<AnonConst
>,
2782 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2784 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2785 /// Also produced for each element of a list `use`, e.g.
2786 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2789 /// Glob import, e.g., `use foo::*`.
2792 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2793 /// an additional `use foo::{}` for performing checks such as
2794 /// unstable feature gating. May be removed in the future.
2798 /// References to traits in impls.
2800 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2801 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2802 /// trait being referred to but just a unique `HirId` that serves as a key
2803 /// within the resolution map.
2804 #[derive(Clone, Debug, HashStable_Generic)]
2805 pub struct TraitRef
<'hir
> {
2806 pub path
: &'hir Path
<'hir
>,
2807 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2808 #[stable_hasher(ignore)]
2809 pub hir_ref_id
: HirId
,
2813 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2814 pub fn trait_def_id(&self) -> Option
<DefId
> {
2815 match self.path
.res
{
2816 Res
::Def(DefKind
::Trait
| DefKind
::TraitAlias
, did
) => Some(did
),
2818 _
=> unreachable
!(),
2823 #[derive(Clone, Debug, HashStable_Generic)]
2824 pub struct PolyTraitRef
<'hir
> {
2825 /// The `'a` in `for<'a> Foo<&'a T>`.
2826 pub bound_generic_params
: &'hir
[GenericParam
<'hir
>],
2828 /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
2829 pub trait_ref
: TraitRef
<'hir
>,
2834 #[derive(Debug, HashStable_Generic)]
2835 pub struct FieldDef
<'hir
> {
2840 pub ty
: &'hir Ty
<'hir
>,
2844 // Still necessary in couple of places
2845 pub fn is_positional(&self) -> bool
{
2846 let first
= self.ident
.as_str().as_bytes()[0];
2847 (b'
0'
..=b'
9'
).contains(&first
)
2851 /// Fields and constructor IDs of enum variants and structs.
2852 #[derive(Debug, HashStable_Generic)]
2853 pub enum VariantData
<'hir
> {
2854 /// A struct variant.
2856 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2857 Struct(&'hir
[FieldDef
<'hir
>], /* recovered */ bool
),
2858 /// A tuple variant.
2860 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2861 Tuple(&'hir
[FieldDef
<'hir
>], HirId
),
2864 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2868 impl<'hir
> VariantData
<'hir
> {
2869 /// Return the fields of this variant.
2870 pub fn fields(&self) -> &'hir
[FieldDef
<'hir
>] {
2872 VariantData
::Struct(ref fields
, ..) | VariantData
::Tuple(ref fields
, ..) => fields
,
2877 /// Return the `HirId` of this variant's constructor, if it has one.
2878 pub fn ctor_hir_id(&self) -> Option
<HirId
> {
2880 VariantData
::Struct(_
, _
) => None
,
2881 VariantData
::Tuple(_
, hir_id
) | VariantData
::Unit(hir_id
) => Some(hir_id
),
2886 // The bodies for items are stored "out of line", in a separate
2887 // hashmap in the `Crate`. Here we just record the hir-id of the item
2888 // so it can fetched later.
2889 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
2891 pub def_id
: LocalDefId
,
2896 pub fn hir_id(&self) -> HirId
{
2897 // Items are always HIR owners.
2898 HirId
::make_owner(self.def_id
)
2904 /// The name might be a dummy name in case of anonymous items
2905 #[derive(Debug, HashStable_Generic)]
2906 pub struct Item
<'hir
> {
2908 pub def_id
: LocalDefId
,
2909 pub kind
: ItemKind
<'hir
>,
2916 pub fn hir_id(&self) -> HirId
{
2917 // Items are always HIR owners.
2918 HirId
::make_owner(self.def_id
)
2921 pub fn item_id(&self) -> ItemId
{
2922 ItemId { def_id: self.def_id }
2926 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2927 #[derive(Encodable, Decodable, HashStable_Generic)]
2934 pub fn prefix_str(&self) -> &'
static str {
2936 Self::Unsafe
=> "unsafe ",
2942 impl fmt
::Display
for Unsafety
{
2943 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2944 f
.write_str(match *self {
2945 Self::Unsafe
=> "unsafe",
2946 Self::Normal
=> "normal",
2951 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2952 #[derive(Encodable, Decodable, HashStable_Generic)]
2953 pub enum Constness
{
2958 impl fmt
::Display
for Constness
{
2959 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2960 f
.write_str(match *self {
2961 Self::Const
=> "const",
2962 Self::NotConst
=> "non-const",
2967 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2968 pub struct FnHeader
{
2969 pub unsafety
: Unsafety
,
2970 pub constness
: Constness
,
2971 pub asyncness
: IsAsync
,
2976 pub fn is_async(&self) -> bool
{
2977 matches
!(&self.asyncness
, IsAsync
::Async
)
2980 pub fn is_const(&self) -> bool
{
2981 matches
!(&self.constness
, Constness
::Const
)
2984 pub fn is_unsafe(&self) -> bool
{
2985 matches
!(&self.unsafety
, Unsafety
::Unsafe
)
2989 #[derive(Debug, HashStable_Generic)]
2990 pub enum ItemKind
<'hir
> {
2991 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2993 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2994 ExternCrate(Option
<Symbol
>),
2996 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
3000 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
3001 Use(&'hir Path
<'hir
>, UseKind
),
3003 /// A `static` item.
3004 Static(&'hir Ty
<'hir
>, Mutability
, BodyId
),
3006 Const(&'hir Ty
<'hir
>, BodyId
),
3007 /// A function declaration.
3008 Fn(FnSig
<'hir
>, &'hir Generics
<'hir
>, BodyId
),
3009 /// A MBE macro definition (`macro_rules!` or `macro`).
3010 Macro(ast
::MacroDef
, MacroKind
),
3012 Mod(&'hir Mod
<'hir
>),
3013 /// An external module, e.g. `extern { .. }`.
3014 ForeignMod { abi: Abi, items: &'hir [ForeignItemRef] }
,
3015 /// Module-level inline assembly (from `global_asm!`).
3016 GlobalAsm(&'hir InlineAsm
<'hir
>),
3017 /// A type alias, e.g., `type Foo = Bar<u8>`.
3018 TyAlias(&'hir Ty
<'hir
>, &'hir Generics
<'hir
>),
3019 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
3020 OpaqueTy(OpaqueTy
<'hir
>),
3021 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
3022 Enum(EnumDef
<'hir
>, &'hir Generics
<'hir
>),
3023 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
3024 Struct(VariantData
<'hir
>, &'hir Generics
<'hir
>),
3025 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
3026 Union(VariantData
<'hir
>, &'hir Generics
<'hir
>),
3027 /// A trait definition.
3028 Trait(IsAuto
, Unsafety
, &'hir Generics
<'hir
>, GenericBounds
<'hir
>, &'hir
[TraitItemRef
]),
3030 TraitAlias(&'hir Generics
<'hir
>, GenericBounds
<'hir
>),
3032 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
3033 Impl(&'hir Impl
<'hir
>),
3036 #[derive(Debug, HashStable_Generic)]
3037 pub struct Impl
<'hir
> {
3038 pub unsafety
: Unsafety
,
3039 pub polarity
: ImplPolarity
,
3040 pub defaultness
: Defaultness
,
3041 // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata
3042 // decoding as `Span`s cannot be decoded when a `Session` is not available.
3043 pub defaultness_span
: Option
<Span
>,
3044 pub constness
: Constness
,
3045 pub generics
: &'hir Generics
<'hir
>,
3047 /// The trait being implemented, if any.
3048 pub of_trait
: Option
<TraitRef
<'hir
>>,
3050 pub self_ty
: &'hir Ty
<'hir
>,
3051 pub items
: &'hir
[ImplItemRef
],
3055 pub fn generics(&self) -> Option
<&Generics
<'_
>> {
3057 ItemKind
::Fn(_
, ref generics
, _
)
3058 | ItemKind
::TyAlias(_
, ref generics
)
3059 | ItemKind
::OpaqueTy(OpaqueTy { ref generics, .. }
)
3060 | ItemKind
::Enum(_
, ref generics
)
3061 | ItemKind
::Struct(_
, ref generics
)
3062 | ItemKind
::Union(_
, ref generics
)
3063 | ItemKind
::Trait(_
, _
, ref generics
, _
, _
)
3064 | ItemKind
::TraitAlias(ref generics
, _
)
3065 | ItemKind
::Impl(Impl { ref generics, .. }
) => generics
,
3070 pub fn descr(&self) -> &'
static str {
3072 ItemKind
::ExternCrate(..) => "extern crate",
3073 ItemKind
::Use(..) => "`use` import",
3074 ItemKind
::Static(..) => "static item",
3075 ItemKind
::Const(..) => "constant item",
3076 ItemKind
::Fn(..) => "function",
3077 ItemKind
::Macro(..) => "macro",
3078 ItemKind
::Mod(..) => "module",
3079 ItemKind
::ForeignMod { .. }
=> "extern block",
3080 ItemKind
::GlobalAsm(..) => "global asm item",
3081 ItemKind
::TyAlias(..) => "type alias",
3082 ItemKind
::OpaqueTy(..) => "opaque type",
3083 ItemKind
::Enum(..) => "enum",
3084 ItemKind
::Struct(..) => "struct",
3085 ItemKind
::Union(..) => "union",
3086 ItemKind
::Trait(..) => "trait",
3087 ItemKind
::TraitAlias(..) => "trait alias",
3088 ItemKind
::Impl(..) => "implementation",
3093 /// A reference from an trait to one of its associated items. This
3094 /// contains the item's id, naturally, but also the item's name and
3095 /// some other high-level details (like whether it is an associated
3096 /// type or method, and whether it is public). This allows other
3097 /// passes to find the impl they want without loading the ID (which
3098 /// means fewer edges in the incremental compilation graph).
3099 #[derive(Encodable, Debug, HashStable_Generic)]
3100 pub struct TraitItemRef
{
3101 pub id
: TraitItemId
,
3103 pub kind
: AssocItemKind
,
3107 /// A reference from an impl to one of its associated items. This
3108 /// contains the item's ID, naturally, but also the item's name and
3109 /// some other high-level details (like whether it is an associated
3110 /// type or method, and whether it is public). This allows other
3111 /// passes to find the impl they want without loading the ID (which
3112 /// means fewer edges in the incremental compilation graph).
3113 #[derive(Debug, HashStable_Generic)]
3114 pub struct ImplItemRef
{
3117 pub kind
: AssocItemKind
,
3119 /// When we are in a trait impl, link to the trait-item's id.
3120 pub trait_item_def_id
: Option
<DefId
>,
3123 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
3124 pub enum AssocItemKind
{
3126 Fn { has_self: bool }
,
3130 // The bodies for items are stored "out of line", in a separate
3131 // hashmap in the `Crate`. Here we just record the hir-id of the item
3132 // so it can fetched later.
3133 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3134 pub struct ForeignItemId
{
3135 pub def_id
: LocalDefId
,
3138 impl ForeignItemId
{
3140 pub fn hir_id(&self) -> HirId
{
3141 // Items are always HIR owners.
3142 HirId
::make_owner(self.def_id
)
3146 /// A reference from a foreign block to one of its items. This
3147 /// contains the item's ID, naturally, but also the item's name and
3148 /// some other high-level details (like whether it is an associated
3149 /// type or method, and whether it is public). This allows other
3150 /// passes to find the impl they want without loading the ID (which
3151 /// means fewer edges in the incremental compilation graph).
3152 #[derive(Debug, HashStable_Generic)]
3153 pub struct ForeignItemRef
{
3154 pub id
: ForeignItemId
,
3159 #[derive(Debug, HashStable_Generic)]
3160 pub struct ForeignItem
<'hir
> {
3162 pub kind
: ForeignItemKind
<'hir
>,
3163 pub def_id
: LocalDefId
,
3168 impl ForeignItem
<'_
> {
3170 pub fn hir_id(&self) -> HirId
{
3171 // Items are always HIR owners.
3172 HirId
::make_owner(self.def_id
)
3175 pub fn foreign_item_id(&self) -> ForeignItemId
{
3176 ForeignItemId { def_id: self.def_id }
3180 /// An item within an `extern` block.
3181 #[derive(Debug, HashStable_Generic)]
3182 pub enum ForeignItemKind
<'hir
> {
3183 /// A foreign function.
3184 Fn(&'hir FnDecl
<'hir
>, &'hir
[Ident
], &'hir Generics
<'hir
>),
3185 /// A foreign static item (`static ext: u8`).
3186 Static(&'hir Ty
<'hir
>, Mutability
),
3191 /// A variable captured by a closure.
3192 #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)]
3194 // First span where it is accessed (there can be multiple).
3198 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
3199 // has length > 0 if the trait is found through an chain of imports, starting with the
3200 // import/use statement in the scope where the trait is used.
3201 #[derive(Encodable, Decodable, Clone, Debug, HashStable_Generic)]
3202 pub struct TraitCandidate
{
3204 pub import_ids
: SmallVec
<[LocalDefId
; 1]>,
3207 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3208 pub enum OwnerNode
<'hir
> {
3209 Item(&'hir Item
<'hir
>),
3210 ForeignItem(&'hir ForeignItem
<'hir
>),
3211 TraitItem(&'hir TraitItem
<'hir
>),
3212 ImplItem(&'hir ImplItem
<'hir
>),
3213 Crate(&'hir Mod
<'hir
>),
3216 impl<'hir
> OwnerNode
<'hir
> {
3217 pub fn ident(&self) -> Option
<Ident
> {
3219 OwnerNode
::Item(Item { ident, .. }
)
3220 | OwnerNode
::ForeignItem(ForeignItem { ident, .. }
)
3221 | OwnerNode
::ImplItem(ImplItem { ident, .. }
)
3222 | OwnerNode
::TraitItem(TraitItem { ident, .. }
) => Some(*ident
),
3223 OwnerNode
::Crate(..) => None
,
3227 pub fn span(&self) -> Span
{
3229 OwnerNode
::Item(Item { span, .. }
)
3230 | OwnerNode
::ForeignItem(ForeignItem { span, .. }
)
3231 | OwnerNode
::ImplItem(ImplItem { span, .. }
)
3232 | OwnerNode
::TraitItem(TraitItem { span, .. }
) => *span
,
3233 OwnerNode
::Crate(Mod { spans: ModSpans { inner_span, .. }
, .. }) => *inner_span
,
3237 pub fn fn_decl(self) -> Option
<&'hir FnDecl
<'hir
>> {
3239 OwnerNode
::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. }
)
3240 | OwnerNode
::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. }
)
3241 | OwnerNode
::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }
) => Some(fn_sig
.decl
),
3242 OwnerNode
::ForeignItem(ForeignItem
{
3243 kind
: ForeignItemKind
::Fn(fn_decl
, _
, _
),
3245 }) => Some(fn_decl
),
3250 pub fn body_id(&self) -> Option
<BodyId
> {
3252 OwnerNode
::TraitItem(TraitItem
{
3253 kind
: TraitItemKind
::Fn(_
, TraitFn
::Provided(body_id
)),
3256 | OwnerNode
::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. }
)
3257 | OwnerNode
::Item(Item { kind: ItemKind::Fn(.., body_id), .. }
) => Some(*body_id
),
3262 pub fn generics(self) -> Option
<&'hir Generics
<'hir
>> {
3263 Node
::generics(self.into())
3266 pub fn def_id(self) -> LocalDefId
{
3268 OwnerNode
::Item(Item { def_id, .. }
)
3269 | OwnerNode
::TraitItem(TraitItem { def_id, .. }
)
3270 | OwnerNode
::ImplItem(ImplItem { def_id, .. }
)
3271 | OwnerNode
::ForeignItem(ForeignItem { def_id, .. }
) => *def_id
,
3272 OwnerNode
::Crate(..) => crate::CRATE_HIR_ID
.owner
,
3276 pub fn expect_item(self) -> &'hir Item
<'hir
> {
3278 OwnerNode
::Item(n
) => n
,
3283 pub fn expect_foreign_item(self) -> &'hir ForeignItem
<'hir
> {
3285 OwnerNode
::ForeignItem(n
) => n
,
3290 pub fn expect_impl_item(self) -> &'hir ImplItem
<'hir
> {
3292 OwnerNode
::ImplItem(n
) => n
,
3297 pub fn expect_trait_item(self) -> &'hir TraitItem
<'hir
> {
3299 OwnerNode
::TraitItem(n
) => n
,
3305 impl<'hir
> Into
<OwnerNode
<'hir
>> for &'hir Item
<'hir
> {
3306 fn into(self) -> OwnerNode
<'hir
> {
3307 OwnerNode
::Item(self)
3311 impl<'hir
> Into
<OwnerNode
<'hir
>> for &'hir ForeignItem
<'hir
> {
3312 fn into(self) -> OwnerNode
<'hir
> {
3313 OwnerNode
::ForeignItem(self)
3317 impl<'hir
> Into
<OwnerNode
<'hir
>> for &'hir ImplItem
<'hir
> {
3318 fn into(self) -> OwnerNode
<'hir
> {
3319 OwnerNode
::ImplItem(self)
3323 impl<'hir
> Into
<OwnerNode
<'hir
>> for &'hir TraitItem
<'hir
> {
3324 fn into(self) -> OwnerNode
<'hir
> {
3325 OwnerNode
::TraitItem(self)
3329 impl<'hir
> Into
<Node
<'hir
>> for OwnerNode
<'hir
> {
3330 fn into(self) -> Node
<'hir
> {
3332 OwnerNode
::Item(n
) => Node
::Item(n
),
3333 OwnerNode
::ForeignItem(n
) => Node
::ForeignItem(n
),
3334 OwnerNode
::ImplItem(n
) => Node
::ImplItem(n
),
3335 OwnerNode
::TraitItem(n
) => Node
::TraitItem(n
),
3336 OwnerNode
::Crate(n
) => Node
::Crate(n
),
3341 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3342 pub enum Node
<'hir
> {
3343 Param(&'hir Param
<'hir
>),
3344 Item(&'hir Item
<'hir
>),
3345 ForeignItem(&'hir ForeignItem
<'hir
>),
3346 TraitItem(&'hir TraitItem
<'hir
>),
3347 ImplItem(&'hir ImplItem
<'hir
>),
3348 Variant(&'hir Variant
<'hir
>),
3349 Field(&'hir FieldDef
<'hir
>),
3350 AnonConst(&'hir AnonConst
),
3351 Expr(&'hir Expr
<'hir
>),
3352 ExprField(&'hir ExprField
<'hir
>),
3353 Stmt(&'hir Stmt
<'hir
>),
3354 PathSegment(&'hir PathSegment
<'hir
>),
3356 TypeBinding(&'hir TypeBinding
<'hir
>),
3357 TraitRef(&'hir TraitRef
<'hir
>),
3358 Pat(&'hir Pat
<'hir
>),
3359 PatField(&'hir PatField
<'hir
>),
3360 Arm(&'hir Arm
<'hir
>),
3361 Block(&'hir Block
<'hir
>),
3362 Local(&'hir Local
<'hir
>),
3364 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
3365 /// with synthesized constructors.
3366 Ctor(&'hir VariantData
<'hir
>),
3368 Lifetime(&'hir Lifetime
),
3369 GenericParam(&'hir GenericParam
<'hir
>),
3371 Crate(&'hir Mod
<'hir
>),
3373 Infer(&'hir InferArg
),
3376 impl<'hir
> Node
<'hir
> {
3377 /// Get the identifier of this `Node`, if applicable.
3381 /// Calling `.ident()` on a [`Node::Ctor`] will return `None`
3382 /// because `Ctor`s do not have identifiers themselves.
3383 /// Instead, call `.ident()` on the parent struct/variant, like so:
3385 /// ```ignore (illustrative)
3388 /// .and_then(|ctor_id| tcx.hir().find(tcx.hir().get_parent_node(ctor_id)))
3389 /// .and_then(|parent| parent.ident())
3391 pub fn ident(&self) -> Option
<Ident
> {
3393 Node
::TraitItem(TraitItem { ident, .. }
)
3394 | Node
::ImplItem(ImplItem { ident, .. }
)
3395 | Node
::ForeignItem(ForeignItem { ident, .. }
)
3396 | Node
::Field(FieldDef { ident, .. }
)
3397 | Node
::Variant(Variant { ident, .. }
)
3398 | Node
::Item(Item { ident, .. }
)
3399 | Node
::PathSegment(PathSegment { ident, .. }
) => Some(*ident
),
3400 Node
::Lifetime(lt
) => Some(lt
.name
.ident()),
3401 Node
::GenericParam(p
) => Some(p
.name
.ident()),
3402 Node
::TypeBinding(b
) => Some(b
.ident
),
3404 | Node
::AnonConst(..)
3410 | Node
::PatField(..)
3411 | Node
::ExprField(..)
3416 | Node
::TraitRef(..)
3417 | Node
::Infer(..) => None
,
3421 pub fn fn_decl(self) -> Option
<&'hir FnDecl
<'hir
>> {
3423 Node
::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. }
)
3424 | Node
::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. }
)
3425 | Node
::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }
) => Some(fn_sig
.decl
),
3426 Node
::Expr(Expr { kind: ExprKind::Closure(Closure { fn_decl, .. }
), .. })
3427 | Node
::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }
) => {
3434 pub fn fn_sig(self) -> Option
<&'hir FnSig
<'hir
>> {
3436 Node
::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. }
)
3437 | Node
::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. }
)
3438 | Node
::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }
) => Some(fn_sig
),
3443 pub fn body_id(&self) -> Option
<BodyId
> {
3445 Node
::TraitItem(TraitItem
{
3446 kind
: TraitItemKind
::Fn(_
, TraitFn
::Provided(body_id
)),
3449 | Node
::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. }
)
3450 | Node
::Item(Item { kind: ItemKind::Fn(.., body_id), .. }
) => Some(*body_id
),
3455 pub fn generics(self) -> Option
<&'hir Generics
<'hir
>> {
3457 Node
::ForeignItem(ForeignItem
{
3458 kind
: ForeignItemKind
::Fn(_
, _
, generics
), ..
3460 | Node
::TraitItem(TraitItem { generics, .. }
)
3461 | Node
::ImplItem(ImplItem { generics, .. }
) => Some(generics
),
3462 Node
::Item(item
) => item
.kind
.generics(),
3467 pub fn as_owner(self) -> Option
<OwnerNode
<'hir
>> {
3469 Node
::Item(i
) => Some(OwnerNode
::Item(i
)),
3470 Node
::ForeignItem(i
) => Some(OwnerNode
::ForeignItem(i
)),
3471 Node
::TraitItem(i
) => Some(OwnerNode
::TraitItem(i
)),
3472 Node
::ImplItem(i
) => Some(OwnerNode
::ImplItem(i
)),
3473 Node
::Crate(i
) => Some(OwnerNode
::Crate(i
)),
3478 pub fn fn_kind(self) -> Option
<FnKind
<'hir
>> {
3480 Node
::Item(i
) => match i
.kind
{
3481 ItemKind
::Fn(ref sig
, ref generics
, _
) => {
3482 Some(FnKind
::ItemFn(i
.ident
, generics
, sig
.header
))
3486 Node
::TraitItem(ti
) => match ti
.kind
{
3487 TraitItemKind
::Fn(ref sig
, TraitFn
::Provided(_
)) => {
3488 Some(FnKind
::Method(ti
.ident
, sig
))
3492 Node
::ImplItem(ii
) => match ii
.kind
{
3493 ImplItemKind
::Fn(ref sig
, _
) => Some(FnKind
::Method(ii
.ident
, sig
)),
3496 Node
::Expr(e
) => match e
.kind
{
3497 ExprKind
::Closure { .. }
=> Some(FnKind
::Closure
),
3504 /// Get the fields for the tuple-constructor,
3505 /// if this node is a tuple constructor, otherwise None
3506 pub fn tuple_fields(&self) -> Option
<&'hir
[FieldDef
<'hir
>]> {
3507 if let Node
::Ctor(&VariantData
::Tuple(fields
, _
)) = self { Some(fields) }
else { None }
3511 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3512 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
3515 // These are in alphabetical order, which is easy to maintain.
3516 static_assert_size
!(Block
<'_
>, 48);
3517 static_assert_size
!(Body
<'_
>, 32);
3518 static_assert_size
!(Expr
<'_
>, 64);
3519 static_assert_size
!(ExprKind
<'_
>, 48);
3520 static_assert_size
!(FnDecl
<'_
>, 40);
3521 static_assert_size
!(ForeignItem
<'_
>, 72);
3522 static_assert_size
!(ForeignItemKind
<'_
>, 40);
3523 #[cfg(not(bootstrap))]
3524 static_assert_size
!(GenericArg
<'_
>, 24);
3525 static_assert_size
!(GenericBound
<'_
>, 48);
3526 static_assert_size
!(Generics
<'_
>, 56);
3527 static_assert_size
!(Impl
<'_
>, 80);
3528 #[cfg(not(bootstrap))]
3529 static_assert_size
!(ImplItem
<'_
>, 80);
3530 #[cfg(not(bootstrap))]
3531 static_assert_size
!(ImplItemKind
<'_
>, 32);
3532 static_assert_size
!(Item
<'_
>, 80);
3533 static_assert_size
!(ItemKind
<'_
>, 48);
3534 static_assert_size
!(Local
<'_
>, 64);
3535 static_assert_size
!(Param
<'_
>, 32);
3536 static_assert_size
!(Pat
<'_
>, 72);
3537 static_assert_size
!(PatKind
<'_
>, 48);
3538 static_assert_size
!(Path
<'_
>, 48);
3539 static_assert_size
!(PathSegment
<'_
>, 56);
3540 static_assert_size
!(QPath
<'_
>, 24);
3541 static_assert_size
!(Stmt
<'_
>, 32);
3542 static_assert_size
!(StmtKind
<'_
>, 16);
3543 #[cfg(not(bootstrap))]
3544 static_assert_size
!(TraitItem
<'_
>, 88);
3545 #[cfg(not(bootstrap))]
3546 static_assert_size
!(TraitItemKind
<'_
>, 48);
3547 static_assert_size
!(Ty
<'_
>, 48);
3548 static_assert_size
!(TyKind
<'_
>, 32);