1 //! HIR datatypes. See the [rustc guide] for more info.
3 //! [rustc guide]: https://rust-lang.github.io/rustc-guide/hir.html
5 pub use self::BlockCheckMode
::*;
6 pub use self::CaptureClause
::*;
7 pub use self::FunctionRetTy
::*;
8 pub use self::Mutability
::*;
9 pub use self::PrimTy
::*;
10 pub use self::UnOp
::*;
11 pub use self::UnsafeSource
::*;
13 use crate::hir
::def
::{Res, DefKind}
;
14 use crate::hir
::def_id
::{DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX}
;
15 use crate::hir
::ptr
::P
;
16 use crate::mir
::mono
::Linkage
;
17 use crate::ty
::AdtKind
;
18 use crate::ty
::query
::Providers
;
19 use crate::util
::nodemap
::{NodeMap, FxHashSet}
;
21 use errors
::FatalError
;
22 use syntax_pos
::{Span, DUMMY_SP, MultiSpan}
;
23 use syntax
::source_map
::Spanned
;
24 use syntax
::ast
::{self, CrateSugar, Ident, Name, NodeId, AsmDialect}
;
25 use syntax
::ast
::{Attribute, Label, LitKind, StrStyle, FloatTy, IntTy, UintTy}
;
26 use syntax
::attr
::{InlineAttr, OptimizeAttr}
;
27 use syntax
::symbol
::{Symbol, kw}
;
28 use syntax
::tokenstream
::TokenStream
;
29 use syntax
::util
::parser
::ExprPrecedence
;
30 use rustc_target
::spec
::abi
::Abi
;
31 use rustc_data_structures
::sync
::{par_for_each_in, Send, Sync}
;
32 use rustc_data_structures
::thin_vec
::ThinVec
;
33 use rustc_macros
::HashStable
;
34 use rustc_serialize
::{self, Encoder, Encodable, Decoder, Decodable}
;
35 use std
::collections
::{BTreeSet, BTreeMap}
;
37 use smallvec
::SmallVec
;
39 /// HIR doesn't commit to a concrete storage type and has its own alias for a vector.
40 /// It can be `Vec`, `P<[T]>` or potentially `Box<[T]>`, or some other container with similar
41 /// behavior. Unlike AST, HIR is mostly a static structure, so we can use an owned slice instead
42 /// of `Vec` to avoid keeping extra capacity.
43 pub type HirVec
<T
> = P
<[T
]>;
45 macro_rules
! hir_vec
{
46 ($elem
:expr
; $n
:expr
) => (
47 $
crate::hir
::HirVec
::from(vec
![$elem
; $n
])
50 $
crate::hir
::HirVec
::from(vec
![$
($x
),*])
58 pub mod itemlikevisit
;
66 /// Uniquely identifies a node in the HIR of the current crate. It is
67 /// composed of the `owner`, which is the `DefIndex` of the directly enclosing
68 /// `hir::Item`, `hir::TraitItem`, or `hir::ImplItem` (i.e., the closest "item-like"),
69 /// and the `local_id` which is unique within the given owner.
71 /// This two-level structure makes for more stable values: One can move an item
72 /// around within the source code, or add or remove stuff before it, without
73 /// the `local_id` part of the `HirId` changing, which is a very useful property in
74 /// incremental compilation where we have to persist things through changes to
76 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)]
79 pub local_id
: ItemLocalId
,
83 pub fn owner_def_id(self) -> DefId
{
84 DefId
::local(self.owner
)
87 pub fn owner_local_def_id(self) -> LocalDefId
{
88 LocalDefId
::from_def_id(DefId
::local(self.owner
))
92 impl rustc_serialize
::UseSpecializedEncodable
for HirId
{
93 fn default_encode
<S
: Encoder
>(&self, s
: &mut S
) -> Result
<(), S
::Error
> {
105 impl rustc_serialize
::UseSpecializedDecodable
for HirId
{
106 fn default_decode
<D
: Decoder
>(d
: &mut D
) -> Result
<HirId
, D
::Error
> {
107 let owner
= DefIndex
::decode(d
)?
;
108 let local_id
= ItemLocalId
::decode(d
)?
;
117 impl fmt
::Display
for HirId
{
118 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
119 write
!(f
, "{:?}", self)
123 // Hack to ensure that we don't try to access the private parts of `ItemLocalId` in this module.
124 mod item_local_id_inner
{
125 use rustc_index
::vec
::Idx
;
126 use rustc_macros
::HashStable
;
127 rustc_index
::newtype_index
! {
128 /// An `ItemLocalId` uniquely identifies something within a given "item-like";
129 /// that is, within a `hir::Item`, `hir::TraitItem`, or `hir::ImplItem`. There is no
130 /// guarantee that the numerical value of a given `ItemLocalId` corresponds to
131 /// the node's position within the owning item in any way, but there is a
132 /// guarantee that the `LocalItemId`s within an owner occupy a dense range of
133 /// integers starting at zero, so a mapping that maps all or most nodes within
134 /// an "item-like" to something else can be implemented by a `Vec` instead of a
135 /// tree or hash map.
136 pub struct ItemLocalId
{
142 pub use self::item_local_id_inner
::ItemLocalId
;
144 /// The `HirId` corresponding to `CRATE_NODE_ID` and `CRATE_DEF_INDEX`.
145 pub const CRATE_HIR_ID
: HirId
= HirId
{
146 owner
: CRATE_DEF_INDEX
,
147 local_id
: ItemLocalId
::from_u32_const(0)
150 pub const DUMMY_HIR_ID
: HirId
= HirId
{
151 owner
: CRATE_DEF_INDEX
,
152 local_id
: DUMMY_ITEM_LOCAL_ID
,
155 pub const DUMMY_ITEM_LOCAL_ID
: ItemLocalId
= ItemLocalId
::MAX
;
157 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, HashStable)]
158 pub struct Lifetime
{
162 /// Either "`'a`", referring to a named lifetime definition,
163 /// or "``" (i.e., `kw::Invalid`), for elision placeholders.
165 /// HIR lowering inserts these placeholders in type paths that
166 /// refer to type definitions needing lifetime parameters,
167 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
168 pub name
: LifetimeName
,
171 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy, HashStable)]
173 /// Some user-given name like `T` or `'x`.
176 /// Synthetic name generated when user elided a lifetime in an impl header.
178 /// E.g., the lifetimes in cases like these:
180 /// impl Foo for &u32
181 /// impl Foo<'_> for u32
183 /// in that case, we rewrite to
185 /// impl<'f> Foo for &'f u32
186 /// impl<'f> Foo<'f> for u32
188 /// where `'f` is something like `Fresh(0)`. The indices are
189 /// unique per impl, but not necessarily continuous.
192 /// Indicates an illegal name was given and an error has been
193 /// reported (so we should squelch other derived errors). Occurs
194 /// when, e.g., `'_` is used in the wrong place.
199 pub fn ident(&self) -> Ident
{
201 ParamName
::Plain(ident
) => ident
,
202 ParamName
::Fresh(_
) |
203 ParamName
::Error
=> Ident
::with_dummy_span(kw
::UnderscoreLifetime
),
207 pub fn modern(&self) -> ParamName
{
209 ParamName
::Plain(ident
) => ParamName
::Plain(ident
.modern()),
210 param_name
=> param_name
,
215 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy, HashStable)]
216 pub enum LifetimeName
{
217 /// User-given names or fresh (synthetic) names.
220 /// User wrote nothing (e.g., the lifetime in `&u32`).
223 /// Implicit lifetime in a context like `dyn Foo`. This is
224 /// distinguished from implicit lifetimes elsewhere because the
225 /// lifetime that they default to must appear elsewhere within the
226 /// enclosing type. This means that, in an `impl Trait` context, we
227 /// don't have to create a parameter for them. That is, `impl
228 /// Trait<Item = &u32>` expands to an opaque type like `type
229 /// Foo<'a> = impl Trait<Item = &'a u32>`, but `impl Trait<item =
230 /// dyn Bar>` expands to `type Foo = impl Trait<Item = dyn Bar +
231 /// 'static>`. The latter uses `ImplicitObjectLifetimeDefault` so
232 /// that surrounding code knows not to create a lifetime
234 ImplicitObjectLifetimeDefault
,
236 /// Indicates an error during lowering (usually `'_` in wrong place)
237 /// that was already reported.
240 /// User wrote specifies `'_`.
243 /// User wrote `'static`.
248 pub fn ident(&self) -> Ident
{
250 LifetimeName
::ImplicitObjectLifetimeDefault
251 | LifetimeName
::Implicit
252 | LifetimeName
::Error
=> Ident
::invalid(),
253 LifetimeName
::Underscore
=> Ident
::with_dummy_span(kw
::UnderscoreLifetime
),
254 LifetimeName
::Static
=> Ident
::with_dummy_span(kw
::StaticLifetime
),
255 LifetimeName
::Param(param_name
) => param_name
.ident(),
259 pub fn is_elided(&self) -> bool
{
261 LifetimeName
::ImplicitObjectLifetimeDefault
262 | LifetimeName
::Implicit
263 | LifetimeName
::Underscore
=> true,
265 // It might seem surprising that `Fresh(_)` counts as
266 // *not* elided -- but this is because, as far as the code
267 // in the compiler is concerned -- `Fresh(_)` variants act
268 // equivalently to "some fresh name". They correspond to
269 // early-bound regions on an impl, in other words.
270 LifetimeName
::Error
| LifetimeName
::Param(_
) | LifetimeName
::Static
=> false,
274 fn is_static(&self) -> bool
{
275 self == &LifetimeName
::Static
278 pub fn modern(&self) -> LifetimeName
{
280 LifetimeName
::Param(param_name
) => LifetimeName
::Param(param_name
.modern()),
281 lifetime_name
=> lifetime_name
,
286 impl fmt
::Display
for Lifetime
{
287 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
288 self.name
.ident().fmt(f
)
292 impl fmt
::Debug
for Lifetime
{
293 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
297 print
::to_string(print
::NO_ANN
, |s
| s
.print_lifetime(self)))
302 pub fn is_elided(&self) -> bool
{
303 self.name
.is_elided()
306 pub fn is_static(&self) -> bool
{
307 self.name
.is_static()
311 /// A `Path` is essentially Rust's notion of a name; for instance,
312 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
313 /// along with a bunch of supporting information.
314 #[derive(RustcEncodable, RustcDecodable, HashStable)]
317 /// The resolution for the path.
319 /// The segments in the path: the things separated by `::`.
320 pub segments
: HirVec
<PathSegment
>,
324 pub fn is_global(&self) -> bool
{
325 !self.segments
.is_empty() && self.segments
[0].ident
.name
== kw
::PathRoot
329 impl fmt
::Debug
for Path
{
330 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
331 write
!(f
, "path({})", self)
335 impl fmt
::Display
for Path
{
336 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
337 write
!(f
, "{}", print
::to_string(print
::NO_ANN
, |s
| s
.print_path(self, false)))
341 /// A segment of a path: an identifier, an optional lifetime, and a set of
343 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
344 pub struct PathSegment
{
345 /// The identifier portion of this path segment.
346 #[stable_hasher(project(name))]
348 // `id` and `res` are optional. We currently only use these in save-analysis,
349 // any path segments without these will not have save-analysis info and
350 // therefore will not have 'jump to def' in IDEs, but otherwise will not be
351 // affected. (In general, we don't bother to get the defs for synthesized
352 // segments, only for segments which have come from the AST).
353 pub hir_id
: Option
<HirId
>,
354 pub res
: Option
<Res
>,
356 /// Type/lifetime parameters attached to this path. They come in
357 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
358 /// this is more than just simple syntactic sugar; the use of
359 /// parens affects the region binding rules, so we preserve the
361 pub args
: Option
<P
<GenericArgs
>>,
363 /// Whether to infer remaining type parameters, if any.
364 /// This only applies to expression and pattern paths, and
365 /// out of those only the segments with no type parameters
366 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
367 pub infer_args
: bool
,
371 /// Converts an identifier to the corresponding segment.
372 pub fn from_ident(ident
: Ident
) -> PathSegment
{
384 hir_id
: Option
<HirId
>,
394 args
: if args
.is_empty() {
402 pub fn generic_args(&self) -> &GenericArgs
{
403 if let Some(ref args
) = self.args
{
406 const DUMMY
: &GenericArgs
= &GenericArgs
::none();
412 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
413 pub struct ConstArg
{
414 pub value
: AnonConst
,
418 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
419 pub enum GenericArg
{
426 pub fn span(&self) -> Span
{
428 GenericArg
::Lifetime(l
) => l
.span
,
429 GenericArg
::Type(t
) => t
.span
,
430 GenericArg
::Const(c
) => c
.span
,
434 pub fn id(&self) -> HirId
{
436 GenericArg
::Lifetime(l
) => l
.hir_id
,
437 GenericArg
::Type(t
) => t
.hir_id
,
438 GenericArg
::Const(c
) => c
.value
.hir_id
,
442 pub fn is_const(&self) -> bool
{
444 GenericArg
::Const(_
) => true,
450 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
451 pub struct GenericArgs
{
452 /// The generic arguments for this path segment.
453 pub args
: HirVec
<GenericArg
>,
454 /// Bindings (equality constraints) on associated types, if present.
455 /// E.g., `Foo<A = Bar>`.
456 pub bindings
: HirVec
<TypeBinding
>,
457 /// Were arguments written in parenthesized form `Fn(T) -> U`?
458 /// This is required mostly for pretty-printing and diagnostics,
459 /// but also for changing lifetime elision rules to be "function-like".
460 pub parenthesized
: bool
,
464 pub const fn none() -> Self {
467 bindings
: HirVec
::new(),
468 parenthesized
: false,
472 pub fn is_empty(&self) -> bool
{
473 self.args
.is_empty() && self.bindings
.is_empty() && !self.parenthesized
476 pub fn inputs(&self) -> &[Ty
] {
477 if self.parenthesized
{
478 for arg
in &self.args
{
480 GenericArg
::Lifetime(_
) => {}
481 GenericArg
::Type(ref ty
) => {
482 if let TyKind
::Tup(ref tys
) = ty
.kind
{
487 GenericArg
::Const(_
) => {}
491 bug
!("GenericArgs::inputs: not a `Fn(T) -> U`");
494 pub fn own_counts(&self) -> GenericParamCount
{
495 // We could cache this as a property of `GenericParamCount`, but
496 // the aim is to refactor this away entirely eventually and the
497 // presence of this method will be a constant reminder.
498 let mut own_counts
: GenericParamCount
= Default
::default();
500 for arg
in &self.args
{
502 GenericArg
::Lifetime(_
) => own_counts
.lifetimes
+= 1,
503 GenericArg
::Type(_
) => own_counts
.types
+= 1,
504 GenericArg
::Const(_
) => own_counts
.consts
+= 1,
512 /// A modifier on a bound, currently this is only used for `?Sized`, where the
513 /// modifier is `Maybe`. Negative bounds should also be handled here.
514 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
515 pub enum TraitBoundModifier
{
520 /// The AST represents all type param bounds as types.
521 /// `typeck::collect::compute_bounds` matches these against
522 /// the "special" built-in traits (see `middle::lang_items`) and
523 /// detects `Copy`, `Send` and `Sync`.
524 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
525 pub enum GenericBound
{
526 Trait(PolyTraitRef
, TraitBoundModifier
),
531 pub fn span(&self) -> Span
{
533 &GenericBound
::Trait(ref t
, ..) => t
.span
,
534 &GenericBound
::Outlives(ref l
) => l
.span
,
539 pub type GenericBounds
= HirVec
<GenericBound
>;
541 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable)]
542 pub enum LifetimeParamKind
{
543 // Indicates that the lifetime definition was explicitly declared (e.g., in
544 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
547 // Indicates that the lifetime definition was synthetically added
548 // as a result of an in-band lifetime usage (e.g., in
549 // `fn foo(x: &'a u8) -> &'a u8 { x }`).
552 // Indication that the lifetime was elided (e.g., in both cases in
553 // `fn foo(x: &u8) -> &'_ u8 { x }`).
556 // Indication that the lifetime name was somehow in error.
560 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
561 pub enum GenericParamKind
{
562 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
564 kind
: LifetimeParamKind
,
567 default: Option
<P
<Ty
>>,
568 synthetic
: Option
<SyntheticTyParamKind
>,
575 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
576 pub struct GenericParam
{
579 pub attrs
: HirVec
<Attribute
>,
580 pub bounds
: GenericBounds
,
582 pub pure_wrt_drop
: bool
,
583 pub kind
: GenericParamKind
,
587 pub struct GenericParamCount
{
588 pub lifetimes
: usize,
593 /// Represents lifetimes and type parameters attached to a declaration
594 /// of a function, enum, trait, etc.
595 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
596 pub struct Generics
{
597 pub params
: HirVec
<GenericParam
>,
598 pub where_clause
: WhereClause
,
603 pub const fn empty() -> Generics
{
605 params
: HirVec
::new(),
606 where_clause
: WhereClause
{
607 predicates
: HirVec
::new(),
614 pub fn own_counts(&self) -> GenericParamCount
{
615 // We could cache this as a property of `GenericParamCount`, but
616 // the aim is to refactor this away entirely eventually and the
617 // presence of this method will be a constant reminder.
618 let mut own_counts
: GenericParamCount
= Default
::default();
620 for param
in &self.params
{
622 GenericParamKind
::Lifetime { .. }
=> own_counts
.lifetimes
+= 1,
623 GenericParamKind
::Type { .. }
=> own_counts
.types
+= 1,
624 GenericParamKind
::Const { .. }
=> own_counts
.consts
+= 1,
631 pub fn get_named(&self, name
: Symbol
) -> Option
<&GenericParam
> {
632 for param
in &self.params
{
633 if name
== param
.name
.ident().name
{
640 pub fn spans(&self) -> MultiSpan
{
641 if self.params
.is_empty() {
644 self.params
.iter().map(|p
| p
.span
).collect
::<Vec
<Span
>>().into()
649 /// Synthetic type parameters are converted to another form during lowering; this allows
650 /// us to track the original form they had, and is useful for error messages.
651 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
652 pub enum SyntheticTyParamKind
{
656 /// A where-clause in a definition.
657 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
658 pub struct WhereClause
{
659 pub predicates
: HirVec
<WherePredicate
>,
660 // Only valid if predicates isn't empty.
665 pub fn span(&self) -> Option
<Span
> {
666 if self.predicates
.is_empty() {
673 /// The `WhereClause` under normal circumstances points at either the predicates or the empty
674 /// space where the `where` clause should be. Only of use for diagnostic suggestions.
675 pub fn span_for_predicates_or_empty_place(&self) -> Span
{
680 /// A single predicate in a where-clause.
681 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
682 pub enum WherePredicate
{
683 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
684 BoundPredicate(WhereBoundPredicate
),
685 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
686 RegionPredicate(WhereRegionPredicate
),
687 /// An equality predicate (unsupported).
688 EqPredicate(WhereEqPredicate
),
691 impl WherePredicate
{
692 pub fn span(&self) -> Span
{
694 &WherePredicate
::BoundPredicate(ref p
) => p
.span
,
695 &WherePredicate
::RegionPredicate(ref p
) => p
.span
,
696 &WherePredicate
::EqPredicate(ref p
) => p
.span
,
701 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
702 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
703 pub struct WhereBoundPredicate
{
705 /// Any generics from a `for` binding.
706 pub bound_generic_params
: HirVec
<GenericParam
>,
707 /// The type being bounded.
708 pub bounded_ty
: P
<Ty
>,
709 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
710 pub bounds
: GenericBounds
,
713 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
714 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
715 pub struct WhereRegionPredicate
{
717 pub lifetime
: Lifetime
,
718 pub bounds
: GenericBounds
,
721 /// An equality predicate (e.g., `T = int`); currently unsupported.
722 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
723 pub struct WhereEqPredicate
{
730 #[derive(RustcEncodable, RustcDecodable, Debug)]
731 pub struct ModuleItems
{
732 // Use BTreeSets here so items are in the same order as in the
733 // list of all items in Crate
734 pub items
: BTreeSet
<HirId
>,
735 pub trait_items
: BTreeSet
<TraitItemId
>,
736 pub impl_items
: BTreeSet
<ImplItemId
>,
739 /// The top-level data structure that stores the entire contents of
740 /// the crate currently being compiled.
742 /// For more details, see the [rustc guide].
744 /// [rustc guide]: https://rust-lang.github.io/rustc-guide/hir.html
745 #[derive(RustcEncodable, RustcDecodable, Debug)]
748 pub attrs
: HirVec
<Attribute
>,
750 pub exported_macros
: HirVec
<MacroDef
>,
751 // Attributes from non-exported macros, kept only for collecting the library feature list.
752 pub non_exported_macro_attrs
: HirVec
<Attribute
>,
754 // N.B., we use a `BTreeMap` here so that `visit_all_items` iterates
755 // over the ids in increasing order. In principle it should not
756 // matter what order we visit things in, but in *practice* it
757 // does, because it can affect the order in which errors are
758 // detected, which in turn can make compile-fail tests yield
759 // slightly different results.
760 pub items
: BTreeMap
<HirId
, Item
>,
762 pub trait_items
: BTreeMap
<TraitItemId
, TraitItem
>,
763 pub impl_items
: BTreeMap
<ImplItemId
, ImplItem
>,
764 pub bodies
: BTreeMap
<BodyId
, Body
>,
765 pub trait_impls
: BTreeMap
<DefId
, Vec
<HirId
>>,
767 /// A list of the body ids written out in the order in which they
768 /// appear in the crate. If you're going to process all the bodies
769 /// in the crate, you should iterate over this list rather than the keys
771 pub body_ids
: Vec
<BodyId
>,
773 /// A list of modules written out in the order in which they
774 /// appear in the crate. This includes the main crate module.
775 pub modules
: BTreeMap
<HirId
, ModuleItems
>,
779 pub fn item(&self, id
: HirId
) -> &Item
{
783 pub fn trait_item(&self, id
: TraitItemId
) -> &TraitItem
{
784 &self.trait_items
[&id
]
787 pub fn impl_item(&self, id
: ImplItemId
) -> &ImplItem
{
788 &self.impl_items
[&id
]
791 /// Visits all items in the crate in some deterministic (but
792 /// unspecified) order. If you just need to process every item,
793 /// but don't care about nesting, this method is the best choice.
795 /// If you do care about nesting -- usually because your algorithm
796 /// follows lexical scoping rules -- then you want a different
797 /// approach. You should override `visit_nested_item` in your
798 /// visitor and then call `intravisit::walk_crate` instead.
799 pub fn visit_all_item_likes
<'hir
, V
>(&'hir
self, visitor
: &mut V
)
800 where V
: itemlikevisit
::ItemLikeVisitor
<'hir
>
802 for (_
, item
) in &self.items
{
803 visitor
.visit_item(item
);
806 for (_
, trait_item
) in &self.trait_items
{
807 visitor
.visit_trait_item(trait_item
);
810 for (_
, impl_item
) in &self.impl_items
{
811 visitor
.visit_impl_item(impl_item
);
815 /// A parallel version of `visit_all_item_likes`.
816 pub fn par_visit_all_item_likes
<'hir
, V
>(&'hir
self, visitor
: &V
)
817 where V
: itemlikevisit
::ParItemLikeVisitor
<'hir
> + Sync
+ Send
820 par_for_each_in(&self.items
, |(_
, item
)| {
821 visitor
.visit_item(item
);
824 par_for_each_in(&self.trait_items
, |(_
, trait_item
)| {
825 visitor
.visit_trait_item(trait_item
);
828 par_for_each_in(&self.impl_items
, |(_
, impl_item
)| {
829 visitor
.visit_impl_item(impl_item
);
834 pub fn body(&self, id
: BodyId
) -> &Body
{
839 /// A macro definition, in this crate or imported from another.
841 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
842 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
843 pub struct MacroDef
{
846 pub attrs
: HirVec
<Attribute
>,
849 pub body
: TokenStream
,
853 /// A block of statements `{ .. }`, which may have a label (in this case the
854 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
855 /// the `rules` being anything but `DefaultBlock`.
856 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
858 /// Statements in a block.
859 pub stmts
: HirVec
<Stmt
>,
860 /// An expression at the end of the block
861 /// without a semicolon, if any.
862 pub expr
: Option
<P
<Expr
>>,
863 #[stable_hasher(ignore)]
865 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
866 pub rules
: BlockCheckMode
,
868 /// If true, then there may exist `break 'a` values that aim to
869 /// break out of this block early.
870 /// Used by `'label: {}` blocks and by `try {}` blocks.
871 pub targeted_by_break
: bool
,
874 #[derive(RustcEncodable, RustcDecodable, HashStable)]
876 #[stable_hasher(ignore)]
882 impl fmt
::Debug
for Pat
{
883 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
884 write
!(f
, "pat({}: {})", self.hir_id
,
885 print
::to_string(print
::NO_ANN
, |s
| s
.print_pat(self)))
890 // FIXME(#19596) this is a workaround, but there should be a better way
891 fn walk_short_(&self, it
: &mut impl FnMut(&Pat
) -> bool
) -> bool
{
898 Wild
| Lit(_
) | Range(..) | Binding(.., None
) | Path(_
) => true,
899 Box(s
) | Ref(s
, _
) | Binding(.., Some(s
)) => s
.walk_short_(it
),
900 Struct(_
, fields
, _
) => fields
.iter().all(|field
| field
.pat
.walk_short_(it
)),
901 TupleStruct(_
, s
, _
) | Tuple(s
, _
) | Or(s
) => s
.iter().all(|p
| p
.walk_short_(it
)),
902 Slice(before
, slice
, after
) => {
906 .all(|p
| p
.walk_short_(it
))
911 /// Walk the pattern in left-to-right order,
912 /// short circuiting (with `.all(..)`) if `false` is returned.
914 /// Note that when visiting e.g. `Tuple(ps)`,
915 /// if visiting `ps[0]` returns `false`,
916 /// then `ps[1]` will not be visited.
917 pub fn walk_short(&self, mut it
: impl FnMut(&Pat
) -> bool
) -> bool
{
918 self.walk_short_(&mut it
)
921 // FIXME(#19596) this is a workaround, but there should be a better way
922 fn walk_(&self, it
: &mut impl FnMut(&Pat
) -> bool
) {
929 Wild
| Lit(_
) | Range(..) | Binding(.., None
) | Path(_
) => {}
,
930 Box(s
) | Ref(s
, _
) | Binding(.., Some(s
)) => s
.walk_(it
),
931 Struct(_
, fields
, _
) => fields
.iter().for_each(|field
| field
.pat
.walk_(it
)),
932 TupleStruct(_
, s
, _
) | Tuple(s
, _
) | Or(s
) => s
.iter().for_each(|p
| p
.walk_(it
)),
933 Slice(before
, slice
, after
) => {
937 .for_each(|p
| p
.walk_(it
))
942 /// Walk the pattern in left-to-right order.
944 /// If `it(pat)` returns `false`, the children are not visited.
945 pub fn walk(&self, mut it
: impl FnMut(&Pat
) -> bool
) {
950 /// A single field in a struct pattern.
952 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
953 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
954 /// except `is_shorthand` is true.
955 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
956 pub struct FieldPat
{
957 #[stable_hasher(ignore)]
959 /// The identifier for the field.
960 #[stable_hasher(project(name))]
962 /// The pattern the field is destructured to.
964 pub is_shorthand
: bool
,
968 /// Explicit binding annotations given in the HIR for a binding. Note
969 /// that this is not the final binding *mode* that we infer after type
971 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
972 pub enum BindingAnnotation
{
973 /// No binding annotation given: this means that the final binding mode
974 /// will depend on whether we have skipped through a `&` reference
975 /// when matching. For example, the `x` in `Some(x)` will have binding
976 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
977 /// ultimately be inferred to be by-reference.
979 /// Note that implicit reference skipping is not implemented yet (#42640).
982 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
985 /// Annotated as `ref`, like `ref x`
988 /// Annotated as `ref mut x`.
992 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
998 impl fmt
::Display
for RangeEnd
{
999 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1000 f
.write_str(match self {
1001 RangeEnd
::Included
=> "..=",
1002 RangeEnd
::Excluded
=> "..",
1007 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1009 /// Represents a wildcard pattern (i.e., `_`).
1012 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
1013 /// The `HirId` is the canonical ID for the variable being bound,
1014 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
1015 /// which is the pattern ID of the first `x`.
1016 Binding(BindingAnnotation
, HirId
, Ident
, Option
<P
<Pat
>>),
1018 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
1019 /// The `bool` is `true` in the presence of a `..`.
1020 Struct(QPath
, HirVec
<FieldPat
>, bool
),
1022 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
1023 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
1024 /// `0 <= position <= subpats.len()`
1025 TupleStruct(QPath
, HirVec
<P
<Pat
>>, Option
<usize>),
1027 /// An or-pattern `A | B | C`.
1028 /// Invariant: `pats.len() >= 2`.
1031 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
1034 /// A tuple pattern (e.g., `(a, b)`).
1035 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
1036 /// `0 <= position <= subpats.len()`
1037 Tuple(HirVec
<P
<Pat
>>, Option
<usize>),
1039 /// A `box` pattern.
1042 /// A reference pattern (e.g., `&mut (a, b)`).
1043 Ref(P
<Pat
>, Mutability
),
1048 /// A range pattern (e.g., `1..=2` or `1..2`).
1049 Range(P
<Expr
>, P
<Expr
>, RangeEnd
),
1051 /// `[a, b, ..i, y, z]` is represented as:
1052 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`.
1053 Slice(HirVec
<P
<Pat
>>, Option
<P
<Pat
>>, HirVec
<P
<Pat
>>),
1056 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, HashStable,
1057 RustcEncodable
, RustcDecodable
, Hash
, Debug
)]
1058 pub enum Mutability
{
1064 /// Returns `MutMutable` only if both `self` and `other` are mutable.
1065 pub fn and(self, other
: Self) -> Self {
1067 MutMutable
=> other
,
1068 MutImmutable
=> MutImmutable
,
1072 pub fn invert(self) -> Self {
1074 MutMutable
=> MutImmutable
,
1075 MutImmutable
=> MutMutable
,
1080 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1081 pub enum BinOpKind
{
1082 /// The `+` operator (addition).
1084 /// The `-` operator (subtraction).
1086 /// The `*` operator (multiplication).
1088 /// The `/` operator (division).
1090 /// The `%` operator (modulus).
1092 /// The `&&` operator (logical and).
1094 /// The `||` operator (logical or).
1096 /// The `^` operator (bitwise xor).
1098 /// The `&` operator (bitwise and).
1100 /// The `|` operator (bitwise or).
1102 /// The `<<` operator (shift left).
1104 /// The `>>` operator (shift right).
1106 /// The `==` operator (equality).
1108 /// The `<` operator (less than).
1110 /// The `<=` operator (less than or equal to).
1112 /// The `!=` operator (not equal to).
1114 /// The `>=` operator (greater than or equal to).
1116 /// The `>` operator (greater than).
1121 pub fn as_str(self) -> &'
static str {
1123 BinOpKind
::Add
=> "+",
1124 BinOpKind
::Sub
=> "-",
1125 BinOpKind
::Mul
=> "*",
1126 BinOpKind
::Div
=> "/",
1127 BinOpKind
::Rem
=> "%",
1128 BinOpKind
::And
=> "&&",
1129 BinOpKind
::Or
=> "||",
1130 BinOpKind
::BitXor
=> "^",
1131 BinOpKind
::BitAnd
=> "&",
1132 BinOpKind
::BitOr
=> "|",
1133 BinOpKind
::Shl
=> "<<",
1134 BinOpKind
::Shr
=> ">>",
1135 BinOpKind
::Eq
=> "==",
1136 BinOpKind
::Lt
=> "<",
1137 BinOpKind
::Le
=> "<=",
1138 BinOpKind
::Ne
=> "!=",
1139 BinOpKind
::Ge
=> ">=",
1140 BinOpKind
::Gt
=> ">",
1144 pub fn is_lazy(self) -> bool
{
1146 BinOpKind
::And
| BinOpKind
::Or
=> true,
1151 pub fn is_shift(self) -> bool
{
1153 BinOpKind
::Shl
| BinOpKind
::Shr
=> true,
1158 pub fn is_comparison(self) -> bool
{
1165 BinOpKind
::Ge
=> true,
1177 BinOpKind
::Shr
=> false,
1181 /// Returns `true` if the binary operator takes its arguments by value.
1182 pub fn is_by_value(self) -> bool
{
1183 !self.is_comparison()
1187 impl Into
<ast
::BinOpKind
> for BinOpKind
{
1188 fn into(self) -> ast
::BinOpKind
{
1190 BinOpKind
::Add
=> ast
::BinOpKind
::Add
,
1191 BinOpKind
::Sub
=> ast
::BinOpKind
::Sub
,
1192 BinOpKind
::Mul
=> ast
::BinOpKind
::Mul
,
1193 BinOpKind
::Div
=> ast
::BinOpKind
::Div
,
1194 BinOpKind
::Rem
=> ast
::BinOpKind
::Rem
,
1195 BinOpKind
::And
=> ast
::BinOpKind
::And
,
1196 BinOpKind
::Or
=> ast
::BinOpKind
::Or
,
1197 BinOpKind
::BitXor
=> ast
::BinOpKind
::BitXor
,
1198 BinOpKind
::BitAnd
=> ast
::BinOpKind
::BitAnd
,
1199 BinOpKind
::BitOr
=> ast
::BinOpKind
::BitOr
,
1200 BinOpKind
::Shl
=> ast
::BinOpKind
::Shl
,
1201 BinOpKind
::Shr
=> ast
::BinOpKind
::Shr
,
1202 BinOpKind
::Eq
=> ast
::BinOpKind
::Eq
,
1203 BinOpKind
::Lt
=> ast
::BinOpKind
::Lt
,
1204 BinOpKind
::Le
=> ast
::BinOpKind
::Le
,
1205 BinOpKind
::Ne
=> ast
::BinOpKind
::Ne
,
1206 BinOpKind
::Ge
=> ast
::BinOpKind
::Ge
,
1207 BinOpKind
::Gt
=> ast
::BinOpKind
::Gt
,
1212 pub type BinOp
= Spanned
<BinOpKind
>;
1214 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1216 /// The `*` operator (deferencing).
1218 /// The `!` operator (logical negation).
1220 /// The `-` operator (negation).
1225 pub fn as_str(self) -> &'
static str {
1233 /// Returns `true` if the unary operator takes its argument by value.
1234 pub fn is_by_value(self) -> bool
{
1236 UnNeg
| UnNot
=> true,
1243 #[derive(RustcEncodable, RustcDecodable)]
1250 impl fmt
::Debug
for Stmt
{
1251 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1252 write
!(f
, "stmt({}: {})", self.hir_id
,
1253 print
::to_string(print
::NO_ANN
, |s
| s
.print_stmt(self)))
1257 /// The contents of a statement.
1258 #[derive(RustcEncodable, RustcDecodable, HashStable)]
1260 /// A local (`let`) binding.
1263 /// An item binding.
1266 /// An expression without a trailing semi-colon (must have unit type).
1269 /// An expression with a trailing semi-colon (may have any type).
1274 pub fn attrs(&self) -> &[Attribute
] {
1276 StmtKind
::Local(ref l
) => &l
.attrs
,
1277 StmtKind
::Item(_
) => &[],
1278 StmtKind
::Expr(ref e
) |
1279 StmtKind
::Semi(ref e
) => &e
.attrs
,
1284 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1285 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1288 /// Type annotation, if any (otherwise the type will be inferred).
1289 pub ty
: Option
<P
<Ty
>>,
1290 /// Initializer expression to set the value, if any.
1291 pub init
: Option
<P
<Expr
>>,
1294 pub attrs
: ThinVec
<Attribute
>,
1295 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1296 /// desugaring. Otherwise will be `Normal`.
1297 pub source
: LocalSource
,
1300 /// Represents a single arm of a `match` expression, e.g.
1301 /// `<pat> (if <guard>) => <body>`.
1302 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1304 #[stable_hasher(ignore)]
1307 pub attrs
: HirVec
<Attribute
>,
1308 /// If this pattern and the optional guard matches, then `body` is evaluated.
1310 /// Optional guard clause.
1311 pub guard
: Option
<Guard
>,
1312 /// The expression the arm evaluates to if this arm matches.
1316 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1321 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1323 #[stable_hasher(ignore)]
1328 pub is_shorthand
: bool
,
1331 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1332 pub enum BlockCheckMode
{
1334 UnsafeBlock(UnsafeSource
),
1335 PushUnsafeBlock(UnsafeSource
),
1336 PopUnsafeBlock(UnsafeSource
),
1339 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1340 pub enum UnsafeSource
{
1345 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1350 /// The body of a function, closure, or constant value. In the case of
1351 /// a function, the body contains not only the function body itself
1352 /// (which is an expression), but also the argument patterns, since
1353 /// those are something that the caller doesn't really care about.
1358 /// fn foo((x, y): (u32, u32)) -> u32 {
1363 /// Here, the `Body` associated with `foo()` would contain:
1365 /// - an `params` array containing the `(x, y)` pattern
1366 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1367 /// - `generator_kind` would be `None`
1369 /// All bodies have an **owner**, which can be accessed via the HIR
1370 /// map using `body_owner_def_id()`.
1371 #[derive(RustcEncodable, RustcDecodable, Debug)]
1373 pub params
: HirVec
<Param
>,
1375 pub generator_kind
: Option
<GeneratorKind
>,
1379 pub fn id(&self) -> BodyId
{
1381 hir_id
: self.value
.hir_id
,
1385 pub fn generator_kind(&self) -> Option
<GeneratorKind
> {
1390 /// The type of source expression that caused this generator to be created.
1391 #[derive(Clone, PartialEq, Eq, HashStable, RustcEncodable, RustcDecodable, Debug, Copy)]
1392 pub enum GeneratorKind
{
1393 /// An explicit `async` block or the body of an async function.
1394 Async(AsyncGeneratorKind
),
1396 /// A generator literal created via a `yield` inside a closure.
1400 impl fmt
::Display
for GeneratorKind
{
1401 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1403 GeneratorKind
::Async(k
) => fmt
::Display
::fmt(k
, f
),
1404 GeneratorKind
::Gen
=> f
.write_str("generator"),
1409 /// In the case of a generator created as part of an async construct,
1410 /// which kind of async construct caused it to be created?
1412 /// This helps error messages but is also used to drive coercions in
1413 /// type-checking (see #60424).
1414 #[derive(Clone, PartialEq, Eq, HashStable, RustcEncodable, RustcDecodable, Debug, Copy)]
1415 pub enum AsyncGeneratorKind
{
1416 /// An explicit `async` block written by the user.
1419 /// An explicit `async` block written by the user.
1422 /// The `async` block generated as the body of an async function.
1426 impl fmt
::Display
for AsyncGeneratorKind
{
1427 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1428 f
.write_str(match self {
1429 AsyncGeneratorKind
::Block
=> "`async` block",
1430 AsyncGeneratorKind
::Closure
=> "`async` closure body",
1431 AsyncGeneratorKind
::Fn
=> "`async fn` body",
1436 #[derive(Copy, Clone, Debug)]
1437 pub enum BodyOwnerKind
{
1438 /// Functions and methods.
1444 /// Constants and associated constants.
1447 /// Initializer of a `static` item.
1451 impl BodyOwnerKind
{
1452 pub fn is_fn_or_closure(self) -> bool
{
1454 BodyOwnerKind
::Fn
| BodyOwnerKind
::Closure
=> true,
1455 BodyOwnerKind
::Const
| BodyOwnerKind
::Static(_
) => false,
1461 pub type Lit
= Spanned
<LitKind
>;
1463 /// A constant (expression) that's not an item or associated item,
1464 /// but needs its own `DefId` for type-checking, const-eval, etc.
1465 /// These are usually found nested inside types (e.g., array lengths)
1466 /// or expressions (e.g., repeat counts), and also used to define
1467 /// explicit discriminant values for enum variants.
1468 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1469 pub struct AnonConst
{
1475 #[derive(RustcEncodable, RustcDecodable)]
1479 pub attrs
: ThinVec
<Attribute
>,
1483 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1484 #[cfg(target_arch = "x86_64")]
1485 static_assert_size
!(Expr
, 72);
1488 pub fn precedence(&self) -> ExprPrecedence
{
1490 ExprKind
::Box(_
) => ExprPrecedence
::Box
,
1491 ExprKind
::Array(_
) => ExprPrecedence
::Array
,
1492 ExprKind
::Call(..) => ExprPrecedence
::Call
,
1493 ExprKind
::MethodCall(..) => ExprPrecedence
::MethodCall
,
1494 ExprKind
::Tup(_
) => ExprPrecedence
::Tup
,
1495 ExprKind
::Binary(op
, ..) => ExprPrecedence
::Binary(op
.node
.into()),
1496 ExprKind
::Unary(..) => ExprPrecedence
::Unary
,
1497 ExprKind
::Lit(_
) => ExprPrecedence
::Lit
,
1498 ExprKind
::Type(..) | ExprKind
::Cast(..) => ExprPrecedence
::Cast
,
1499 ExprKind
::DropTemps(ref expr
, ..) => expr
.precedence(),
1500 ExprKind
::Loop(..) => ExprPrecedence
::Loop
,
1501 ExprKind
::Match(..) => ExprPrecedence
::Match
,
1502 ExprKind
::Closure(..) => ExprPrecedence
::Closure
,
1503 ExprKind
::Block(..) => ExprPrecedence
::Block
,
1504 ExprKind
::Assign(..) => ExprPrecedence
::Assign
,
1505 ExprKind
::AssignOp(..) => ExprPrecedence
::AssignOp
,
1506 ExprKind
::Field(..) => ExprPrecedence
::Field
,
1507 ExprKind
::Index(..) => ExprPrecedence
::Index
,
1508 ExprKind
::Path(..) => ExprPrecedence
::Path
,
1509 ExprKind
::AddrOf(..) => ExprPrecedence
::AddrOf
,
1510 ExprKind
::Break(..) => ExprPrecedence
::Break
,
1511 ExprKind
::Continue(..) => ExprPrecedence
::Continue
,
1512 ExprKind
::Ret(..) => ExprPrecedence
::Ret
,
1513 ExprKind
::InlineAsm(..) => ExprPrecedence
::InlineAsm
,
1514 ExprKind
::Struct(..) => ExprPrecedence
::Struct
,
1515 ExprKind
::Repeat(..) => ExprPrecedence
::Repeat
,
1516 ExprKind
::Yield(..) => ExprPrecedence
::Yield
,
1517 ExprKind
::Err
=> ExprPrecedence
::Err
,
1521 pub fn is_place_expr(&self) -> bool
{
1523 ExprKind
::Path(QPath
::Resolved(_
, ref path
)) => {
1526 | Res
::Def(DefKind
::Static
, _
)
1532 ExprKind
::Type(ref e
, _
) => {
1536 ExprKind
::Unary(UnDeref
, _
) |
1537 ExprKind
::Field(..) |
1538 ExprKind
::Index(..) => {
1542 // Partially qualified paths in expressions can only legally
1543 // refer to associated items which are always rvalues.
1544 ExprKind
::Path(QPath
::TypeRelative(..)) |
1546 ExprKind
::Call(..) |
1547 ExprKind
::MethodCall(..) |
1548 ExprKind
::Struct(..) |
1550 ExprKind
::Match(..) |
1551 ExprKind
::Closure(..) |
1552 ExprKind
::Block(..) |
1553 ExprKind
::Repeat(..) |
1554 ExprKind
::Array(..) |
1555 ExprKind
::Break(..) |
1556 ExprKind
::Continue(..) |
1558 ExprKind
::Loop(..) |
1559 ExprKind
::Assign(..) |
1560 ExprKind
::InlineAsm(..) |
1561 ExprKind
::AssignOp(..) |
1563 ExprKind
::Unary(..) |
1565 ExprKind
::AddrOf(..) |
1566 ExprKind
::Binary(..) |
1567 ExprKind
::Yield(..) |
1568 ExprKind
::Cast(..) |
1569 ExprKind
::DropTemps(..) |
1576 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1577 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1578 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1579 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1580 /// beyond remembering to call this function before doing analysis on it.
1581 pub fn peel_drop_temps(&self) -> &Self {
1582 let mut expr
= self;
1583 while let ExprKind
::DropTemps(inner
) = &expr
.kind
{
1590 impl fmt
::Debug
for Expr
{
1591 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1592 write
!(f
, "expr({}: {})", self.hir_id
,
1593 print
::to_string(print
::NO_ANN
, |s
| s
.print_expr(self)))
1597 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1599 /// A `box x` expression.
1601 /// An array (e.g., `[a, b, c, d]`).
1602 Array(HirVec
<Expr
>),
1603 /// A function call.
1605 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1606 /// and the second field is the list of arguments.
1607 /// This also represents calling the constructor of
1608 /// tuple-like ADTs such as tuple structs and enum variants.
1609 Call(P
<Expr
>, HirVec
<Expr
>),
1610 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1612 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1613 /// (within the angle brackets).
1614 /// The first element of the vector of `Expr`s is the expression that evaluates
1615 /// to the object on which the method is being called on (the receiver),
1616 /// and the remaining elements are the rest of the arguments.
1617 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1618 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1619 MethodCall(P
<PathSegment
>, Span
, HirVec
<Expr
>),
1620 /// A tuple (e.g., `(a, b, c, d)`).
1622 /// A binary operation (e.g., `a + b`, `a * b`).
1623 Binary(BinOp
, P
<Expr
>, P
<Expr
>),
1624 /// A unary operation (e.g., `!x`, `*x`).
1625 Unary(UnOp
, P
<Expr
>),
1626 /// A literal (e.g., `1`, `"foo"`).
1628 /// A cast (e.g., `foo as f64`).
1629 Cast(P
<Expr
>, P
<Ty
>),
1630 /// A type reference (e.g., `Foo`).
1631 Type(P
<Expr
>, P
<Ty
>),
1632 /// Wraps the expression in a terminating scope.
1633 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1635 /// This construct only exists to tweak the drop order in HIR lowering.
1636 /// An example of that is the desugaring of `for` loops.
1638 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1640 /// I.e., `'label: loop { <block> }`.
1641 Loop(P
<Block
>, Option
<Label
>, LoopSource
),
1642 /// A `match` block, with a source that indicates whether or not it is
1643 /// the result of a desugaring, and if so, which kind.
1644 Match(P
<Expr
>, HirVec
<Arm
>, MatchSource
),
1645 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1647 /// The `Span` is the argument block `|...|`.
1649 /// This may also be a generator literal or an `async block` as indicated by the
1650 /// `Option<GeneratorMovability>`.
1651 Closure(CaptureClause
, P
<FnDecl
>, BodyId
, Span
, Option
<GeneratorMovability
>),
1652 /// A block (e.g., `'label: { ... }`).
1653 Block(P
<Block
>, Option
<Label
>),
1655 /// An assignment (e.g., `a = foo()`).
1656 Assign(P
<Expr
>, P
<Expr
>),
1657 /// An assignment with an operator.
1660 AssignOp(BinOp
, P
<Expr
>, P
<Expr
>),
1661 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1662 Field(P
<Expr
>, Ident
),
1663 /// An indexing operation (`foo[2]`).
1664 Index(P
<Expr
>, P
<Expr
>),
1666 /// Path to a definition, possibly containing lifetime or type parameters.
1669 /// A referencing operation (i.e., `&a` or `&mut a`).
1670 AddrOf(Mutability
, P
<Expr
>),
1671 /// A `break`, with an optional label to break.
1672 Break(Destination
, Option
<P
<Expr
>>),
1673 /// A `continue`, with an optional label.
1674 Continue(Destination
),
1675 /// A `return`, with an optional value to be returned.
1676 Ret(Option
<P
<Expr
>>),
1678 /// Inline assembly (from `asm!`), with its outputs and inputs.
1679 InlineAsm(P
<InlineAsm
>, HirVec
<Expr
>, HirVec
<Expr
>),
1681 /// A struct or struct-like variant literal expression.
1683 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1684 /// where `base` is the `Option<Expr>`.
1685 Struct(P
<QPath
>, HirVec
<Field
>, Option
<P
<Expr
>>),
1687 /// An array literal constructed from one repeated element.
1689 /// E.g., `[1; 5]`. The first expression is the element
1690 /// to be repeated; the second is the number of times to repeat it.
1691 Repeat(P
<Expr
>, AnonConst
),
1693 /// A suspension point for generators (i.e., `yield <expr>`).
1694 Yield(P
<Expr
>, YieldSource
),
1696 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1700 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1701 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1703 /// Path to a definition, optionally "fully-qualified" with a `Self`
1704 /// type, if the path points to an associated item in a trait.
1706 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1707 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1708 /// even though they both have the same two-segment `Clone::clone` `Path`.
1709 Resolved(Option
<P
<Ty
>>, P
<Path
>),
1711 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1712 /// Will be resolved by type-checking to an associated item.
1714 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1715 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1716 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1717 TypeRelative(P
<Ty
>, P
<PathSegment
>)
1720 /// Hints at the original code for a let statement.
1721 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1722 pub enum LocalSource
{
1723 /// A `match _ { .. }`.
1725 /// A desugared `for _ in _ { .. }` loop.
1727 /// When lowering async functions, we create locals within the `async move` so that
1728 /// all parameters are dropped after the future is polled.
1730 /// ```ignore (pseudo-Rust)
1731 /// async fn foo(<pattern> @ x: Type) {
1733 /// let <pattern> = x;
1738 /// A desugared `<expr>.await`.
1742 /// Hints at the original code for a `match _ { .. }`.
1743 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
1744 pub enum MatchSource
{
1745 /// A `match _ { .. }`.
1747 /// An `if _ { .. }` (optionally with `else { .. }`).
1749 contains_else_clause
: bool
,
1751 /// An `if let _ = _ { .. }` (optionally with `else { .. }`).
1753 contains_else_clause
: bool
,
1755 /// A `while _ { .. }` (which was desugared to a `loop { match _ { .. } }`).
1757 /// A `while let _ = _ { .. }` (which was desugared to a
1758 /// `loop { match _ { .. } }`).
1760 /// A desugared `for _ in _ { .. }` loop.
1762 /// A desugared `?` operator.
1764 /// A desugared `<expr>.await`.
1768 /// The loop type that yielded an `ExprKind::Loop`.
1769 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1770 pub enum LoopSource
{
1771 /// A `loop { .. }` loop.
1773 /// A `while _ { .. }` loop.
1775 /// A `while let _ = _ { .. }` loop.
1777 /// A `for _ in _ { .. }` loop.
1782 pub fn name(self) -> &'
static str {
1784 LoopSource
::Loop
=> "loop",
1785 LoopSource
::While
=> "while",
1786 LoopSource
::WhileLet
=> "while let",
1787 LoopSource
::ForLoop
=> "for",
1792 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1793 pub enum LoopIdError
{
1795 UnlabeledCfInWhileCondition
,
1799 impl fmt
::Display
for LoopIdError
{
1800 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1801 f
.write_str(match self {
1802 LoopIdError
::OutsideLoopScope
=> "not inside loop scope",
1803 LoopIdError
::UnlabeledCfInWhileCondition
=>
1804 "unlabeled control flow (break or continue) in while condition",
1805 LoopIdError
::UnresolvedLabel
=> "label not found",
1810 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1811 pub struct Destination
{
1812 // This is `Some(_)` iff there is an explicit user-specified `label
1813 pub label
: Option
<Label
>,
1815 // These errors are caught and then reported during the diagnostics pass in
1816 // librustc_passes/loops.rs
1817 pub target_id
: Result
<HirId
, LoopIdError
>,
1820 /// Whether a generator contains self-references, causing it to be `!Unpin`.
1821 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, HashStable,
1822 RustcEncodable
, RustcDecodable
, Hash
, Debug
)]
1823 pub enum GeneratorMovability
{
1824 /// May contain self-references, `!Unpin`.
1827 /// Must not contain self-references, `Unpin`.
1831 /// The yield kind that caused an `ExprKind::Yield`.
1832 #[derive(Copy, Clone, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable, HashStable)]
1833 pub enum YieldSource
{
1834 /// An `<expr>.await`.
1836 /// A plain `yield`.
1840 impl fmt
::Display
for YieldSource
{
1841 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1842 f
.write_str(match self {
1843 YieldSource
::Await
=> "`await`",
1844 YieldSource
::Yield
=> "`yield`",
1849 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1850 pub enum CaptureClause
{
1855 // N.B., if you change this, you'll probably want to change the corresponding
1856 // type structure in middle/ty.rs as well.
1857 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1860 pub mutbl
: Mutability
,
1863 /// Represents a method's signature in a trait declaration or implementation.
1864 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1865 pub struct MethodSig
{
1866 pub header
: FnHeader
,
1867 pub decl
: P
<FnDecl
>,
1870 // The bodies for items are stored "out of line", in a separate
1871 // hashmap in the `Crate`. Here we just record the node-id of the item
1872 // so it can fetched later.
1873 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1874 pub struct TraitItemId
{
1878 /// Represents an item declaration within a trait declaration,
1879 /// possibly including a default implementation. A trait item is
1880 /// either required (meaning it doesn't have an implementation, just a
1881 /// signature) or provided (meaning it has a default implementation).
1882 #[derive(RustcEncodable, RustcDecodable, Debug)]
1883 pub struct TraitItem
{
1886 pub attrs
: HirVec
<Attribute
>,
1887 pub generics
: Generics
,
1888 pub kind
: TraitItemKind
,
1892 /// Represents a trait method's body (or just argument names).
1893 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1894 pub enum TraitMethod
{
1895 /// No default body in the trait, just a signature.
1896 Required(HirVec
<Ident
>),
1898 /// Both signature and body are provided in the trait.
1902 /// Represents a trait method or associated constant or type
1903 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1904 pub enum TraitItemKind
{
1905 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
1906 Const(P
<Ty
>, Option
<BodyId
>),
1907 /// A method with an optional body.
1908 Method(MethodSig
, TraitMethod
),
1909 /// An associated type with (possibly empty) bounds and optional concrete
1911 Type(GenericBounds
, Option
<P
<Ty
>>),
1914 // The bodies for items are stored "out of line", in a separate
1915 // hashmap in the `Crate`. Here we just record the node-id of the item
1916 // so it can fetched later.
1917 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1918 pub struct ImplItemId
{
1922 /// Represents anything within an `impl` block.
1923 #[derive(RustcEncodable, RustcDecodable, Debug)]
1924 pub struct ImplItem
{
1927 pub vis
: Visibility
,
1928 pub defaultness
: Defaultness
,
1929 pub attrs
: HirVec
<Attribute
>,
1930 pub generics
: Generics
,
1931 pub kind
: ImplItemKind
,
1935 /// Represents various kinds of content within an `impl`.
1936 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1937 pub enum ImplItemKind
{
1938 /// An associated constant of the given type, set to the constant result
1939 /// of the expression.
1940 Const(P
<Ty
>, BodyId
),
1941 /// A method implementation with the given signature and body.
1942 Method(MethodSig
, BodyId
),
1943 /// An associated type.
1945 /// An associated `type = impl Trait`.
1946 OpaqueTy(GenericBounds
),
1949 /// Bind a type to an associated type (i.e., `A = Foo`).
1951 /// Bindings like `A: Debug` are represented as a special type `A =
1952 /// $::Debug` that is understood by the astconv code.
1954 /// FIXME(alexreg) -- why have a separate type for the binding case,
1955 /// wouldn't it be better to make the `ty` field an enum like:
1958 /// enum TypeBindingKind {
1963 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1964 pub struct TypeBinding
{
1966 #[stable_hasher(project(name))]
1968 pub kind
: TypeBindingKind
,
1972 // Represents the two kinds of type bindings.
1973 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1974 pub enum TypeBindingKind
{
1975 /// E.g., `Foo<Bar: Send>`.
1977 bounds
: HirVec
<GenericBound
>,
1979 /// E.g., `Foo<Bar = ()>`.
1986 pub fn ty(&self) -> &Ty
{
1988 TypeBindingKind
::Equality { ref ty }
=> ty
,
1989 _
=> bug
!("expected equality type binding for parenthesized generic args"),
1994 #[derive(RustcEncodable, RustcDecodable)]
2001 impl fmt
::Debug
for Ty
{
2002 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2003 write
!(f
, "type({})",
2004 print
::to_string(print
::NO_ANN
, |s
| s
.print_type(self)))
2008 /// Not represented directly in the AST; referred to by name through a `ty_path`.
2009 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
2019 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2020 pub struct BareFnTy
{
2021 pub unsafety
: Unsafety
,
2023 pub generic_params
: HirVec
<GenericParam
>,
2024 pub decl
: P
<FnDecl
>,
2025 pub param_names
: HirVec
<Ident
>,
2028 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2029 pub struct OpaqueTy
{
2030 pub generics
: Generics
,
2031 pub bounds
: GenericBounds
,
2032 pub impl_trait_fn
: Option
<DefId
>,
2033 pub origin
: OpaqueTyOrigin
,
2036 /// From whence the opaque type came.
2037 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2038 pub enum OpaqueTyOrigin
{
2039 /// `type Foo = impl Trait;`
2047 /// The various kinds of types recognized by the compiler.
2048 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2050 /// A variable length slice (i.e., `[T]`).
2052 /// A fixed length array (i.e., `[T; n]`).
2053 Array(P
<Ty
>, AnonConst
),
2054 /// A raw pointer (i.e., `*const T` or `*mut T`).
2056 /// A reference (i.e., `&'a T` or `&'a mut T`).
2057 Rptr(Lifetime
, MutTy
),
2058 /// A bare function (e.g., `fn(usize) -> bool`).
2059 BareFn(P
<BareFnTy
>),
2060 /// The never type (`!`).
2062 /// A tuple (`(A, B, C, D, ...)`).
2064 /// A path to a type definition (`module::module::...::Type`), or an
2065 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2067 /// Type parameters may be stored in each `PathSegment`.
2069 /// A type definition itself. This is currently only used for the `type Foo = impl Trait`
2070 /// item that `impl Trait` in return position desugars to.
2072 /// The generic argument list contains the lifetimes (and in the future possibly parameters)
2073 /// that are actually bound on the `impl Trait`.
2074 Def(ItemId
, HirVec
<GenericArg
>),
2075 /// A trait object type `Bound1 + Bound2 + Bound3`
2076 /// where `Bound` is a trait or a lifetime.
2077 TraitObject(HirVec
<PolyTraitRef
>, Lifetime
),
2080 /// `TyKind::Infer` means the type should be inferred instead of it having been
2081 /// specified. This can appear anywhere in a type.
2083 /// Placeholder for a type that has failed to be defined.
2087 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2088 pub struct InlineAsmOutput
{
2089 pub constraint
: Symbol
,
2091 pub is_indirect
: bool
,
2095 // NOTE(eddyb) This is used within MIR as well, so unlike the rest of the HIR,
2096 // it needs to be `Clone` and use plain `Vec<T>` instead of `HirVec<T>`.
2097 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2098 pub struct InlineAsm
{
2100 pub asm_str_style
: StrStyle
,
2101 pub outputs
: Vec
<InlineAsmOutput
>,
2102 pub inputs
: Vec
<Symbol
>,
2103 pub clobbers
: Vec
<Symbol
>,
2105 pub alignstack
: bool
,
2106 pub dialect
: AsmDialect
,
2109 /// Represents a parameter in a function header.
2110 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2112 pub attrs
: HirVec
<Attribute
>,
2118 /// Represents the header (not the body) of a function declaration.
2119 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2121 /// The types of the function's parameters.
2123 /// Additional argument data is stored in the function's [body](Body::parameters).
2124 pub inputs
: HirVec
<Ty
>,
2125 pub output
: FunctionRetTy
,
2126 pub c_variadic
: bool
,
2127 /// Does the function have an implicit self?
2128 pub implicit_self
: ImplicitSelfKind
,
2131 /// Represents what type of implicit self a function has, if any.
2132 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2133 pub enum ImplicitSelfKind
{
2134 /// Represents a `fn x(self);`.
2136 /// Represents a `fn x(mut self);`.
2138 /// Represents a `fn x(&self);`.
2140 /// Represents a `fn x(&mut self);`.
2142 /// Represents when a function does not have a self argument or
2143 /// when a function has a `self: X` argument.
2147 impl ImplicitSelfKind
{
2148 /// Does this represent an implicit self?
2149 pub fn has_implicit_self(&self) -> bool
{
2151 ImplicitSelfKind
::None
=> false,
2157 /// Is the trait definition an auto trait?
2158 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2164 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, HashStable,
2165 Ord
, RustcEncodable
, RustcDecodable
, Debug
)]
2171 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, HashStable,
2172 RustcEncodable
, RustcDecodable
, Hash
, Debug
)]
2178 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2179 pub enum Constness
{
2184 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2185 pub enum Defaultness
{
2186 Default { has_value: bool }
,
2191 pub fn has_value(&self) -> bool
{
2193 Defaultness
::Default { has_value, .. }
=> has_value
,
2194 Defaultness
::Final
=> true,
2198 pub fn is_final(&self) -> bool
{
2199 *self == Defaultness
::Final
2202 pub fn is_default(&self) -> bool
{
2204 Defaultness
::Default { .. }
=> true,
2210 impl fmt
::Display
for Unsafety
{
2211 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2212 f
.write_str(match self {
2213 Unsafety
::Normal
=> "normal",
2214 Unsafety
::Unsafe
=> "unsafe",
2219 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2220 pub enum ImplPolarity
{
2221 /// `impl Trait for Type`
2223 /// `impl !Trait for Type`
2227 impl fmt
::Debug
for ImplPolarity
{
2228 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2229 f
.write_str(match self {
2230 ImplPolarity
::Positive
=> "positive",
2231 ImplPolarity
::Negative
=> "negative",
2237 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2238 pub enum FunctionRetTy
{
2239 /// Return type is not specified.
2241 /// Functions default to `()` and
2242 /// closures default to inference. Span points to where return
2243 /// type would be inserted.
2244 DefaultReturn(Span
),
2245 /// Everything else.
2249 impl fmt
::Display
for FunctionRetTy
{
2250 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2252 Return(ref ty
) => print
::to_string(print
::NO_ANN
, |s
| s
.print_type(ty
)).fmt(f
),
2253 DefaultReturn(_
) => "()".fmt(f
),
2258 impl FunctionRetTy
{
2259 pub fn span(&self) -> Span
{
2261 DefaultReturn(span
) => span
,
2262 Return(ref ty
) => ty
.span
,
2267 #[derive(RustcEncodable, RustcDecodable, Debug)]
2269 /// A span from the first token past `{` to the last token until `}`.
2270 /// For `mod foo;`, the inner span ranges from the first token
2271 /// to the last token in the external file.
2273 pub item_ids
: HirVec
<ItemId
>,
2276 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2277 pub struct ForeignMod
{
2279 pub items
: HirVec
<ForeignItem
>,
2282 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2283 pub struct GlobalAsm
{
2287 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2288 pub struct EnumDef
{
2289 pub variants
: HirVec
<Variant
>,
2292 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2293 pub struct Variant
{
2294 /// Name of the variant.
2295 #[stable_hasher(project(name))]
2297 /// Attributes of the variant.
2298 pub attrs
: HirVec
<Attribute
>,
2299 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2301 /// Fields and constructor id of the variant.
2302 pub data
: VariantData
,
2303 /// Explicit discriminant (e.g., `Foo = 1`).
2304 pub disr_expr
: Option
<AnonConst
>,
2309 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2311 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2312 /// Also produced for each element of a list `use`, e.g.
2313 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2316 /// Glob import, e.g., `use foo::*`.
2319 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2320 /// an additional `use foo::{}` for performing checks such as
2321 /// unstable feature gating. May be removed in the future.
2325 /// References to traits in impls.
2327 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2328 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2329 /// trait being referred to but just a unique `HirId` that serves as a key
2330 /// within the resolution map.
2331 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2332 pub struct TraitRef
{
2334 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2335 #[stable_hasher(ignore)]
2336 pub hir_ref_id
: HirId
,
2340 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2341 pub fn trait_def_id(&self) -> DefId
{
2342 match self.path
.res
{
2343 Res
::Def(DefKind
::Trait
, did
) => did
,
2344 Res
::Def(DefKind
::TraitAlias
, did
) => did
,
2348 _
=> unreachable
!(),
2353 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2354 pub struct PolyTraitRef
{
2355 /// The `'a` in `<'a> Foo<&'a T>`.
2356 pub bound_generic_params
: HirVec
<GenericParam
>,
2358 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2359 pub trait_ref
: TraitRef
,
2364 pub type Visibility
= Spanned
<VisibilityKind
>;
2366 #[derive(RustcEncodable, RustcDecodable, Debug)]
2367 pub enum VisibilityKind
{
2370 Restricted { path: P<Path>, hir_id: HirId }
,
2374 impl VisibilityKind
{
2375 pub fn is_pub(&self) -> bool
{
2377 VisibilityKind
::Public
=> true,
2382 pub fn is_pub_restricted(&self) -> bool
{
2384 VisibilityKind
::Public
|
2385 VisibilityKind
::Inherited
=> false,
2386 VisibilityKind
::Crate(..) |
2387 VisibilityKind
::Restricted { .. }
=> true,
2391 pub fn descr(&self) -> &'
static str {
2393 VisibilityKind
::Public
=> "public",
2394 VisibilityKind
::Inherited
=> "private",
2395 VisibilityKind
::Crate(..) => "crate-visible",
2396 VisibilityKind
::Restricted { .. }
=> "restricted",
2401 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2402 pub struct StructField
{
2404 #[stable_hasher(project(name))]
2406 pub vis
: Visibility
,
2409 pub attrs
: HirVec
<Attribute
>,
2413 // Still necessary in couple of places
2414 pub fn is_positional(&self) -> bool
{
2415 let first
= self.ident
.as_str().as_bytes()[0];
2416 first
>= b'
0'
&& first
<= b'
9'
2420 /// Fields and constructor IDs of enum variants and structs.
2421 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2422 pub enum VariantData
{
2423 /// A struct variant.
2425 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2426 Struct(HirVec
<StructField
>, /* recovered */ bool
),
2427 /// A tuple variant.
2429 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2430 Tuple(HirVec
<StructField
>, HirId
),
2433 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2438 /// Return the fields of this variant.
2439 pub fn fields(&self) -> &[StructField
] {
2441 VariantData
::Struct(ref fields
, ..) | VariantData
::Tuple(ref fields
, ..) => fields
,
2446 /// Return the `HirId` of this variant's constructor, if it has one.
2447 pub fn ctor_hir_id(&self) -> Option
<HirId
> {
2449 VariantData
::Struct(_
, _
) => None
,
2450 VariantData
::Tuple(_
, hir_id
) | VariantData
::Unit(hir_id
) => Some(hir_id
),
2455 // The bodies for items are stored "out of line", in a separate
2456 // hashmap in the `Crate`. Here we just record the node-id of the item
2457 // so it can fetched later.
2458 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2465 /// The name might be a dummy name in case of anonymous items
2466 #[derive(RustcEncodable, RustcDecodable, Debug)]
2470 pub attrs
: HirVec
<Attribute
>,
2472 pub vis
: Visibility
,
2476 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2477 pub struct FnHeader
{
2478 pub unsafety
: Unsafety
,
2479 pub constness
: Constness
,
2480 pub asyncness
: IsAsync
,
2485 pub fn is_const(&self) -> bool
{
2486 match &self.constness
{
2487 Constness
::Const
=> true,
2493 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
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
<Name
>),
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(P
<Path
>, UseKind
),
2507 /// A `static` item.
2508 Static(P
<Ty
>, Mutability
, BodyId
),
2510 Const(P
<Ty
>, BodyId
),
2511 /// A function declaration.
2512 Fn(P
<FnDecl
>, FnHeader
, Generics
, BodyId
),
2515 /// An external module, e.g. `extern { .. }`.
2516 ForeignMod(ForeignMod
),
2517 /// Module-level inline assembly (from `global_asm!`).
2518 GlobalAsm(P
<GlobalAsm
>),
2519 /// A type alias, e.g., `type Foo = Bar<u8>`.
2520 TyAlias(P
<Ty
>, Generics
),
2521 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2523 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2524 Enum(EnumDef
, Generics
),
2525 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2526 Struct(VariantData
, Generics
),
2527 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2528 Union(VariantData
, Generics
),
2529 /// A trait definition.
2530 Trait(IsAuto
, Unsafety
, Generics
, GenericBounds
, HirVec
<TraitItemRef
>),
2532 TraitAlias(Generics
, GenericBounds
),
2534 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2539 Option
<TraitRef
>, // (optional) trait this impl implements
2541 HirVec
<ImplItemRef
>),
2545 pub fn descriptive_variant(&self) -> &str {
2547 ItemKind
::ExternCrate(..) => "extern crate",
2548 ItemKind
::Use(..) => "use",
2549 ItemKind
::Static(..) => "static item",
2550 ItemKind
::Const(..) => "constant item",
2551 ItemKind
::Fn(..) => "function",
2552 ItemKind
::Mod(..) => "module",
2553 ItemKind
::ForeignMod(..) => "foreign module",
2554 ItemKind
::GlobalAsm(..) => "global asm",
2555 ItemKind
::TyAlias(..) => "type alias",
2556 ItemKind
::OpaqueTy(..) => "opaque type",
2557 ItemKind
::Enum(..) => "enum",
2558 ItemKind
::Struct(..) => "struct",
2559 ItemKind
::Union(..) => "union",
2560 ItemKind
::Trait(..) => "trait",
2561 ItemKind
::TraitAlias(..) => "trait alias",
2562 ItemKind
::Impl(..) => "impl",
2566 pub fn adt_kind(&self) -> Option
<AdtKind
> {
2568 ItemKind
::Struct(..) => Some(AdtKind
::Struct
),
2569 ItemKind
::Union(..) => Some(AdtKind
::Union
),
2570 ItemKind
::Enum(..) => Some(AdtKind
::Enum
),
2575 pub fn generics(&self) -> Option
<&Generics
> {
2577 ItemKind
::Fn(_
, _
, ref generics
, _
) |
2578 ItemKind
::TyAlias(_
, ref generics
) |
2579 ItemKind
::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. }
) |
2580 ItemKind
::Enum(_
, ref generics
) |
2581 ItemKind
::Struct(_
, ref generics
) |
2582 ItemKind
::Union(_
, ref generics
) |
2583 ItemKind
::Trait(_
, _
, ref generics
, _
, _
) |
2584 ItemKind
::Impl(_
, _
, _
, ref generics
, _
, _
, _
)=> generics
,
2590 /// A reference from an trait to one of its associated items. This
2591 /// contains the item's id, naturally, but also the item's name and
2592 /// some other high-level details (like whether it is an associated
2593 /// type or method, and whether it is public). This allows other
2594 /// passes to find the impl they want without loading the ID (which
2595 /// means fewer edges in the incremental compilation graph).
2596 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2597 pub struct TraitItemRef
{
2598 pub id
: TraitItemId
,
2599 #[stable_hasher(project(name))]
2601 pub kind
: AssocItemKind
,
2603 pub defaultness
: Defaultness
,
2606 /// A reference from an impl to one of its associated items. This
2607 /// contains the item's ID, naturally, but also the item's name and
2608 /// some other high-level details (like whether it is an associated
2609 /// type or method, and whether it is public). This allows other
2610 /// passes to find the impl they want without loading the ID (which
2611 /// means fewer edges in the incremental compilation graph).
2612 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2613 pub struct ImplItemRef
{
2615 #[stable_hasher(project(name))]
2617 pub kind
: AssocItemKind
,
2619 pub vis
: Visibility
,
2620 pub defaultness
: Defaultness
,
2623 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2624 pub enum AssocItemKind
{
2626 Method { has_self: bool }
,
2631 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2632 pub struct ForeignItem
{
2633 #[stable_hasher(project(name))]
2635 pub attrs
: HirVec
<Attribute
>,
2636 pub kind
: ForeignItemKind
,
2639 pub vis
: Visibility
,
2642 /// An item within an `extern` block.
2643 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2644 pub enum ForeignItemKind
{
2645 /// A foreign function.
2646 Fn(P
<FnDecl
>, HirVec
<Ident
>, Generics
),
2647 /// A foreign static item (`static ext: u8`).
2648 Static(P
<Ty
>, Mutability
),
2653 impl ForeignItemKind
{
2654 pub fn descriptive_variant(&self) -> &str {
2656 ForeignItemKind
::Fn(..) => "foreign function",
2657 ForeignItemKind
::Static(..) => "foreign static item",
2658 ForeignItemKind
::Type
=> "foreign type",
2663 /// A variable captured by a closure.
2664 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable, HashStable)]
2666 // First span where it is accessed (there can be multiple).
2670 pub type CaptureModeMap
= NodeMap
<CaptureClause
>;
2672 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2673 // has length > 0 if the trait is found through an chain of imports, starting with the
2674 // import/use statement in the scope where the trait is used.
2675 #[derive(Clone, Debug)]
2676 pub struct TraitCandidate
{
2678 pub import_ids
: SmallVec
<[NodeId
; 1]>,
2681 // Trait method resolution
2682 pub type TraitMap
= NodeMap
<Vec
<TraitCandidate
>>;
2684 // Map from the NodeId of a glob import to a list of items which are actually
2686 pub type GlobMap
= NodeMap
<FxHashSet
<Name
>>;
2688 pub fn provide(providers
: &mut Providers
<'_
>) {
2689 check_attr
::provide(providers
);
2690 map
::provide(providers
);
2691 upvars
::provide(providers
);
2694 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
2695 pub struct CodegenFnAttrs
{
2696 pub flags
: CodegenFnAttrFlags
,
2697 /// Parsed representation of the `#[inline]` attribute
2698 pub inline
: InlineAttr
,
2699 /// Parsed representation of the `#[optimize]` attribute
2700 pub optimize
: OptimizeAttr
,
2701 /// The `#[export_name = "..."]` attribute, indicating a custom symbol a
2702 /// function should be exported under
2703 pub export_name
: Option
<Symbol
>,
2704 /// The `#[link_name = "..."]` attribute, indicating a custom symbol an
2705 /// imported function should be imported as. Note that `export_name`
2706 /// probably isn't set when this is set, this is for foreign items while
2707 /// `#[export_name]` is for Rust-defined functions.
2708 pub link_name
: Option
<Symbol
>,
2709 /// The `#[link_ordinal = "..."]` attribute, indicating an ordinal an
2710 /// imported function has in the dynamic library. Note that this must not
2711 /// be set when `link_name` is set. This is for foreign items with the
2712 /// "raw-dylib" kind.
2713 pub link_ordinal
: Option
<usize>,
2714 /// The `#[target_feature(enable = "...")]` attribute and the enabled
2715 /// features (only enabled features are supported right now).
2716 pub target_features
: Vec
<Symbol
>,
2717 /// The `#[linkage = "..."]` attribute and the value we found.
2718 pub linkage
: Option
<Linkage
>,
2719 /// The `#[link_section = "..."]` attribute, or what executable section this
2720 /// should be placed in.
2721 pub link_section
: Option
<Symbol
>,
2725 #[derive(RustcEncodable, RustcDecodable, HashStable)]
2726 pub struct CodegenFnAttrFlags
: u32 {
2727 /// `#[cold]`: a hint to LLVM that this function, when called, is never on
2729 const COLD
= 1 << 0;
2730 /// `#[rustc_allocator]`: a hint to LLVM that the pointer returned from this
2731 /// function is never null.
2732 const ALLOCATOR
= 1 << 1;
2733 /// `#[unwind]`: an indicator that this function may unwind despite what
2734 /// its ABI signature may otherwise imply.
2735 const UNWIND
= 1 << 2;
2736 /// `#[rust_allocator_nounwind]`, an indicator that an imported FFI
2737 /// function will never unwind. Probably obsolete by recent changes with
2738 /// #[unwind], but hasn't been removed/migrated yet
2739 const RUSTC_ALLOCATOR_NOUNWIND
= 1 << 3;
2740 /// `#[naked]`: an indicator to LLVM that no function prologue/epilogue
2741 /// should be generated.
2742 const NAKED
= 1 << 4;
2743 /// `#[no_mangle]`: an indicator that the function's name should be the same
2745 const NO_MANGLE
= 1 << 5;
2746 /// `#[rustc_std_internal_symbol]`: an indicator that this symbol is a
2747 /// "weird symbol" for the standard library in that it has slightly
2748 /// different linkage, visibility, and reachability rules.
2749 const RUSTC_STD_INTERNAL_SYMBOL
= 1 << 6;
2750 /// `#[no_debug]`: an indicator that no debugging information should be
2751 /// generated for this function by LLVM.
2752 const NO_DEBUG
= 1 << 7;
2753 /// `#[thread_local]`: indicates a static is actually a thread local
2755 const THREAD_LOCAL
= 1 << 8;
2756 /// `#[used]`: indicates that LLVM can't eliminate this function (but the
2758 const USED
= 1 << 9;
2759 /// `#[ffi_returns_twice]`, indicates that an extern function can return
2761 const FFI_RETURNS_TWICE
= 1 << 10;
2762 /// `#[track_caller]`: allow access to the caller location
2763 const TRACK_CALLER
= 1 << 11;
2767 impl CodegenFnAttrs
{
2768 pub fn new() -> CodegenFnAttrs
{
2770 flags
: CodegenFnAttrFlags
::empty(),
2771 inline
: InlineAttr
::None
,
2772 optimize
: OptimizeAttr
::None
,
2776 target_features
: vec
![],
2782 /// Returns `true` if `#[inline]` or `#[inline(always)]` is present.
2783 pub fn requests_inline(&self) -> bool
{
2785 InlineAttr
::Hint
| InlineAttr
::Always
=> true,
2786 InlineAttr
::None
| InlineAttr
::Never
=> false,
2790 /// Returns `true` if it looks like this symbol needs to be exported, for example:
2792 /// * `#[no_mangle]` is present
2793 /// * `#[export_name(...)]` is present
2794 /// * `#[linkage]` is present
2795 pub fn contains_extern_indicator(&self) -> bool
{
2796 self.flags
.contains(CodegenFnAttrFlags
::NO_MANGLE
) ||
2797 self.export_name
.is_some() ||
2798 match self.linkage
{
2799 // These are private, so make sure we don't try to consider
2802 Some(Linkage
::Internal
) |
2803 Some(Linkage
::Private
) => false,
2809 #[derive(Copy, Clone, Debug)]
2810 pub enum Node
<'hir
> {
2813 ForeignItem(&'hir ForeignItem
),
2814 TraitItem(&'hir TraitItem
),
2815 ImplItem(&'hir ImplItem
),
2816 Variant(&'hir Variant
),
2817 Field(&'hir StructField
),
2818 AnonConst(&'hir AnonConst
),
2821 PathSegment(&'hir PathSegment
),
2823 TraitRef(&'hir TraitRef
),
2829 MacroDef(&'hir MacroDef
),
2831 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
2832 /// with synthesized constructors.
2833 Ctor(&'hir VariantData
),
2835 Lifetime(&'hir Lifetime
),
2836 GenericParam(&'hir GenericParam
),
2837 Visibility(&'hir Visibility
),
2843 pub fn ident(&self) -> Option
<Ident
> {
2845 Node
::TraitItem(TraitItem { ident, .. }
) |
2846 Node
::ImplItem(ImplItem { ident, .. }
) |
2847 Node
::ForeignItem(ForeignItem { ident, .. }
) |
2848 Node
::Item(Item { ident, .. }
) => Some(*ident
),