1 use crate::def
::{DefKind, Namespace, Res}
;
2 use crate::def_id
::DefId
;
3 crate use crate::hir_id
::HirId
;
4 use crate::{itemlikevisit, LangItem}
;
6 use rustc_ast
::util
::parser
::ExprPrecedence
;
7 use rustc_ast
::{self as ast, CrateSugar, LlvmAsmDialect}
;
8 use rustc_ast
::{AttrVec, Attribute, FloatTy, IntTy, Label, LitKind, StrStyle, UintTy}
;
9 pub use rustc_ast
::{BorrowKind, ImplPolarity, IsAuto}
;
10 pub use rustc_ast
::{CaptureBy, Movability, Mutability}
;
11 use rustc_ast
::{InlineAsmOptions, InlineAsmTemplatePiece}
;
12 use rustc_data_structures
::sync
::{par_for_each_in, Send, Sync}
;
13 use rustc_macros
::HashStable_Generic
;
14 use rustc_span
::def_id
::LocalDefId
;
15 use rustc_span
::source_map
::Spanned
;
16 use rustc_span
::symbol
::{kw, sym, Ident, Symbol}
;
17 use rustc_span
::{MultiSpan, Span, DUMMY_SP}
;
18 use rustc_target
::asm
::InlineAsmRegOrRegClass
;
19 use rustc_target
::spec
::abi
::Abi
;
21 use smallvec
::SmallVec
;
22 use std
::collections
::{BTreeMap, BTreeSet}
;
25 #[derive(Copy, Clone, Encodable, HashStable_Generic)]
30 /// Either "`'a`", referring to a named lifetime definition,
31 /// or "``" (i.e., `kw::Invalid`), for elision placeholders.
33 /// HIR lowering inserts these placeholders in type paths that
34 /// refer to type definitions needing lifetime parameters,
35 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
36 pub name
: LifetimeName
,
39 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
40 #[derive(HashStable_Generic)]
42 /// Some user-given name like `T` or `'x`.
45 /// Synthetic name generated when user elided a lifetime in an impl header.
47 /// E.g., the lifetimes in cases like these:
50 /// impl Foo<'_> for u32
52 /// in that case, we rewrite to
54 /// impl<'f> Foo for &'f u32
55 /// impl<'f> Foo<'f> for u32
57 /// where `'f` is something like `Fresh(0)`. The indices are
58 /// unique per impl, but not necessarily continuous.
61 /// Indicates an illegal name was given and an error has been
62 /// reported (so we should squelch other derived errors). Occurs
63 /// when, e.g., `'_` is used in the wrong place.
68 pub fn ident(&self) -> Ident
{
70 ParamName
::Plain(ident
) => ident
,
71 ParamName
::Fresh(_
) | ParamName
::Error
=> {
72 Ident
::with_dummy_span(kw
::UnderscoreLifetime
)
77 pub fn normalize_to_macros_2_0(&self) -> ParamName
{
79 ParamName
::Plain(ident
) => ParamName
::Plain(ident
.normalize_to_macros_2_0()),
80 param_name
=> param_name
,
85 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
86 #[derive(HashStable_Generic)]
87 pub enum LifetimeName
{
88 /// User-given names or fresh (synthetic) names.
91 /// User wrote nothing (e.g., the lifetime in `&u32`).
94 /// Implicit lifetime in a context like `dyn Foo`. This is
95 /// distinguished from implicit lifetimes elsewhere because the
96 /// lifetime that they default to must appear elsewhere within the
97 /// enclosing type. This means that, in an `impl Trait` context, we
98 /// don't have to create a parameter for them. That is, `impl
99 /// Trait<Item = &u32>` expands to an opaque type like `type
100 /// Foo<'a> = impl Trait<Item = &'a u32>`, but `impl Trait<item =
101 /// dyn Bar>` expands to `type Foo = impl Trait<Item = dyn Bar +
102 /// 'static>`. The latter uses `ImplicitObjectLifetimeDefault` so
103 /// that surrounding code knows not to create a lifetime
105 ImplicitObjectLifetimeDefault
,
107 /// Indicates an error during lowering (usually `'_` in wrong place)
108 /// that was already reported.
111 /// User wrote specifies `'_`.
114 /// User wrote `'static`.
119 pub fn ident(&self) -> Ident
{
121 LifetimeName
::ImplicitObjectLifetimeDefault
122 | LifetimeName
::Implicit
123 | LifetimeName
::Error
=> Ident
::invalid(),
124 LifetimeName
::Underscore
=> Ident
::with_dummy_span(kw
::UnderscoreLifetime
),
125 LifetimeName
::Static
=> Ident
::with_dummy_span(kw
::StaticLifetime
),
126 LifetimeName
::Param(param_name
) => param_name
.ident(),
130 pub fn is_elided(&self) -> bool
{
132 LifetimeName
::ImplicitObjectLifetimeDefault
133 | LifetimeName
::Implicit
134 | LifetimeName
::Underscore
=> true,
136 // It might seem surprising that `Fresh(_)` counts as
137 // *not* elided -- but this is because, as far as the code
138 // in the compiler is concerned -- `Fresh(_)` variants act
139 // equivalently to "some fresh name". They correspond to
140 // early-bound regions on an impl, in other words.
141 LifetimeName
::Error
| LifetimeName
::Param(_
) | LifetimeName
::Static
=> false,
145 fn is_static(&self) -> bool
{
146 self == &LifetimeName
::Static
149 pub fn normalize_to_macros_2_0(&self) -> LifetimeName
{
151 LifetimeName
::Param(param_name
) => {
152 LifetimeName
::Param(param_name
.normalize_to_macros_2_0())
154 lifetime_name
=> lifetime_name
,
159 impl fmt
::Display
for Lifetime
{
160 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
161 self.name
.ident().fmt(f
)
165 impl fmt
::Debug
for Lifetime
{
166 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
167 write
!(f
, "lifetime({}: {})", self.hir_id
, self.name
.ident())
172 pub fn is_elided(&self) -> bool
{
173 self.name
.is_elided()
176 pub fn is_static(&self) -> bool
{
177 self.name
.is_static()
181 /// A `Path` is essentially Rust's notion of a name; for instance,
182 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
183 /// along with a bunch of supporting information.
184 #[derive(Debug, HashStable_Generic)]
185 pub struct Path
<'hir
> {
187 /// The resolution for the path.
189 /// The segments in the path: the things separated by `::`.
190 pub segments
: &'hir
[PathSegment
<'hir
>],
194 pub fn is_global(&self) -> bool
{
195 !self.segments
.is_empty() && self.segments
[0].ident
.name
== kw
::PathRoot
199 /// A segment of a path: an identifier, an optional lifetime, and a set of
201 #[derive(Debug, HashStable_Generic)]
202 pub struct PathSegment
<'hir
> {
203 /// The identifier portion of this path segment.
204 #[stable_hasher(project(name))]
206 // `id` and `res` are optional. We currently only use these in save-analysis,
207 // any path segments without these will not have save-analysis info and
208 // therefore will not have 'jump to def' in IDEs, but otherwise will not be
209 // affected. (In general, we don't bother to get the defs for synthesized
210 // segments, only for segments which have come from the AST).
211 pub hir_id
: Option
<HirId
>,
212 pub res
: Option
<Res
>,
214 /// Type/lifetime parameters attached to this path. They come in
215 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
216 /// this is more than just simple syntactic sugar; the use of
217 /// parens affects the region binding rules, so we preserve the
219 pub args
: Option
<&'hir GenericArgs
<'hir
>>,
221 /// Whether to infer remaining type parameters, if any.
222 /// This only applies to expression and pattern paths, and
223 /// out of those only the segments with no type parameters
224 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
225 pub infer_args
: bool
,
228 impl<'hir
> PathSegment
<'hir
> {
229 /// Converts an identifier to the corresponding segment.
230 pub fn from_ident(ident
: Ident
) -> PathSegment
<'hir
> {
231 PathSegment { ident, hir_id: None, res: None, infer_args: true, args: None }
234 pub fn generic_args(&self) -> &GenericArgs
<'hir
> {
235 if let Some(ref args
) = self.args
{
238 const DUMMY
: &GenericArgs
<'_
> = &GenericArgs
::none();
244 #[derive(Encodable, Debug, HashStable_Generic)]
245 pub struct ConstArg
{
246 pub value
: AnonConst
,
250 #[derive(Debug, HashStable_Generic)]
251 pub enum GenericArg
<'hir
> {
257 impl GenericArg
<'_
> {
258 pub fn span(&self) -> Span
{
260 GenericArg
::Lifetime(l
) => l
.span
,
261 GenericArg
::Type(t
) => t
.span
,
262 GenericArg
::Const(c
) => c
.span
,
266 pub fn id(&self) -> HirId
{
268 GenericArg
::Lifetime(l
) => l
.hir_id
,
269 GenericArg
::Type(t
) => t
.hir_id
,
270 GenericArg
::Const(c
) => c
.value
.hir_id
,
274 pub fn is_const(&self) -> bool
{
275 matches
!(self, GenericArg
::Const(_
))
278 pub fn descr(&self) -> &'
static str {
280 GenericArg
::Lifetime(_
) => "lifetime",
281 GenericArg
::Type(_
) => "type",
282 GenericArg
::Const(_
) => "constant",
287 #[derive(Debug, HashStable_Generic)]
288 pub struct GenericArgs
<'hir
> {
289 /// The generic arguments for this path segment.
290 pub args
: &'hir
[GenericArg
<'hir
>],
291 /// Bindings (equality constraints) on associated types, if present.
292 /// E.g., `Foo<A = Bar>`.
293 pub bindings
: &'hir
[TypeBinding
<'hir
>],
294 /// Were arguments written in parenthesized form `Fn(T) -> U`?
295 /// This is required mostly for pretty-printing and diagnostics,
296 /// but also for changing lifetime elision rules to be "function-like".
297 pub parenthesized
: bool
,
300 impl GenericArgs
<'_
> {
301 pub const fn none() -> Self {
302 Self { args: &[], bindings: &[], parenthesized: false }
305 pub fn inputs(&self) -> &[Ty
<'_
>] {
306 if self.parenthesized
{
307 for arg
in self.args
{
309 GenericArg
::Lifetime(_
) => {}
310 GenericArg
::Type(ref ty
) => {
311 if let TyKind
::Tup(ref tys
) = ty
.kind
{
316 GenericArg
::Const(_
) => {}
320 panic
!("GenericArgs::inputs: not a `Fn(T) -> U`");
323 pub fn own_counts(&self) -> GenericParamCount
{
324 // We could cache this as a property of `GenericParamCount`, but
325 // the aim is to refactor this away entirely eventually and the
326 // presence of this method will be a constant reminder.
327 let mut own_counts
: GenericParamCount
= Default
::default();
329 for arg
in self.args
{
331 GenericArg
::Lifetime(_
) => own_counts
.lifetimes
+= 1,
332 GenericArg
::Type(_
) => own_counts
.types
+= 1,
333 GenericArg
::Const(_
) => own_counts
.consts
+= 1,
341 /// A modifier on a bound, currently this is only used for `?Sized`, where the
342 /// modifier is `Maybe`. Negative bounds should also be handled here.
343 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
344 #[derive(HashStable_Generic)]
345 pub enum TraitBoundModifier
{
351 /// The AST represents all type param bounds as types.
352 /// `typeck::collect::compute_bounds` matches these against
353 /// the "special" built-in traits (see `middle::lang_items`) and
354 /// detects `Copy`, `Send` and `Sync`.
355 #[derive(Debug, HashStable_Generic)]
356 pub enum GenericBound
<'hir
> {
357 Trait(PolyTraitRef
<'hir
>, TraitBoundModifier
),
358 // FIXME(davidtwco): Introduce `PolyTraitRef::LangItem`
359 LangItemTrait(LangItem
, Span
, HirId
, &'hir GenericArgs
<'hir
>),
363 impl GenericBound
<'_
> {
364 pub fn trait_ref(&self) -> Option
<&TraitRef
<'_
>> {
366 GenericBound
::Trait(data
, _
) => Some(&data
.trait_ref
),
371 pub fn span(&self) -> Span
{
373 &GenericBound
::Trait(ref t
, ..) => t
.span
,
374 &GenericBound
::LangItemTrait(_
, span
, ..) => span
,
375 &GenericBound
::Outlives(ref l
) => l
.span
,
380 pub type GenericBounds
<'hir
> = &'hir
[GenericBound
<'hir
>];
382 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
383 pub enum LifetimeParamKind
{
384 // Indicates that the lifetime definition was explicitly declared (e.g., in
385 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
388 // Indicates that the lifetime definition was synthetically added
389 // as a result of an in-band lifetime usage (e.g., in
390 // `fn foo(x: &'a u8) -> &'a u8 { x }`).
393 // Indication that the lifetime was elided (e.g., in both cases in
394 // `fn foo(x: &u8) -> &'_ u8 { x }`).
397 // Indication that the lifetime name was somehow in error.
401 #[derive(Debug, HashStable_Generic)]
402 pub enum GenericParamKind
<'hir
> {
403 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
405 kind
: LifetimeParamKind
,
408 default: Option
<&'hir Ty
<'hir
>>,
409 synthetic
: Option
<SyntheticTyParamKind
>,
416 #[derive(Debug, HashStable_Generic)]
417 pub struct GenericParam
<'hir
> {
420 pub attrs
: &'hir
[Attribute
],
421 pub bounds
: GenericBounds
<'hir
>,
423 pub pure_wrt_drop
: bool
,
424 pub kind
: GenericParamKind
<'hir
>,
427 impl GenericParam
<'hir
> {
428 pub fn bounds_span(&self) -> Option
<Span
> {
429 self.bounds
.iter().fold(None
, |span
, bound
| {
430 let span
= span
.map(|s
| s
.to(bound
.span())).unwrap_or_else(|| bound
.span());
438 pub struct GenericParamCount
{
439 pub lifetimes
: usize,
444 /// Represents lifetimes and type parameters attached to a declaration
445 /// of a function, enum, trait, etc.
446 #[derive(Debug, HashStable_Generic)]
447 pub struct Generics
<'hir
> {
448 pub params
: &'hir
[GenericParam
<'hir
>],
449 pub where_clause
: WhereClause
<'hir
>,
453 impl Generics
<'hir
> {
454 pub const fn empty() -> Generics
<'hir
> {
457 where_clause
: WhereClause { predicates: &[], span: DUMMY_SP }
,
462 pub fn get_named(&self, name
: Symbol
) -> Option
<&GenericParam
<'_
>> {
463 for param
in self.params
{
464 if name
== param
.name
.ident().name
{
471 pub fn spans(&self) -> MultiSpan
{
472 if self.params
.is_empty() {
475 self.params
.iter().map(|p
| p
.span
).collect
::<Vec
<Span
>>().into()
480 /// Synthetic type parameters are converted to another form during lowering; this allows
481 /// us to track the original form they had, and is useful for error messages.
482 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
483 #[derive(HashStable_Generic)]
484 pub enum SyntheticTyParamKind
{
486 // Created by the `#[rustc_synthetic]` attribute.
490 /// A where-clause in a definition.
491 #[derive(Debug, HashStable_Generic)]
492 pub struct WhereClause
<'hir
> {
493 pub predicates
: &'hir
[WherePredicate
<'hir
>],
494 // Only valid if predicates aren't empty.
498 impl WhereClause
<'_
> {
499 pub fn span(&self) -> Option
<Span
> {
500 if self.predicates
.is_empty() { None }
else { Some(self.span) }
503 /// The `WhereClause` under normal circumstances points at either the predicates or the empty
504 /// space where the `where` clause should be. Only of use for diagnostic suggestions.
505 pub fn span_for_predicates_or_empty_place(&self) -> Span
{
509 /// `Span` where further predicates would be suggested, accounting for trailing commas, like
510 /// in `fn foo<T>(t: T) where T: Foo,` so we don't suggest two trailing commas.
511 pub fn tail_span_for_suggestion(&self) -> Span
{
512 let end
= self.span_for_predicates_or_empty_place().shrink_to_hi();
513 self.predicates
.last().map(|p
| p
.span()).unwrap_or(end
).shrink_to_hi().to(end
)
517 /// A single predicate in a where-clause.
518 #[derive(Debug, HashStable_Generic)]
519 pub enum WherePredicate
<'hir
> {
520 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
521 BoundPredicate(WhereBoundPredicate
<'hir
>),
522 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
523 RegionPredicate(WhereRegionPredicate
<'hir
>),
524 /// An equality predicate (unsupported).
525 EqPredicate(WhereEqPredicate
<'hir
>),
528 impl WherePredicate
<'_
> {
529 pub fn span(&self) -> Span
{
531 &WherePredicate
::BoundPredicate(ref p
) => p
.span
,
532 &WherePredicate
::RegionPredicate(ref p
) => p
.span
,
533 &WherePredicate
::EqPredicate(ref p
) => p
.span
,
538 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
539 #[derive(Debug, HashStable_Generic)]
540 pub struct WhereBoundPredicate
<'hir
> {
542 /// Any generics from a `for` binding.
543 pub bound_generic_params
: &'hir
[GenericParam
<'hir
>],
544 /// The type being bounded.
545 pub bounded_ty
: &'hir Ty
<'hir
>,
546 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
547 pub bounds
: GenericBounds
<'hir
>,
550 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
551 #[derive(Debug, HashStable_Generic)]
552 pub struct WhereRegionPredicate
<'hir
> {
554 pub lifetime
: Lifetime
,
555 pub bounds
: GenericBounds
<'hir
>,
558 /// An equality predicate (e.g., `T = int`); currently unsupported.
559 #[derive(Debug, HashStable_Generic)]
560 pub struct WhereEqPredicate
<'hir
> {
563 pub lhs_ty
: &'hir Ty
<'hir
>,
564 pub rhs_ty
: &'hir Ty
<'hir
>,
567 #[derive(Encodable, Debug, HashStable_Generic)]
568 pub struct ModuleItems
{
569 // Use BTreeSets here so items are in the same order as in the
570 // list of all items in Crate
571 pub items
: BTreeSet
<HirId
>,
572 pub trait_items
: BTreeSet
<TraitItemId
>,
573 pub impl_items
: BTreeSet
<ImplItemId
>,
576 /// A type representing only the top-level module.
577 #[derive(Encodable, Debug, HashStable_Generic)]
578 pub struct CrateItem
<'hir
> {
579 pub module
: Mod
<'hir
>,
580 pub attrs
: &'hir
[Attribute
],
584 /// The top-level data structure that stores the entire contents of
585 /// the crate currently being compiled.
587 /// For more details, see the [rustc dev guide].
589 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
591 pub struct Crate
<'hir
> {
592 pub item
: CrateItem
<'hir
>,
593 pub exported_macros
: &'hir
[MacroDef
<'hir
>],
594 // Attributes from non-exported macros, kept only for collecting the library feature list.
595 pub non_exported_macro_attrs
: &'hir
[Attribute
],
597 // N.B., we use a `BTreeMap` here so that `visit_all_items` iterates
598 // over the ids in increasing order. In principle it should not
599 // matter what order we visit things in, but in *practice* it
600 // does, because it can affect the order in which errors are
601 // detected, which in turn can make compile-fail tests yield
602 // slightly different results.
603 pub items
: BTreeMap
<HirId
, Item
<'hir
>>,
605 pub trait_items
: BTreeMap
<TraitItemId
, TraitItem
<'hir
>>,
606 pub impl_items
: BTreeMap
<ImplItemId
, ImplItem
<'hir
>>,
607 pub bodies
: BTreeMap
<BodyId
, Body
<'hir
>>,
608 pub trait_impls
: BTreeMap
<DefId
, Vec
<HirId
>>,
610 /// A list of the body ids written out in the order in which they
611 /// appear in the crate. If you're going to process all the bodies
612 /// in the crate, you should iterate over this list rather than the keys
614 pub body_ids
: Vec
<BodyId
>,
616 /// A list of modules written out in the order in which they
617 /// appear in the crate. This includes the main crate module.
618 pub modules
: BTreeMap
<HirId
, ModuleItems
>,
619 /// A list of proc macro HirIds, written out in the order in which
620 /// they are declared in the static array generated by proc_macro_harness.
621 pub proc_macros
: Vec
<HirId
>,
623 pub trait_map
: BTreeMap
<HirId
, Vec
<TraitCandidate
>>,
627 pub fn item(&self, id
: HirId
) -> &Item
<'hir
> {
631 pub fn trait_item(&self, id
: TraitItemId
) -> &TraitItem
<'hir
> {
632 &self.trait_items
[&id
]
635 pub fn impl_item(&self, id
: ImplItemId
) -> &ImplItem
<'hir
> {
636 &self.impl_items
[&id
]
639 pub fn body(&self, id
: BodyId
) -> &Body
<'hir
> {
645 /// Visits all items in the crate in some deterministic (but
646 /// unspecified) order. If you just need to process every item,
647 /// but don't care about nesting, this method is the best choice.
649 /// If you do care about nesting -- usually because your algorithm
650 /// follows lexical scoping rules -- then you want a different
651 /// approach. You should override `visit_nested_item` in your
652 /// visitor and then call `intravisit::walk_crate` instead.
653 pub fn visit_all_item_likes
<'hir
, V
>(&'hir
self, visitor
: &mut V
)
655 V
: itemlikevisit
::ItemLikeVisitor
<'hir
>,
657 for item
in self.items
.values() {
658 visitor
.visit_item(item
);
661 for trait_item
in self.trait_items
.values() {
662 visitor
.visit_trait_item(trait_item
);
665 for impl_item
in self.impl_items
.values() {
666 visitor
.visit_impl_item(impl_item
);
670 /// A parallel version of `visit_all_item_likes`.
671 pub fn par_visit_all_item_likes
<'hir
, V
>(&'hir
self, visitor
: &V
)
673 V
: itemlikevisit
::ParItemLikeVisitor
<'hir
> + Sync
+ Send
,
677 par_for_each_in(&self.items
, |(_
, item
)| {
678 visitor
.visit_item(item
);
682 par_for_each_in(&self.trait_items
, |(_
, trait_item
)| {
683 visitor
.visit_trait_item(trait_item
);
687 par_for_each_in(&self.impl_items
, |(_
, impl_item
)| {
688 visitor
.visit_impl_item(impl_item
);
695 /// A macro definition, in this crate or imported from another.
697 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
698 #[derive(Debug, HashStable_Generic)]
699 pub struct MacroDef
<'hir
> {
701 pub vis
: Visibility
<'hir
>,
702 pub attrs
: &'hir
[Attribute
],
705 pub ast
: ast
::MacroDef
,
708 /// A block of statements `{ .. }`, which may have a label (in this case the
709 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
710 /// the `rules` being anything but `DefaultBlock`.
711 #[derive(Debug, HashStable_Generic)]
712 pub struct Block
<'hir
> {
713 /// Statements in a block.
714 pub stmts
: &'hir
[Stmt
<'hir
>],
715 /// An expression at the end of the block
716 /// without a semicolon, if any.
717 pub expr
: Option
<&'hir Expr
<'hir
>>,
718 #[stable_hasher(ignore)]
720 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
721 pub rules
: BlockCheckMode
,
723 /// If true, then there may exist `break 'a` values that aim to
724 /// break out of this block early.
725 /// Used by `'label: {}` blocks and by `try {}` blocks.
726 pub targeted_by_break
: bool
,
729 #[derive(Debug, HashStable_Generic)]
730 pub struct Pat
<'hir
> {
731 #[stable_hasher(ignore)]
733 pub kind
: PatKind
<'hir
>,
735 // Whether to use default binding modes.
736 // At present, this is false only for destructuring assignment.
737 pub default_binding_modes
: bool
,
741 // FIXME(#19596) this is a workaround, but there should be a better way
742 fn walk_short_(&self, it
: &mut impl FnMut(&Pat
<'_
>) -> bool
) -> bool
{
749 Wild
| Lit(_
) | Range(..) | Binding(.., None
) | Path(_
) => true,
750 Box(s
) | Ref(s
, _
) | Binding(.., Some(s
)) => s
.walk_short_(it
),
751 Struct(_
, fields
, _
) => fields
.iter().all(|field
| field
.pat
.walk_short_(it
)),
752 TupleStruct(_
, s
, _
) | Tuple(s
, _
) | Or(s
) => s
.iter().all(|p
| p
.walk_short_(it
)),
753 Slice(before
, slice
, after
) => {
754 before
.iter().chain(slice
.iter()).chain(after
.iter()).all(|p
| p
.walk_short_(it
))
759 /// Walk the pattern in left-to-right order,
760 /// short circuiting (with `.all(..)`) if `false` is returned.
762 /// Note that when visiting e.g. `Tuple(ps)`,
763 /// if visiting `ps[0]` returns `false`,
764 /// then `ps[1]` will not be visited.
765 pub fn walk_short(&self, mut it
: impl FnMut(&Pat
<'_
>) -> bool
) -> bool
{
766 self.walk_short_(&mut it
)
769 // FIXME(#19596) this is a workaround, but there should be a better way
770 fn walk_(&self, it
: &mut impl FnMut(&Pat
<'_
>) -> bool
) {
777 Wild
| Lit(_
) | Range(..) | Binding(.., None
) | Path(_
) => {}
778 Box(s
) | Ref(s
, _
) | Binding(.., Some(s
)) => s
.walk_(it
),
779 Struct(_
, fields
, _
) => fields
.iter().for_each(|field
| field
.pat
.walk_(it
)),
780 TupleStruct(_
, s
, _
) | Tuple(s
, _
) | Or(s
) => s
.iter().for_each(|p
| p
.walk_(it
)),
781 Slice(before
, slice
, after
) => {
782 before
.iter().chain(slice
.iter()).chain(after
.iter()).for_each(|p
| p
.walk_(it
))
787 /// Walk the pattern in left-to-right order.
789 /// If `it(pat)` returns `false`, the children are not visited.
790 pub fn walk(&self, mut it
: impl FnMut(&Pat
<'_
>) -> bool
) {
794 /// Walk the pattern in left-to-right order.
796 /// If you always want to recurse, prefer this method over `walk`.
797 pub fn walk_always(&self, mut it
: impl FnMut(&Pat
<'_
>)) {
805 /// A single field in a struct pattern.
807 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
808 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
809 /// except `is_shorthand` is true.
810 #[derive(Debug, HashStable_Generic)]
811 pub struct FieldPat
<'hir
> {
812 #[stable_hasher(ignore)]
814 /// The identifier for the field.
815 #[stable_hasher(project(name))]
817 /// The pattern the field is destructured to.
818 pub pat
: &'hir Pat
<'hir
>,
819 pub is_shorthand
: bool
,
823 /// Explicit binding annotations given in the HIR for a binding. Note
824 /// that this is not the final binding *mode* that we infer after type
826 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
827 pub enum BindingAnnotation
{
828 /// No binding annotation given: this means that the final binding mode
829 /// will depend on whether we have skipped through a `&` reference
830 /// when matching. For example, the `x` in `Some(x)` will have binding
831 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
832 /// ultimately be inferred to be by-reference.
834 /// Note that implicit reference skipping is not implemented yet (#42640).
837 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
840 /// Annotated as `ref`, like `ref x`
843 /// Annotated as `ref mut x`.
847 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
853 impl fmt
::Display
for RangeEnd
{
854 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
855 f
.write_str(match self {
856 RangeEnd
::Included
=> "..=",
857 RangeEnd
::Excluded
=> "..",
862 #[derive(Debug, HashStable_Generic)]
863 pub enum PatKind
<'hir
> {
864 /// Represents a wildcard pattern (i.e., `_`).
867 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
868 /// The `HirId` is the canonical ID for the variable being bound,
869 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
870 /// which is the pattern ID of the first `x`.
871 Binding(BindingAnnotation
, HirId
, Ident
, Option
<&'hir Pat
<'hir
>>),
873 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
874 /// The `bool` is `true` in the presence of a `..`.
875 Struct(QPath
<'hir
>, &'hir
[FieldPat
<'hir
>], bool
),
877 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
878 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
879 /// `0 <= position <= subpats.len()`
880 TupleStruct(QPath
<'hir
>, &'hir
[&'hir Pat
<'hir
>], Option
<usize>),
882 /// An or-pattern `A | B | C`.
883 /// Invariant: `pats.len() >= 2`.
884 Or(&'hir
[&'hir Pat
<'hir
>]),
886 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
889 /// A tuple pattern (e.g., `(a, b)`).
890 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
891 /// `0 <= position <= subpats.len()`
892 Tuple(&'hir
[&'hir Pat
<'hir
>], Option
<usize>),
895 Box(&'hir Pat
<'hir
>),
897 /// A reference pattern (e.g., `&mut (a, b)`).
898 Ref(&'hir Pat
<'hir
>, Mutability
),
901 Lit(&'hir Expr
<'hir
>),
903 /// A range pattern (e.g., `1..=2` or `1..2`).
904 Range(Option
<&'hir Expr
<'hir
>>, Option
<&'hir Expr
<'hir
>>, RangeEnd
),
906 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
908 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
909 /// If `slice` exists, then `after` can be non-empty.
911 /// The representation for e.g., `[a, b, .., c, d]` is:
913 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
915 Slice(&'hir
[&'hir Pat
<'hir
>], Option
<&'hir Pat
<'hir
>>, &'hir
[&'hir Pat
<'hir
>]),
918 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
920 /// The `+` operator (addition).
922 /// The `-` operator (subtraction).
924 /// The `*` operator (multiplication).
926 /// The `/` operator (division).
928 /// The `%` operator (modulus).
930 /// The `&&` operator (logical and).
932 /// The `||` operator (logical or).
934 /// The `^` operator (bitwise xor).
936 /// The `&` operator (bitwise and).
938 /// The `|` operator (bitwise or).
940 /// The `<<` operator (shift left).
942 /// The `>>` operator (shift right).
944 /// The `==` operator (equality).
946 /// The `<` operator (less than).
948 /// The `<=` operator (less than or equal to).
950 /// The `!=` operator (not equal to).
952 /// The `>=` operator (greater than or equal to).
954 /// The `>` operator (greater than).
959 pub fn as_str(self) -> &'
static str {
961 BinOpKind
::Add
=> "+",
962 BinOpKind
::Sub
=> "-",
963 BinOpKind
::Mul
=> "*",
964 BinOpKind
::Div
=> "/",
965 BinOpKind
::Rem
=> "%",
966 BinOpKind
::And
=> "&&",
967 BinOpKind
::Or
=> "||",
968 BinOpKind
::BitXor
=> "^",
969 BinOpKind
::BitAnd
=> "&",
970 BinOpKind
::BitOr
=> "|",
971 BinOpKind
::Shl
=> "<<",
972 BinOpKind
::Shr
=> ">>",
973 BinOpKind
::Eq
=> "==",
974 BinOpKind
::Lt
=> "<",
975 BinOpKind
::Le
=> "<=",
976 BinOpKind
::Ne
=> "!=",
977 BinOpKind
::Ge
=> ">=",
978 BinOpKind
::Gt
=> ">",
982 pub fn is_lazy(self) -> bool
{
983 matches
!(self, BinOpKind
::And
| BinOpKind
::Or
)
986 pub fn is_shift(self) -> bool
{
987 matches
!(self, BinOpKind
::Shl
| BinOpKind
::Shr
)
990 pub fn is_comparison(self) -> bool
{
997 | BinOpKind
::Ge
=> true,
1009 | BinOpKind
::Shr
=> false,
1013 /// Returns `true` if the binary operator takes its arguments by value.
1014 pub fn is_by_value(self) -> bool
{
1015 !self.is_comparison()
1019 impl Into
<ast
::BinOpKind
> for BinOpKind
{
1020 fn into(self) -> ast
::BinOpKind
{
1022 BinOpKind
::Add
=> ast
::BinOpKind
::Add
,
1023 BinOpKind
::Sub
=> ast
::BinOpKind
::Sub
,
1024 BinOpKind
::Mul
=> ast
::BinOpKind
::Mul
,
1025 BinOpKind
::Div
=> ast
::BinOpKind
::Div
,
1026 BinOpKind
::Rem
=> ast
::BinOpKind
::Rem
,
1027 BinOpKind
::And
=> ast
::BinOpKind
::And
,
1028 BinOpKind
::Or
=> ast
::BinOpKind
::Or
,
1029 BinOpKind
::BitXor
=> ast
::BinOpKind
::BitXor
,
1030 BinOpKind
::BitAnd
=> ast
::BinOpKind
::BitAnd
,
1031 BinOpKind
::BitOr
=> ast
::BinOpKind
::BitOr
,
1032 BinOpKind
::Shl
=> ast
::BinOpKind
::Shl
,
1033 BinOpKind
::Shr
=> ast
::BinOpKind
::Shr
,
1034 BinOpKind
::Eq
=> ast
::BinOpKind
::Eq
,
1035 BinOpKind
::Lt
=> ast
::BinOpKind
::Lt
,
1036 BinOpKind
::Le
=> ast
::BinOpKind
::Le
,
1037 BinOpKind
::Ne
=> ast
::BinOpKind
::Ne
,
1038 BinOpKind
::Ge
=> ast
::BinOpKind
::Ge
,
1039 BinOpKind
::Gt
=> ast
::BinOpKind
::Gt
,
1044 pub type BinOp
= Spanned
<BinOpKind
>;
1046 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1048 /// The `*` operator (deferencing).
1050 /// The `!` operator (logical negation).
1052 /// The `-` operator (negation).
1057 pub fn as_str(self) -> &'
static str {
1059 Self::UnDeref
=> "*",
1065 /// Returns `true` if the unary operator takes its argument by value.
1066 pub fn is_by_value(self) -> bool
{
1067 matches
!(self, Self::UnNeg
| Self::UnNot
)
1072 #[derive(Debug, HashStable_Generic)]
1073 pub struct Stmt
<'hir
> {
1075 pub kind
: StmtKind
<'hir
>,
1079 /// The contents of a statement.
1080 #[derive(Debug, HashStable_Generic)]
1081 pub enum StmtKind
<'hir
> {
1082 /// A local (`let`) binding.
1083 Local(&'hir Local
<'hir
>),
1085 /// An item binding.
1088 /// An expression without a trailing semi-colon (must have unit type).
1089 Expr(&'hir Expr
<'hir
>),
1091 /// An expression with a trailing semi-colon (may have any type).
1092 Semi(&'hir Expr
<'hir
>),
1095 impl<'hir
> StmtKind
<'hir
> {
1096 pub fn attrs(&self, get_item
: impl FnOnce(ItemId
) -> &'hir Item
<'hir
>) -> &'hir
[Attribute
] {
1098 StmtKind
::Local(ref l
) => &l
.attrs
,
1099 StmtKind
::Item(ref item_id
) => &get_item(*item_id
).attrs
,
1100 StmtKind
::Expr(ref e
) | StmtKind
::Semi(ref e
) => &e
.attrs
,
1105 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1106 #[derive(Debug, HashStable_Generic)]
1107 pub struct Local
<'hir
> {
1108 pub pat
: &'hir Pat
<'hir
>,
1109 /// Type annotation, if any (otherwise the type will be inferred).
1110 pub ty
: Option
<&'hir Ty
<'hir
>>,
1111 /// Initializer expression to set the value, if any.
1112 pub init
: Option
<&'hir Expr
<'hir
>>,
1116 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1117 /// desugaring. Otherwise will be `Normal`.
1118 pub source
: LocalSource
,
1121 /// Represents a single arm of a `match` expression, e.g.
1122 /// `<pat> (if <guard>) => <body>`.
1123 #[derive(Debug, HashStable_Generic)]
1124 pub struct Arm
<'hir
> {
1125 #[stable_hasher(ignore)]
1128 pub attrs
: &'hir
[Attribute
],
1129 /// If this pattern and the optional guard matches, then `body` is evaluated.
1130 pub pat
: &'hir Pat
<'hir
>,
1131 /// Optional guard clause.
1132 pub guard
: Option
<Guard
<'hir
>>,
1133 /// The expression the arm evaluates to if this arm matches.
1134 pub body
: &'hir Expr
<'hir
>,
1137 #[derive(Debug, HashStable_Generic)]
1138 pub enum Guard
<'hir
> {
1139 If(&'hir Expr
<'hir
>),
1142 #[derive(Debug, HashStable_Generic)]
1143 pub struct Field
<'hir
> {
1144 #[stable_hasher(ignore)]
1147 pub expr
: &'hir Expr
<'hir
>,
1149 pub is_shorthand
: bool
,
1152 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1153 pub enum BlockCheckMode
{
1155 UnsafeBlock(UnsafeSource
),
1156 PushUnsafeBlock(UnsafeSource
),
1157 PopUnsafeBlock(UnsafeSource
),
1160 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1161 pub enum UnsafeSource
{
1166 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Hash, Debug)]
1171 /// The body of a function, closure, or constant value. In the case of
1172 /// a function, the body contains not only the function body itself
1173 /// (which is an expression), but also the argument patterns, since
1174 /// those are something that the caller doesn't really care about.
1179 /// fn foo((x, y): (u32, u32)) -> u32 {
1184 /// Here, the `Body` associated with `foo()` would contain:
1186 /// - an `params` array containing the `(x, y)` pattern
1187 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1188 /// - `generator_kind` would be `None`
1190 /// All bodies have an **owner**, which can be accessed via the HIR
1191 /// map using `body_owner_def_id()`.
1193 pub struct Body
<'hir
> {
1194 pub params
: &'hir
[Param
<'hir
>],
1195 pub value
: Expr
<'hir
>,
1196 pub generator_kind
: Option
<GeneratorKind
>,
1200 pub fn id(&self) -> BodyId
{
1201 BodyId { hir_id: self.value.hir_id }
1204 pub fn generator_kind(&self) -> Option
<GeneratorKind
> {
1209 /// The type of source expression that caused this generator to be created.
1210 #[derive(Clone, PartialEq, Eq, HashStable_Generic, Encodable, Decodable, Debug, Copy)]
1211 pub enum GeneratorKind
{
1212 /// An explicit `async` block or the body of an async function.
1213 Async(AsyncGeneratorKind
),
1215 /// A generator literal created via a `yield` inside a closure.
1219 impl fmt
::Display
for GeneratorKind
{
1220 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1222 GeneratorKind
::Async(k
) => fmt
::Display
::fmt(k
, f
),
1223 GeneratorKind
::Gen
=> f
.write_str("generator"),
1228 /// In the case of a generator created as part of an async construct,
1229 /// which kind of async construct caused it to be created?
1231 /// This helps error messages but is also used to drive coercions in
1232 /// type-checking (see #60424).
1233 #[derive(Clone, PartialEq, Eq, HashStable_Generic, Encodable, Decodable, Debug, Copy)]
1234 pub enum AsyncGeneratorKind
{
1235 /// An explicit `async` block written by the user.
1238 /// An explicit `async` block written by the user.
1241 /// The `async` block generated as the body of an async function.
1245 impl fmt
::Display
for AsyncGeneratorKind
{
1246 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1247 f
.write_str(match self {
1248 AsyncGeneratorKind
::Block
=> "`async` block",
1249 AsyncGeneratorKind
::Closure
=> "`async` closure body",
1250 AsyncGeneratorKind
::Fn
=> "`async fn` body",
1255 #[derive(Copy, Clone, Debug)]
1256 pub enum BodyOwnerKind
{
1257 /// Functions and methods.
1263 /// Constants and associated constants.
1266 /// Initializer of a `static` item.
1270 impl BodyOwnerKind
{
1271 pub fn is_fn_or_closure(self) -> bool
{
1273 BodyOwnerKind
::Fn
| BodyOwnerKind
::Closure
=> true,
1274 BodyOwnerKind
::Const
| BodyOwnerKind
::Static(_
) => false,
1279 /// The kind of an item that requires const-checking.
1280 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1281 pub enum ConstContext
{
1285 /// A `static` or `static mut`.
1288 /// A `const`, associated `const`, or other const context.
1290 /// Other contexts include:
1291 /// - Array length expressions
1292 /// - Enum discriminants
1293 /// - Const generics
1295 /// For the most part, other contexts are treated just like a regular `const`, so they are
1296 /// lumped into the same category.
1301 /// A description of this const context that can appear between backticks in an error message.
1303 /// E.g. `const` or `static mut`.
1304 pub fn keyword_name(self) -> &'
static str {
1306 Self::Const
=> "const",
1307 Self::Static(Mutability
::Not
) => "static",
1308 Self::Static(Mutability
::Mut
) => "static mut",
1309 Self::ConstFn
=> "const fn",
1314 /// A colloquial, trivially pluralizable description of this const context for use in error
1316 impl fmt
::Display
for ConstContext
{
1317 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1319 Self::Const
=> write
!(f
, "constant"),
1320 Self::Static(_
) => write
!(f
, "static"),
1321 Self::ConstFn
=> write
!(f
, "constant function"),
1327 pub type Lit
= Spanned
<LitKind
>;
1329 /// A constant (expression) that's not an item or associated item,
1330 /// but needs its own `DefId` for type-checking, const-eval, etc.
1331 /// These are usually found nested inside types (e.g., array lengths)
1332 /// or expressions (e.g., repeat counts), and also used to define
1333 /// explicit discriminant values for enum variants.
1334 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1335 pub struct AnonConst
{
1342 pub struct Expr
<'hir
> {
1344 pub kind
: ExprKind
<'hir
>,
1349 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1350 #[cfg(target_arch = "x86_64")]
1351 rustc_data_structures
::static_assert_size
!(Expr
<'
static>, 72);
1354 pub fn precedence(&self) -> ExprPrecedence
{
1356 ExprKind
::Box(_
) => ExprPrecedence
::Box
,
1357 ExprKind
::ConstBlock(_
) => ExprPrecedence
::ConstBlock
,
1358 ExprKind
::Array(_
) => ExprPrecedence
::Array
,
1359 ExprKind
::Call(..) => ExprPrecedence
::Call
,
1360 ExprKind
::MethodCall(..) => ExprPrecedence
::MethodCall
,
1361 ExprKind
::Tup(_
) => ExprPrecedence
::Tup
,
1362 ExprKind
::Binary(op
, ..) => ExprPrecedence
::Binary(op
.node
.into()),
1363 ExprKind
::Unary(..) => ExprPrecedence
::Unary
,
1364 ExprKind
::Lit(_
) => ExprPrecedence
::Lit
,
1365 ExprKind
::Type(..) | ExprKind
::Cast(..) => ExprPrecedence
::Cast
,
1366 ExprKind
::DropTemps(ref expr
, ..) => expr
.precedence(),
1367 ExprKind
::Loop(..) => ExprPrecedence
::Loop
,
1368 ExprKind
::Match(..) => ExprPrecedence
::Match
,
1369 ExprKind
::Closure(..) => ExprPrecedence
::Closure
,
1370 ExprKind
::Block(..) => ExprPrecedence
::Block
,
1371 ExprKind
::Assign(..) => ExprPrecedence
::Assign
,
1372 ExprKind
::AssignOp(..) => ExprPrecedence
::AssignOp
,
1373 ExprKind
::Field(..) => ExprPrecedence
::Field
,
1374 ExprKind
::Index(..) => ExprPrecedence
::Index
,
1375 ExprKind
::Path(..) => ExprPrecedence
::Path
,
1376 ExprKind
::AddrOf(..) => ExprPrecedence
::AddrOf
,
1377 ExprKind
::Break(..) => ExprPrecedence
::Break
,
1378 ExprKind
::Continue(..) => ExprPrecedence
::Continue
,
1379 ExprKind
::Ret(..) => ExprPrecedence
::Ret
,
1380 ExprKind
::InlineAsm(..) => ExprPrecedence
::InlineAsm
,
1381 ExprKind
::LlvmInlineAsm(..) => ExprPrecedence
::InlineAsm
,
1382 ExprKind
::Struct(..) => ExprPrecedence
::Struct
,
1383 ExprKind
::Repeat(..) => ExprPrecedence
::Repeat
,
1384 ExprKind
::Yield(..) => ExprPrecedence
::Yield
,
1385 ExprKind
::Err
=> ExprPrecedence
::Err
,
1389 // Whether this looks like a place expr, without checking for deref
1391 // This will return `true` in some potentially surprising cases such as
1392 // `CONSTANT.field`.
1393 pub fn is_syntactic_place_expr(&self) -> bool
{
1394 self.is_place_expr(|_
| true)
1397 /// Whether this is a place expression.
1399 /// `allow_projections_from` should return `true` if indexing a field or index expression based
1400 /// on the given expression should be considered a place expression.
1401 pub fn is_place_expr(&self, mut allow_projections_from
: impl FnMut(&Self) -> bool
) -> bool
{
1403 ExprKind
::Path(QPath
::Resolved(_
, ref path
)) => {
1404 matches
!(path
.res
, Res
::Local(..) | Res
::Def(DefKind
::Static
, _
) | Res
::Err
)
1407 // Type ascription inherits its place expression kind from its
1409 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1410 ExprKind
::Type(ref e
, _
) => e
.is_place_expr(allow_projections_from
),
1412 ExprKind
::Unary(UnOp
::UnDeref
, _
) => true,
1414 ExprKind
::Field(ref base
, _
) | ExprKind
::Index(ref base
, _
) => {
1415 allow_projections_from(base
) || base
.is_place_expr(allow_projections_from
)
1418 // Lang item paths cannot currently be local variables or statics.
1419 ExprKind
::Path(QPath
::LangItem(..)) => false,
1421 // Partially qualified paths in expressions can only legally
1422 // refer to associated items which are always rvalues.
1423 ExprKind
::Path(QPath
::TypeRelative(..))
1424 | ExprKind
::Call(..)
1425 | ExprKind
::MethodCall(..)
1426 | ExprKind
::Struct(..)
1428 | ExprKind
::Match(..)
1429 | ExprKind
::Closure(..)
1430 | ExprKind
::Block(..)
1431 | ExprKind
::Repeat(..)
1432 | ExprKind
::Array(..)
1433 | ExprKind
::Break(..)
1434 | ExprKind
::Continue(..)
1436 | ExprKind
::Loop(..)
1437 | ExprKind
::Assign(..)
1438 | ExprKind
::InlineAsm(..)
1439 | ExprKind
::LlvmInlineAsm(..)
1440 | ExprKind
::AssignOp(..)
1442 | ExprKind
::ConstBlock(..)
1443 | ExprKind
::Unary(..)
1445 | ExprKind
::AddrOf(..)
1446 | ExprKind
::Binary(..)
1447 | ExprKind
::Yield(..)
1448 | ExprKind
::Cast(..)
1449 | ExprKind
::DropTemps(..)
1450 | ExprKind
::Err
=> false,
1454 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1455 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1456 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1457 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1458 /// beyond remembering to call this function before doing analysis on it.
1459 pub fn peel_drop_temps(&self) -> &Self {
1460 let mut expr
= self;
1461 while let ExprKind
::DropTemps(inner
) = &expr
.kind
{
1468 /// Checks if the specified expression is a built-in range literal.
1469 /// (See: `LoweringContext::lower_expr()`).
1470 pub fn is_range_literal(expr
: &Expr
<'_
>) -> bool
{
1472 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1473 ExprKind
::Struct(ref qpath
, _
, _
) => matches
!(
1478 | LangItem
::RangeFrom
1479 | LangItem
::RangeFull
1480 | LangItem
::RangeToInclusive
,
1485 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1486 ExprKind
::Call(ref func
, _
) => {
1487 matches
!(func
.kind
, ExprKind
::Path(QPath
::LangItem(LangItem
::RangeInclusiveNew
, _
)))
1494 #[derive(Debug, HashStable_Generic)]
1495 pub enum ExprKind
<'hir
> {
1496 /// A `box x` expression.
1497 Box(&'hir Expr
<'hir
>),
1498 /// Allow anonymous constants from an inline `const` block
1499 ConstBlock(AnonConst
),
1500 /// An array (e.g., `[a, b, c, d]`).
1501 Array(&'hir
[Expr
<'hir
>]),
1502 /// A function call.
1504 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1505 /// and the second field is the list of arguments.
1506 /// This also represents calling the constructor of
1507 /// tuple-like ADTs such as tuple structs and enum variants.
1508 Call(&'hir Expr
<'hir
>, &'hir
[Expr
<'hir
>]),
1509 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1511 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1512 /// (within the angle brackets).
1513 /// The first element of the vector of `Expr`s is the expression that evaluates
1514 /// to the object on which the method is being called on (the receiver),
1515 /// and the remaining elements are the rest of the arguments.
1516 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1517 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1518 /// The final `Span` represents the span of the function and arguments
1519 /// (e.g. `foo::<Bar, Baz>(a, b, c, d)` in `x.foo::<Bar, Baz>(a, b, c, d)`
1521 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1522 /// the `hir_id` of the `MethodCall` node itself.
1524 /// [`type_dependent_def_id`]: ../ty/struct.TypeckResults.html#method.type_dependent_def_id
1525 MethodCall(&'hir PathSegment
<'hir
>, Span
, &'hir
[Expr
<'hir
>], Span
),
1526 /// A tuple (e.g., `(a, b, c, d)`).
1527 Tup(&'hir
[Expr
<'hir
>]),
1528 /// A binary operation (e.g., `a + b`, `a * b`).
1529 Binary(BinOp
, &'hir Expr
<'hir
>, &'hir Expr
<'hir
>),
1530 /// A unary operation (e.g., `!x`, `*x`).
1531 Unary(UnOp
, &'hir Expr
<'hir
>),
1532 /// A literal (e.g., `1`, `"foo"`).
1534 /// A cast (e.g., `foo as f64`).
1535 Cast(&'hir Expr
<'hir
>, &'hir Ty
<'hir
>),
1536 /// A type reference (e.g., `Foo`).
1537 Type(&'hir Expr
<'hir
>, &'hir Ty
<'hir
>),
1538 /// Wraps the expression in a terminating scope.
1539 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1541 /// This construct only exists to tweak the drop order in HIR lowering.
1542 /// An example of that is the desugaring of `for` loops.
1543 DropTemps(&'hir Expr
<'hir
>),
1544 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1546 /// I.e., `'label: loop { <block> }`.
1547 Loop(&'hir Block
<'hir
>, Option
<Label
>, LoopSource
),
1548 /// A `match` block, with a source that indicates whether or not it is
1549 /// the result of a desugaring, and if so, which kind.
1550 Match(&'hir Expr
<'hir
>, &'hir
[Arm
<'hir
>], MatchSource
),
1551 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1553 /// The `Span` is the argument block `|...|`.
1555 /// This may also be a generator literal or an `async block` as indicated by the
1556 /// `Option<Movability>`.
1557 Closure(CaptureBy
, &'hir FnDecl
<'hir
>, BodyId
, Span
, Option
<Movability
>),
1558 /// A block (e.g., `'label: { ... }`).
1559 Block(&'hir Block
<'hir
>, Option
<Label
>),
1561 /// An assignment (e.g., `a = foo()`).
1562 Assign(&'hir Expr
<'hir
>, &'hir Expr
<'hir
>, Span
),
1563 /// An assignment with an operator.
1566 AssignOp(BinOp
, &'hir Expr
<'hir
>, &'hir Expr
<'hir
>),
1567 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1568 Field(&'hir Expr
<'hir
>, Ident
),
1569 /// An indexing operation (`foo[2]`).
1570 Index(&'hir Expr
<'hir
>, &'hir Expr
<'hir
>),
1572 /// Path to a definition, possibly containing lifetime or type parameters.
1575 /// A referencing operation (i.e., `&a` or `&mut a`).
1576 AddrOf(BorrowKind
, Mutability
, &'hir Expr
<'hir
>),
1577 /// A `break`, with an optional label to break.
1578 Break(Destination
, Option
<&'hir Expr
<'hir
>>),
1579 /// A `continue`, with an optional label.
1580 Continue(Destination
),
1581 /// A `return`, with an optional value to be returned.
1582 Ret(Option
<&'hir Expr
<'hir
>>),
1584 /// Inline assembly (from `asm!`), with its outputs and inputs.
1585 InlineAsm(&'hir InlineAsm
<'hir
>),
1586 /// Inline assembly (from `llvm_asm!`), with its outputs and inputs.
1587 LlvmInlineAsm(&'hir LlvmInlineAsm
<'hir
>),
1589 /// A struct or struct-like variant literal expression.
1591 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1592 /// where `base` is the `Option<Expr>`.
1593 Struct(&'hir QPath
<'hir
>, &'hir
[Field
<'hir
>], Option
<&'hir Expr
<'hir
>>),
1595 /// An array literal constructed from one repeated element.
1597 /// E.g., `[1; 5]`. The first expression is the element
1598 /// to be repeated; the second is the number of times to repeat it.
1599 Repeat(&'hir Expr
<'hir
>, AnonConst
),
1601 /// A suspension point for generators (i.e., `yield <expr>`).
1602 Yield(&'hir Expr
<'hir
>, YieldSource
),
1604 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1608 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1610 /// To resolve the path to a `DefId`, call [`qpath_res`].
1612 /// [`qpath_res`]: ../rustc_middle/ty/struct.TypeckResults.html#method.qpath_res
1613 #[derive(Debug, HashStable_Generic)]
1614 pub enum QPath
<'hir
> {
1615 /// Path to a definition, optionally "fully-qualified" with a `Self`
1616 /// type, if the path points to an associated item in a trait.
1618 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1619 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1620 /// even though they both have the same two-segment `Clone::clone` `Path`.
1621 Resolved(Option
<&'hir Ty
<'hir
>>, &'hir Path
<'hir
>),
1623 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1624 /// Will be resolved by type-checking to an associated item.
1626 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1627 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1628 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1629 TypeRelative(&'hir Ty
<'hir
>, &'hir PathSegment
<'hir
>),
1631 /// Reference to a `#[lang = "foo"]` item.
1632 LangItem(LangItem
, Span
),
1635 impl<'hir
> QPath
<'hir
> {
1636 /// Returns the span of this `QPath`.
1637 pub fn span(&self) -> Span
{
1639 QPath
::Resolved(_
, path
) => path
.span
,
1640 QPath
::TypeRelative(_
, ps
) => ps
.ident
.span
,
1641 QPath
::LangItem(_
, span
) => span
,
1645 /// Returns the span of the qself of this `QPath`. For example, `()` in
1646 /// `<() as Trait>::method`.
1647 pub fn qself_span(&self) -> Span
{
1649 QPath
::Resolved(_
, path
) => path
.span
,
1650 QPath
::TypeRelative(qself
, _
) => qself
.span
,
1651 QPath
::LangItem(_
, span
) => span
,
1655 /// Returns the span of the last segment of this `QPath`. For example, `method` in
1656 /// `<() as Trait>::method`.
1657 pub fn last_segment_span(&self) -> Span
{
1659 QPath
::Resolved(_
, path
) => path
.segments
.last().unwrap().ident
.span
,
1660 QPath
::TypeRelative(_
, segment
) => segment
.ident
.span
,
1661 QPath
::LangItem(_
, span
) => span
,
1666 /// Hints at the original code for a let statement.
1667 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1668 pub enum LocalSource
{
1669 /// A `match _ { .. }`.
1671 /// A desugared `for _ in _ { .. }` loop.
1673 /// When lowering async functions, we create locals within the `async move` so that
1674 /// all parameters are dropped after the future is polled.
1676 /// ```ignore (pseudo-Rust)
1677 /// async fn foo(<pattern> @ x: Type) {
1679 /// let <pattern> = x;
1684 /// A desugared `<expr>.await`.
1686 /// A desugared `expr = expr`, where the LHS is a tuple, struct or array.
1687 /// The span is that of the `=` sign.
1688 AssignDesugar(Span
),
1691 /// Hints at the original code for a `match _ { .. }`.
1692 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
1693 #[derive(HashStable_Generic)]
1694 pub enum MatchSource
{
1695 /// A `match _ { .. }`.
1697 /// An `if _ { .. }` (optionally with `else { .. }`).
1698 IfDesugar { contains_else_clause: bool }
,
1699 /// An `if let _ = _ { .. }` (optionally with `else { .. }`).
1700 IfLetDesugar { contains_else_clause: bool }
,
1701 /// A `while _ { .. }` (which was desugared to a `loop { match _ { .. } }`).
1703 /// A `while let _ = _ { .. }` (which was desugared to a
1704 /// `loop { match _ { .. } }`).
1706 /// A desugared `for _ in _ { .. }` loop.
1708 /// A desugared `?` operator.
1710 /// A desugared `<expr>.await`.
1715 pub fn name(self) -> &'
static str {
1719 IfDesugar { .. }
| IfLetDesugar { .. }
=> "if",
1720 WhileDesugar
| WhileLetDesugar
=> "while",
1721 ForLoopDesugar
=> "for",
1723 AwaitDesugar
=> ".await",
1728 /// The loop type that yielded an `ExprKind::Loop`.
1729 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1730 pub enum LoopSource
{
1731 /// A `loop { .. }` loop.
1733 /// A `while _ { .. }` loop.
1735 /// A `while let _ = _ { .. }` loop.
1737 /// A `for _ in _ { .. }` loop.
1742 pub fn name(self) -> &'
static str {
1744 LoopSource
::Loop
=> "loop",
1745 LoopSource
::While
| LoopSource
::WhileLet
=> "while",
1746 LoopSource
::ForLoop
=> "for",
1751 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1752 pub enum LoopIdError
{
1754 UnlabeledCfInWhileCondition
,
1758 impl fmt
::Display
for LoopIdError
{
1759 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1760 f
.write_str(match self {
1761 LoopIdError
::OutsideLoopScope
=> "not inside loop scope",
1762 LoopIdError
::UnlabeledCfInWhileCondition
=> {
1763 "unlabeled control flow (break or continue) in while condition"
1765 LoopIdError
::UnresolvedLabel
=> "label not found",
1770 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1771 pub struct Destination
{
1772 // This is `Some(_)` iff there is an explicit user-specified `label
1773 pub label
: Option
<Label
>,
1775 // These errors are caught and then reported during the diagnostics pass in
1776 // librustc_passes/loops.rs
1777 pub target_id
: Result
<HirId
, LoopIdError
>,
1780 /// The yield kind that caused an `ExprKind::Yield`.
1781 #[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
1782 pub enum YieldSource
{
1783 /// An `<expr>.await`.
1784 Await { expr: Option<HirId> }
,
1785 /// A plain `yield`.
1790 pub fn is_await(&self) -> bool
{
1792 YieldSource
::Await { .. }
=> true,
1793 YieldSource
::Yield
=> false,
1798 impl fmt
::Display
for YieldSource
{
1799 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1800 f
.write_str(match self {
1801 YieldSource
::Await { .. }
=> "`await`",
1802 YieldSource
::Yield
=> "`yield`",
1807 impl From
<GeneratorKind
> for YieldSource
{
1808 fn from(kind
: GeneratorKind
) -> Self {
1810 // Guess based on the kind of the current generator.
1811 GeneratorKind
::Gen
=> Self::Yield
,
1812 GeneratorKind
::Async(_
) => Self::Await { expr: None }
,
1817 // N.B., if you change this, you'll probably want to change the corresponding
1818 // type structure in middle/ty.rs as well.
1819 #[derive(Debug, HashStable_Generic)]
1820 pub struct MutTy
<'hir
> {
1821 pub ty
: &'hir Ty
<'hir
>,
1822 pub mutbl
: Mutability
,
1825 /// Represents a function's signature in a trait declaration,
1826 /// trait implementation, or a free function.
1827 #[derive(Debug, HashStable_Generic)]
1828 pub struct FnSig
<'hir
> {
1829 pub header
: FnHeader
,
1830 pub decl
: &'hir FnDecl
<'hir
>,
1834 // The bodies for items are stored "out of line", in a separate
1835 // hashmap in the `Crate`. Here we just record the node-id of the item
1836 // so it can fetched later.
1837 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
1838 pub struct TraitItemId
{
1842 /// Represents an item declaration within a trait declaration,
1843 /// possibly including a default implementation. A trait item is
1844 /// either required (meaning it doesn't have an implementation, just a
1845 /// signature) or provided (meaning it has a default implementation).
1847 pub struct TraitItem
<'hir
> {
1850 pub attrs
: &'hir
[Attribute
],
1851 pub generics
: Generics
<'hir
>,
1852 pub kind
: TraitItemKind
<'hir
>,
1856 /// Represents a trait method's body (or just argument names).
1857 #[derive(Encodable, Debug, HashStable_Generic)]
1858 pub enum TraitFn
<'hir
> {
1859 /// No default body in the trait, just a signature.
1860 Required(&'hir
[Ident
]),
1862 /// Both signature and body are provided in the trait.
1866 /// Represents a trait method or associated constant or type
1867 #[derive(Debug, HashStable_Generic)]
1868 pub enum TraitItemKind
<'hir
> {
1869 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
1870 Const(&'hir Ty
<'hir
>, Option
<BodyId
>),
1871 /// An associated function with an optional body.
1872 Fn(FnSig
<'hir
>, TraitFn
<'hir
>),
1873 /// An associated type with (possibly empty) bounds and optional concrete
1875 Type(GenericBounds
<'hir
>, Option
<&'hir Ty
<'hir
>>),
1878 // The bodies for items are stored "out of line", in a separate
1879 // hashmap in the `Crate`. Here we just record the node-id of the item
1880 // so it can fetched later.
1881 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
1882 pub struct ImplItemId
{
1886 /// Represents anything within an `impl` block.
1888 pub struct ImplItem
<'hir
> {
1891 pub vis
: Visibility
<'hir
>,
1892 pub defaultness
: Defaultness
,
1893 pub attrs
: &'hir
[Attribute
],
1894 pub generics
: Generics
<'hir
>,
1895 pub kind
: ImplItemKind
<'hir
>,
1899 /// Represents various kinds of content within an `impl`.
1900 #[derive(Debug, HashStable_Generic)]
1901 pub enum ImplItemKind
<'hir
> {
1902 /// An associated constant of the given type, set to the constant result
1903 /// of the expression.
1904 Const(&'hir Ty
<'hir
>, BodyId
),
1905 /// An associated function implementation with the given signature and body.
1906 Fn(FnSig
<'hir
>, BodyId
),
1907 /// An associated type.
1908 TyAlias(&'hir Ty
<'hir
>),
1911 impl ImplItemKind
<'_
> {
1912 pub fn namespace(&self) -> Namespace
{
1914 ImplItemKind
::TyAlias(..) => Namespace
::TypeNS
,
1915 ImplItemKind
::Const(..) | ImplItemKind
::Fn(..) => Namespace
::ValueNS
,
1920 // The name of the associated type for `Fn` return types.
1921 pub const FN_OUTPUT_NAME
: Symbol
= sym
::Output
;
1923 /// Bind a type to an associated type (i.e., `A = Foo`).
1925 /// Bindings like `A: Debug` are represented as a special type `A =
1926 /// $::Debug` that is understood by the astconv code.
1928 /// FIXME(alexreg): why have a separate type for the binding case,
1929 /// wouldn't it be better to make the `ty` field an enum like the
1933 /// enum TypeBindingKind {
1938 #[derive(Debug, HashStable_Generic)]
1939 pub struct TypeBinding
<'hir
> {
1941 #[stable_hasher(project(name))]
1943 pub kind
: TypeBindingKind
<'hir
>,
1947 // Represents the two kinds of type bindings.
1948 #[derive(Debug, HashStable_Generic)]
1949 pub enum TypeBindingKind
<'hir
> {
1950 /// E.g., `Foo<Bar: Send>`.
1951 Constraint { bounds: &'hir [GenericBound<'hir>] }
,
1952 /// E.g., `Foo<Bar = ()>`.
1953 Equality { ty: &'hir Ty<'hir> }
,
1956 impl TypeBinding
<'_
> {
1957 pub fn ty(&self) -> &Ty
<'_
> {
1959 TypeBindingKind
::Equality { ref ty }
=> ty
,
1960 _
=> panic
!("expected equality type binding for parenthesized generic args"),
1966 pub struct Ty
<'hir
> {
1968 pub kind
: TyKind
<'hir
>,
1972 /// Not represented directly in the AST; referred to by name through a `ty_path`.
1973 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
1974 #[derive(HashStable_Generic)]
1985 pub fn name_str(self) -> &'
static str {
1987 PrimTy
::Int(i
) => i
.name_str(),
1988 PrimTy
::Uint(u
) => u
.name_str(),
1989 PrimTy
::Float(f
) => f
.name_str(),
1990 PrimTy
::Str
=> "str",
1991 PrimTy
::Bool
=> "bool",
1992 PrimTy
::Char
=> "char",
1996 pub fn name(self) -> Symbol
{
1998 PrimTy
::Int(i
) => i
.name(),
1999 PrimTy
::Uint(u
) => u
.name(),
2000 PrimTy
::Float(f
) => f
.name(),
2001 PrimTy
::Str
=> sym
::str,
2002 PrimTy
::Bool
=> sym
::bool
,
2003 PrimTy
::Char
=> sym
::char,
2008 #[derive(Debug, HashStable_Generic)]
2009 pub struct BareFnTy
<'hir
> {
2010 pub unsafety
: Unsafety
,
2012 pub generic_params
: &'hir
[GenericParam
<'hir
>],
2013 pub decl
: &'hir FnDecl
<'hir
>,
2014 pub param_names
: &'hir
[Ident
],
2017 #[derive(Debug, HashStable_Generic)]
2018 pub struct OpaqueTy
<'hir
> {
2019 pub generics
: Generics
<'hir
>,
2020 pub bounds
: GenericBounds
<'hir
>,
2021 pub impl_trait_fn
: Option
<DefId
>,
2022 pub origin
: OpaqueTyOrigin
,
2025 /// From whence the opaque type came.
2026 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2027 pub enum OpaqueTyOrigin
{
2032 /// `let _: impl Trait = ...`
2034 /// Impl trait in type aliases, consts, statics, bounds.
2038 /// The various kinds of types recognized by the compiler.
2039 #[derive(Debug, HashStable_Generic)]
2040 pub enum TyKind
<'hir
> {
2041 /// A variable length slice (i.e., `[T]`).
2042 Slice(&'hir Ty
<'hir
>),
2043 /// A fixed length array (i.e., `[T; n]`).
2044 Array(&'hir Ty
<'hir
>, AnonConst
),
2045 /// A raw pointer (i.e., `*const T` or `*mut T`).
2047 /// A reference (i.e., `&'a T` or `&'a mut T`).
2048 Rptr(Lifetime
, MutTy
<'hir
>),
2049 /// A bare function (e.g., `fn(usize) -> bool`).
2050 BareFn(&'hir BareFnTy
<'hir
>),
2051 /// The never type (`!`).
2053 /// A tuple (`(A, B, C, D, ...)`).
2054 Tup(&'hir
[Ty
<'hir
>]),
2055 /// A path to a type definition (`module::module::...::Type`), or an
2056 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2058 /// Type parameters may be stored in each `PathSegment`.
2060 /// A opaque type definition itself. This is currently only used for the
2061 /// `opaque type Foo: Trait` item that `impl Trait` in desugars to.
2063 /// The generic argument list contains the lifetimes (and in the future
2064 /// possibly parameters) that are actually bound on the `impl Trait`.
2065 OpaqueDef(ItemId
, &'hir
[GenericArg
<'hir
>]),
2066 /// A trait object type `Bound1 + Bound2 + Bound3`
2067 /// where `Bound` is a trait or a lifetime.
2068 TraitObject(&'hir
[PolyTraitRef
<'hir
>], Lifetime
),
2071 /// `TyKind::Infer` means the type should be inferred instead of it having been
2072 /// specified. This can appear anywhere in a type.
2074 /// Placeholder for a type that has failed to be defined.
2078 #[derive(Debug, HashStable_Generic)]
2079 pub enum InlineAsmOperand
<'hir
> {
2081 reg
: InlineAsmRegOrRegClass
,
2085 reg
: InlineAsmRegOrRegClass
,
2087 expr
: Option
<Expr
<'hir
>>,
2090 reg
: InlineAsmRegOrRegClass
,
2095 reg
: InlineAsmRegOrRegClass
,
2097 in_expr
: Expr
<'hir
>,
2098 out_expr
: Option
<Expr
<'hir
>>,
2108 impl<'hir
> InlineAsmOperand
<'hir
> {
2109 pub fn reg(&self) -> Option
<InlineAsmRegOrRegClass
> {
2111 Self::In { reg, .. }
2112 | Self::Out { reg, .. }
2113 | Self::InOut { reg, .. }
2114 | Self::SplitInOut { reg, .. }
=> Some(reg
),
2115 Self::Const { .. }
| Self::Sym { .. }
=> None
,
2120 #[derive(Debug, HashStable_Generic)]
2121 pub struct InlineAsm
<'hir
> {
2122 pub template
: &'hir
[InlineAsmTemplatePiece
],
2123 pub operands
: &'hir
[InlineAsmOperand
<'hir
>],
2124 pub options
: InlineAsmOptions
,
2125 pub line_spans
: &'hir
[Span
],
2128 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic, PartialEq)]
2129 pub struct LlvmInlineAsmOutput
{
2130 pub constraint
: Symbol
,
2132 pub is_indirect
: bool
,
2136 // NOTE(eddyb) This is used within MIR as well, so unlike the rest of the HIR,
2137 // it needs to be `Clone` and `Decodable` and use plain `Vec<T>` instead of
2138 // arena-allocated slice.
2139 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic, PartialEq)]
2140 pub struct LlvmInlineAsmInner
{
2142 pub asm_str_style
: StrStyle
,
2143 pub outputs
: Vec
<LlvmInlineAsmOutput
>,
2144 pub inputs
: Vec
<Symbol
>,
2145 pub clobbers
: Vec
<Symbol
>,
2147 pub alignstack
: bool
,
2148 pub dialect
: LlvmAsmDialect
,
2151 #[derive(Debug, HashStable_Generic)]
2152 pub struct LlvmInlineAsm
<'hir
> {
2153 pub inner
: LlvmInlineAsmInner
,
2154 pub outputs_exprs
: &'hir
[Expr
<'hir
>],
2155 pub inputs_exprs
: &'hir
[Expr
<'hir
>],
2158 /// Represents a parameter in a function header.
2159 #[derive(Debug, HashStable_Generic)]
2160 pub struct Param
<'hir
> {
2161 pub attrs
: &'hir
[Attribute
],
2163 pub pat
: &'hir Pat
<'hir
>,
2168 /// Represents the header (not the body) of a function declaration.
2169 #[derive(Debug, HashStable_Generic)]
2170 pub struct FnDecl
<'hir
> {
2171 /// The types of the function's parameters.
2173 /// Additional argument data is stored in the function's [body](Body::params).
2174 pub inputs
: &'hir
[Ty
<'hir
>],
2175 pub output
: FnRetTy
<'hir
>,
2176 pub c_variadic
: bool
,
2177 /// Does the function have an implicit self?
2178 pub implicit_self
: ImplicitSelfKind
,
2181 /// Represents what type of implicit self a function has, if any.
2182 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2183 pub enum ImplicitSelfKind
{
2184 /// Represents a `fn x(self);`.
2186 /// Represents a `fn x(mut self);`.
2188 /// Represents a `fn x(&self);`.
2190 /// Represents a `fn x(&mut self);`.
2192 /// Represents when a function does not have a self argument or
2193 /// when a function has a `self: X` argument.
2197 impl ImplicitSelfKind
{
2198 /// Does this represent an implicit self?
2199 pub fn has_implicit_self(&self) -> bool
{
2200 !matches
!(*self, ImplicitSelfKind
::None
)
2204 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable, Debug)]
2205 #[derive(HashStable_Generic)]
2211 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable, HashStable_Generic)]
2212 pub enum Defaultness
{
2213 Default { has_value: bool }
,
2218 pub fn has_value(&self) -> bool
{
2220 Defaultness
::Default { has_value }
=> has_value
,
2221 Defaultness
::Final
=> true,
2225 pub fn is_final(&self) -> bool
{
2226 *self == Defaultness
::Final
2229 pub fn is_default(&self) -> bool
{
2230 matches
!(*self, Defaultness
::Default { .. }
)
2234 #[derive(Debug, HashStable_Generic)]
2235 pub enum FnRetTy
<'hir
> {
2236 /// Return type is not specified.
2238 /// Functions default to `()` and
2239 /// closures default to inference. Span points to where return
2240 /// type would be inserted.
2241 DefaultReturn(Span
),
2242 /// Everything else.
2243 Return(&'hir Ty
<'hir
>),
2247 pub fn span(&self) -> Span
{
2249 Self::DefaultReturn(span
) => span
,
2250 Self::Return(ref ty
) => ty
.span
,
2255 #[derive(Encodable, Debug)]
2256 pub struct Mod
<'hir
> {
2257 /// A span from the first token past `{` to the last token until `}`.
2258 /// For `mod foo;`, the inner span ranges from the first token
2259 /// to the last token in the external file.
2261 pub item_ids
: &'hir
[ItemId
],
2264 #[derive(Debug, HashStable_Generic)]
2265 pub struct ForeignMod
<'hir
> {
2267 pub items
: &'hir
[ForeignItem
<'hir
>],
2270 #[derive(Encodable, Debug, HashStable_Generic)]
2271 pub struct GlobalAsm
{
2275 #[derive(Debug, HashStable_Generic)]
2276 pub struct EnumDef
<'hir
> {
2277 pub variants
: &'hir
[Variant
<'hir
>],
2280 #[derive(Debug, HashStable_Generic)]
2281 pub struct Variant
<'hir
> {
2282 /// Name of the variant.
2283 #[stable_hasher(project(name))]
2285 /// Attributes of the variant.
2286 pub attrs
: &'hir
[Attribute
],
2287 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2289 /// Fields and constructor id of the variant.
2290 pub data
: VariantData
<'hir
>,
2291 /// Explicit discriminant (e.g., `Foo = 1`).
2292 pub disr_expr
: Option
<AnonConst
>,
2297 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2299 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2300 /// Also produced for each element of a list `use`, e.g.
2301 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2304 /// Glob import, e.g., `use foo::*`.
2307 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2308 /// an additional `use foo::{}` for performing checks such as
2309 /// unstable feature gating. May be removed in the future.
2313 /// References to traits in impls.
2315 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2316 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2317 /// trait being referred to but just a unique `HirId` that serves as a key
2318 /// within the resolution map.
2319 #[derive(Debug, HashStable_Generic)]
2320 pub struct TraitRef
<'hir
> {
2321 pub path
: &'hir Path
<'hir
>,
2322 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2323 #[stable_hasher(ignore)]
2324 pub hir_ref_id
: HirId
,
2328 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2329 pub fn trait_def_id(&self) -> Option
<DefId
> {
2330 match self.path
.res
{
2331 Res
::Def(DefKind
::Trait
| DefKind
::TraitAlias
, did
) => Some(did
),
2333 _
=> unreachable
!(),
2338 #[derive(Debug, HashStable_Generic)]
2339 pub struct PolyTraitRef
<'hir
> {
2340 /// The `'a` in `for<'a> Foo<&'a T>`.
2341 pub bound_generic_params
: &'hir
[GenericParam
<'hir
>],
2343 /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
2344 pub trait_ref
: TraitRef
<'hir
>,
2349 pub type Visibility
<'hir
> = Spanned
<VisibilityKind
<'hir
>>;
2352 pub enum VisibilityKind
<'hir
> {
2355 Restricted { path: &'hir Path<'hir>, hir_id: HirId }
,
2359 impl VisibilityKind
<'_
> {
2360 pub fn is_pub(&self) -> bool
{
2361 matches
!(*self, VisibilityKind
::Public
)
2364 pub fn is_pub_restricted(&self) -> bool
{
2366 VisibilityKind
::Public
| VisibilityKind
::Inherited
=> false,
2367 VisibilityKind
::Crate(..) | VisibilityKind
::Restricted { .. }
=> true,
2372 #[derive(Debug, HashStable_Generic)]
2373 pub struct StructField
<'hir
> {
2375 #[stable_hasher(project(name))]
2377 pub vis
: Visibility
<'hir
>,
2379 pub ty
: &'hir Ty
<'hir
>,
2380 pub attrs
: &'hir
[Attribute
],
2383 impl StructField
<'_
> {
2384 // Still necessary in couple of places
2385 pub fn is_positional(&self) -> bool
{
2386 let first
= self.ident
.as_str().as_bytes()[0];
2387 first
>= b'
0'
&& first
<= b'
9'
2391 /// Fields and constructor IDs of enum variants and structs.
2392 #[derive(Debug, HashStable_Generic)]
2393 pub enum VariantData
<'hir
> {
2394 /// A struct variant.
2396 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2397 Struct(&'hir
[StructField
<'hir
>], /* recovered */ bool
),
2398 /// A tuple variant.
2400 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2401 Tuple(&'hir
[StructField
<'hir
>], HirId
),
2404 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2408 impl VariantData
<'hir
> {
2409 /// Return the fields of this variant.
2410 pub fn fields(&self) -> &'hir
[StructField
<'hir
>] {
2412 VariantData
::Struct(ref fields
, ..) | VariantData
::Tuple(ref fields
, ..) => fields
,
2417 /// Return the `HirId` of this variant's constructor, if it has one.
2418 pub fn ctor_hir_id(&self) -> Option
<HirId
> {
2420 VariantData
::Struct(_
, _
) => None
,
2421 VariantData
::Tuple(_
, hir_id
) | VariantData
::Unit(hir_id
) => Some(hir_id
),
2426 // The bodies for items are stored "out of line", in a separate
2427 // hashmap in the `Crate`. Here we just record the node-id of the item
2428 // so it can fetched later.
2429 #[derive(Copy, Clone, Encodable, Debug)]
2436 /// The name might be a dummy name in case of anonymous items
2438 pub struct Item
<'hir
> {
2441 pub attrs
: &'hir
[Attribute
],
2442 pub kind
: ItemKind
<'hir
>,
2443 pub vis
: Visibility
<'hir
>,
2447 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2448 #[derive(Encodable, Decodable, HashStable_Generic)]
2455 pub fn prefix_str(&self) -> &'
static str {
2457 Self::Unsafe
=> "unsafe ",
2463 impl fmt
::Display
for Unsafety
{
2464 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2465 f
.write_str(match *self {
2466 Self::Unsafe
=> "unsafe",
2467 Self::Normal
=> "normal",
2472 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2473 #[derive(Encodable, Decodable, HashStable_Generic)]
2474 pub enum Constness
{
2479 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2480 pub struct FnHeader
{
2481 pub unsafety
: Unsafety
,
2482 pub constness
: Constness
,
2483 pub asyncness
: IsAsync
,
2488 pub fn is_const(&self) -> bool
{
2489 matches
!(&self.constness
, Constness
::Const
)
2493 #[derive(Debug, HashStable_Generic)]
2494 pub enum ItemKind
<'hir
> {
2495 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2497 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2498 ExternCrate(Option
<Symbol
>),
2500 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2504 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2505 Use(&'hir Path
<'hir
>, UseKind
),
2507 /// A `static` item.
2508 Static(&'hir Ty
<'hir
>, Mutability
, BodyId
),
2510 Const(&'hir Ty
<'hir
>, BodyId
),
2511 /// A function declaration.
2512 Fn(FnSig
<'hir
>, Generics
<'hir
>, BodyId
),
2515 /// An external module, e.g. `extern { .. }`.
2516 ForeignMod(ForeignMod
<'hir
>),
2517 /// Module-level inline assembly (from `global_asm!`).
2518 GlobalAsm(&'hir GlobalAsm
),
2519 /// A type alias, e.g., `type Foo = Bar<u8>`.
2520 TyAlias(&'hir Ty
<'hir
>, Generics
<'hir
>),
2521 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2522 OpaqueTy(OpaqueTy
<'hir
>),
2523 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2524 Enum(EnumDef
<'hir
>, Generics
<'hir
>),
2525 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2526 Struct(VariantData
<'hir
>, Generics
<'hir
>),
2527 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2528 Union(VariantData
<'hir
>, Generics
<'hir
>),
2529 /// A trait definition.
2530 Trait(IsAuto
, Unsafety
, Generics
<'hir
>, GenericBounds
<'hir
>, &'hir
[TraitItemRef
]),
2532 TraitAlias(Generics
<'hir
>, GenericBounds
<'hir
>),
2534 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2537 polarity
: ImplPolarity
,
2538 defaultness
: Defaultness
,
2539 // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata
2540 // decoding as `Span`s cannot be decoded when a `Session` is not available.
2541 defaultness_span
: Option
<Span
>,
2542 constness
: Constness
,
2543 generics
: Generics
<'hir
>,
2545 /// The trait being implemented, if any.
2546 of_trait
: Option
<TraitRef
<'hir
>>,
2548 self_ty
: &'hir Ty
<'hir
>,
2549 items
: &'hir
[ImplItemRef
<'hir
>],
2554 pub fn generics(&self) -> Option
<&Generics
<'_
>> {
2556 ItemKind
::Fn(_
, ref generics
, _
)
2557 | ItemKind
::TyAlias(_
, ref generics
)
2558 | ItemKind
::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. }
)
2559 | ItemKind
::Enum(_
, ref generics
)
2560 | ItemKind
::Struct(_
, ref generics
)
2561 | ItemKind
::Union(_
, ref generics
)
2562 | ItemKind
::Trait(_
, _
, ref generics
, _
, _
)
2563 | ItemKind
::Impl { ref generics, .. }
=> generics
,
2569 /// A reference from an trait to one of its associated items. This
2570 /// contains the item's id, naturally, but also the item's name and
2571 /// some other high-level details (like whether it is an associated
2572 /// type or method, and whether it is public). This allows other
2573 /// passes to find the impl they want without loading the ID (which
2574 /// means fewer edges in the incremental compilation graph).
2575 #[derive(Encodable, Debug, HashStable_Generic)]
2576 pub struct TraitItemRef
{
2577 pub id
: TraitItemId
,
2578 #[stable_hasher(project(name))]
2580 pub kind
: AssocItemKind
,
2582 pub defaultness
: Defaultness
,
2585 /// A reference from an impl to one of its associated items. This
2586 /// contains the item's ID, naturally, but also the item's name and
2587 /// some other high-level details (like whether it is an associated
2588 /// type or method, and whether it is public). This allows other
2589 /// passes to find the impl they want without loading the ID (which
2590 /// means fewer edges in the incremental compilation graph).
2591 #[derive(Debug, HashStable_Generic)]
2592 pub struct ImplItemRef
<'hir
> {
2594 #[stable_hasher(project(name))]
2596 pub kind
: AssocItemKind
,
2598 pub vis
: Visibility
<'hir
>,
2599 pub defaultness
: Defaultness
,
2602 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2603 pub enum AssocItemKind
{
2605 Fn { has_self: bool }
,
2609 #[derive(Debug, HashStable_Generic)]
2610 pub struct ForeignItem
<'hir
> {
2611 #[stable_hasher(project(name))]
2613 pub attrs
: &'hir
[Attribute
],
2614 pub kind
: ForeignItemKind
<'hir
>,
2617 pub vis
: Visibility
<'hir
>,
2620 /// An item within an `extern` block.
2621 #[derive(Debug, HashStable_Generic)]
2622 pub enum ForeignItemKind
<'hir
> {
2623 /// A foreign function.
2624 Fn(&'hir FnDecl
<'hir
>, &'hir
[Ident
], Generics
<'hir
>),
2625 /// A foreign static item (`static ext: u8`).
2626 Static(&'hir Ty
<'hir
>, Mutability
),
2631 /// A variable captured by a closure.
2632 #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)]
2634 // First span where it is accessed (there can be multiple).
2638 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2639 // has length > 0 if the trait is found through an chain of imports, starting with the
2640 // import/use statement in the scope where the trait is used.
2641 #[derive(Encodable, Decodable, Clone, Debug)]
2642 pub struct TraitCandidate
{
2644 pub import_ids
: SmallVec
<[LocalDefId
; 1]>,
2647 #[derive(Copy, Clone, Debug, HashStable_Generic)]
2648 pub enum Node
<'hir
> {
2649 Param(&'hir Param
<'hir
>),
2650 Item(&'hir Item
<'hir
>),
2651 ForeignItem(&'hir ForeignItem
<'hir
>),
2652 TraitItem(&'hir TraitItem
<'hir
>),
2653 ImplItem(&'hir ImplItem
<'hir
>),
2654 Variant(&'hir Variant
<'hir
>),
2655 Field(&'hir StructField
<'hir
>),
2656 AnonConst(&'hir AnonConst
),
2657 Expr(&'hir Expr
<'hir
>),
2658 Stmt(&'hir Stmt
<'hir
>),
2659 PathSegment(&'hir PathSegment
<'hir
>),
2661 TraitRef(&'hir TraitRef
<'hir
>),
2662 Binding(&'hir Pat
<'hir
>),
2663 Pat(&'hir Pat
<'hir
>),
2664 Arm(&'hir Arm
<'hir
>),
2665 Block(&'hir Block
<'hir
>),
2666 Local(&'hir Local
<'hir
>),
2667 MacroDef(&'hir MacroDef
<'hir
>),
2669 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
2670 /// with synthesized constructors.
2671 Ctor(&'hir VariantData
<'hir
>),
2673 Lifetime(&'hir Lifetime
),
2674 GenericParam(&'hir GenericParam
<'hir
>),
2675 Visibility(&'hir Visibility
<'hir
>),
2677 Crate(&'hir CrateItem
<'hir
>),
2680 impl<'hir
> Node
<'hir
> {
2681 pub fn ident(&self) -> Option
<Ident
> {
2683 Node
::TraitItem(TraitItem { ident, .. }
)
2684 | Node
::ImplItem(ImplItem { ident, .. }
)
2685 | Node
::ForeignItem(ForeignItem { ident, .. }
)
2686 | Node
::Field(StructField { ident, .. }
)
2687 | Node
::Variant(Variant { ident, .. }
)
2688 | Node
::MacroDef(MacroDef { ident, .. }
)
2689 | Node
::Item(Item { ident, .. }
) => Some(*ident
),
2694 pub fn fn_decl(&self) -> Option
<&FnDecl
<'hir
>> {
2696 Node
::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. }
)
2697 | Node
::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. }
)
2698 | Node
::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }
) => Some(fn_sig
.decl
),
2699 Node
::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }
) => {
2706 pub fn body_id(&self) -> Option
<BodyId
> {
2708 Node
::TraitItem(TraitItem
{
2709 kind
: TraitItemKind
::Fn(_
, TraitFn
::Provided(body_id
)),
2712 | Node
::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. }
)
2713 | Node
::Item(Item { kind: ItemKind::Fn(.., body_id), .. }
) => Some(*body_id
),
2718 pub fn generics(&self) -> Option
<&'hir Generics
<'hir
>> {
2720 Node
::TraitItem(TraitItem { generics, .. }
)
2721 | Node
::ImplItem(ImplItem { generics, .. }
) => Some(generics
),
2722 Node
::Item(item
) => item
.kind
.generics(),
2727 pub fn hir_id(&self) -> Option
<HirId
> {
2729 Node
::Item(Item { hir_id, .. }
)
2730 | Node
::ForeignItem(ForeignItem { hir_id, .. }
)
2731 | Node
::TraitItem(TraitItem { hir_id, .. }
)
2732 | Node
::ImplItem(ImplItem { hir_id, .. }
)
2733 | Node
::Field(StructField { hir_id, .. }
)
2734 | Node
::AnonConst(AnonConst { hir_id, .. }
)
2735 | Node
::Expr(Expr { hir_id, .. }
)
2736 | Node
::Stmt(Stmt { hir_id, .. }
)
2737 | Node
::Ty(Ty { hir_id, .. }
)
2738 | Node
::Binding(Pat { hir_id, .. }
)
2739 | Node
::Pat(Pat { hir_id, .. }
)
2740 | Node
::Arm(Arm { hir_id, .. }
)
2741 | Node
::Block(Block { hir_id, .. }
)
2742 | Node
::Local(Local { hir_id, .. }
)
2743 | Node
::MacroDef(MacroDef { hir_id, .. }
)
2744 | Node
::Lifetime(Lifetime { hir_id, .. }
)
2745 | Node
::Param(Param { hir_id, .. }
)
2746 | Node
::GenericParam(GenericParam { hir_id, .. }
) => Some(*hir_id
),
2747 Node
::TraitRef(TraitRef { hir_ref_id, .. }
) => Some(*hir_ref_id
),
2748 Node
::PathSegment(PathSegment { hir_id, .. }
) => *hir_id
,
2749 Node
::Variant(Variant { id, .. }
) => Some(*id
),
2750 Node
::Ctor(variant
) => variant
.ctor_hir_id(),
2751 Node
::Crate(_
) | Node
::Visibility(_
) => None
,