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, symbol::InternedString, 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: InternedString) -> Option<&GenericParam> {
632 for param in &self.params {
633 if name == param.name.ident().as_interned_str() {
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() {
674 /// A single predicate in a where-clause.
675 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
676 pub enum WherePredicate {
677 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
678 BoundPredicate(WhereBoundPredicate),
679 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
680 RegionPredicate(WhereRegionPredicate),
681 /// An equality predicate (unsupported).
682 EqPredicate(WhereEqPredicate),
685 impl WherePredicate {
686 pub fn span(&self) -> Span {
688 &WherePredicate::BoundPredicate(ref p) => p.span,
689 &WherePredicate::RegionPredicate(ref p) => p.span,
690 &WherePredicate::EqPredicate(ref p) => p.span,
695 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
696 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
697 pub struct WhereBoundPredicate {
699 /// Any generics from a `for` binding.
700 pub bound_generic_params: HirVec<GenericParam>,
701 /// The type being bounded.
702 pub bounded_ty: P<Ty>,
703 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
704 pub bounds: GenericBounds,
707 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
708 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
709 pub struct WhereRegionPredicate {
711 pub lifetime: Lifetime,
712 pub bounds: GenericBounds,
715 /// An equality predicate (e.g., `T = int`); currently unsupported.
716 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
717 pub struct WhereEqPredicate {
724 #[derive(RustcEncodable, RustcDecodable, Debug)]
725 pub struct ModuleItems {
726 // Use BTreeSets here so items are in the same order as in the
727 // list of all items in Crate
728 pub items: BTreeSet<HirId>,
729 pub trait_items: BTreeSet<TraitItemId>,
730 pub impl_items: BTreeSet<ImplItemId>,
733 /// The top-level data structure that stores the entire contents of
734 /// the crate currently being compiled.
736 /// For more details, see the [rustc guide].
738 /// [rustc guide]: https://rust-lang.github.io/rustc-guide/hir.html
739 #[derive(RustcEncodable, RustcDecodable, Debug)]
742 pub attrs: HirVec<Attribute>,
744 pub exported_macros: HirVec<MacroDef>,
745 // Attributes from non-exported macros, kept only for collecting the library feature list.
746 pub non_exported_macro_attrs: HirVec<Attribute>,
748 // N.B., we use a `BTreeMap` here so that `visit_all_items` iterates
749 // over the ids in increasing order. In principle it should not
750 // matter what order we visit things in, but in *practice* it
751 // does, because it can affect the order in which errors are
752 // detected, which in turn can make compile-fail tests yield
753 // slightly different results.
754 pub items: BTreeMap<HirId, Item>,
756 pub trait_items: BTreeMap<TraitItemId, TraitItem>,
757 pub impl_items: BTreeMap<ImplItemId, ImplItem>,
758 pub bodies: BTreeMap<BodyId, Body>,
759 pub trait_impls: BTreeMap<DefId, Vec<HirId>>,
761 /// A list of the body ids written out in the order in which they
762 /// appear in the crate. If you're going to process all the bodies
763 /// in the crate, you should iterate over this list rather than the keys
765 pub body_ids: Vec<BodyId>,
767 /// A list of modules written out in the order in which they
768 /// appear in the crate. This includes the main crate module.
769 pub modules: BTreeMap<HirId, ModuleItems>,
773 pub fn item(&self, id: HirId) -> &Item {
777 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem {
778 &self.trait_items[&id]
781 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem {
782 &self.impl_items[&id]
785 /// Visits all items in the crate in some deterministic (but
786 /// unspecified) order. If you just need to process every item,
787 /// but don't care about nesting, this method is the best choice.
789 /// If you do care about nesting -- usually because your algorithm
790 /// follows lexical scoping rules -- then you want a different
791 /// approach. You should override `visit_nested_item` in your
792 /// visitor and then call `intravisit::walk_crate` instead.
793 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
794 where V: itemlikevisit::ItemLikeVisitor<'hir>
796 for (_, item) in &self.items {
797 visitor.visit_item(item);
800 for (_, trait_item) in &self.trait_items {
801 visitor.visit_trait_item(trait_item);
804 for (_, impl_item) in &self.impl_items {
805 visitor.visit_impl_item(impl_item);
809 /// A parallel version of `visit_all_item_likes`.
810 pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
811 where V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send
814 par_for_each_in(&self.items, |(_, item)| {
815 visitor.visit_item(item);
818 par_for_each_in(&self.trait_items, |(_, trait_item)| {
819 visitor.visit_trait_item(trait_item);
822 par_for_each_in(&self.impl_items, |(_, impl_item)| {
823 visitor.visit_impl_item(impl_item);
828 pub fn body(&self, id: BodyId) -> &Body {
833 /// A macro definition, in this crate or imported from another.
835 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
836 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
837 pub struct MacroDef {
840 pub attrs: HirVec<Attribute>,
843 pub body: TokenStream,
847 /// A block of statements `{ .. }`, which may have a label (in this case the
848 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
849 /// the `rules` being anything but `DefaultBlock`.
850 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
852 /// Statements in a block.
853 pub stmts: HirVec<Stmt>,
854 /// An expression at the end of the block
855 /// without a semicolon, if any.
856 pub expr: Option<P<Expr>>,
857 #[stable_hasher(ignore)]
859 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
860 pub rules: BlockCheckMode,
862 /// If true, then there may exist `break 'a` values that aim to
863 /// break out of this block early.
864 /// Used by `'label: {}` blocks and by `try {}` blocks.
865 pub targeted_by_break: bool,
868 #[derive(RustcEncodable, RustcDecodable, HashStable)]
870 #[stable_hasher(ignore)]
876 impl fmt::Debug for Pat {
877 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
878 write!(f, "pat({}: {})", self.hir_id,
879 print::to_string(print::NO_ANN, |s| s.print_pat(self)))
884 // FIXME(#19596) this is a workaround, but there should be a better way
885 fn walk_short_(&self, it: &mut impl FnMut(&Pat) -> bool) -> bool {
892 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
893 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
894 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
895 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
896 Slice(before, slice, after) => {
900 .all(|p| p.walk_short_(it))
905 /// Walk the pattern in left-to-right order,
906 /// short circuiting (with `.all(..)`) if `false` is returned.
908 /// Note that when visiting e.g. `Tuple(ps)`,
909 /// if visiting `ps[0]` returns `false`,
910 /// then `ps[1]` will not be visited.
911 pub fn walk_short(&self, mut it: impl FnMut(&Pat) -> bool) -> bool {
912 self.walk_short_(&mut it)
915 // FIXME(#19596) this is a workaround, but there should be a better way
916 fn walk_(&self, it: &mut impl FnMut(&Pat) -> bool) {
923 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {},
924 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
925 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
926 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
927 Slice(before, slice, after) => {
931 .for_each(|p| p.walk_(it))
936 /// Walk the pattern in left-to-right order.
938 /// If `it(pat)` returns `false`, the children are not visited.
939 pub fn walk(&self, mut it: impl FnMut(&Pat) -> bool) {
944 /// A single field in a struct pattern.
946 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
947 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
948 /// except `is_shorthand` is true.
949 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
950 pub struct FieldPat {
951 #[stable_hasher(ignore)]
953 /// The identifier for the field.
954 #[stable_hasher(project(name))]
956 /// The pattern the field is destructured to.
958 pub is_shorthand: bool,
962 /// Explicit binding annotations given in the HIR for a binding. Note
963 /// that this is not the final binding *mode* that we infer after type
965 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
966 pub enum BindingAnnotation {
967 /// No binding annotation given: this means that the final binding mode
968 /// will depend on whether we have skipped through a `&` reference
969 /// when matching. For example, the `x` in `Some(x)` will have binding
970 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
971 /// ultimately be inferred to be by-reference.
973 /// Note that implicit reference skipping is not implemented yet (#42640).
976 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
979 /// Annotated as `ref`, like `ref x`
982 /// Annotated as `ref mut x`.
986 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
992 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
994 /// Represents a wildcard pattern (i.e., `_`).
997 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
998 /// The `HirId` is the canonical ID for the variable being bound,
999 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
1000 /// which is the pattern ID of the first `x`.
1001 Binding(BindingAnnotation, HirId, Ident, Option<P<Pat>>),
1003 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
1004 /// The `bool` is `true` in the presence of a `..`.
1005 Struct(QPath, HirVec<FieldPat>, bool),
1007 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
1008 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
1009 /// `0 <= position <= subpats.len()`
1010 TupleStruct(QPath, HirVec<P<Pat>>, Option<usize>),
1012 /// An or-pattern `A | B | C`.
1013 /// Invariant: `pats.len() >= 2`.
1016 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
1019 /// A tuple pattern (e.g., `(a, b)`).
1020 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
1021 /// `0 <= position <= subpats.len()`
1022 Tuple(HirVec<P<Pat>>, Option<usize>),
1024 /// A `box` pattern.
1027 /// A reference pattern (e.g., `&mut (a, b)`).
1028 Ref(P<Pat>, Mutability),
1033 /// A range pattern (e.g., `1..=2` or `1..2`).
1034 Range(P<Expr>, P<Expr>, RangeEnd),
1036 /// `[a, b, ..i, y, z]` is represented as:
1037 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`.
1038 Slice(HirVec<P<Pat>>, Option<P<Pat>>, HirVec<P<Pat>>),
1041 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, HashStable,
1042 RustcEncodable, RustcDecodable, Hash, Debug)]
1043 pub enum Mutability {
1049 /// Returns `MutMutable` only if both `self` and `other` are mutable.
1050 pub fn and(self, other: Self) -> Self {
1052 MutMutable => other,
1053 MutImmutable => MutImmutable,
1057 pub fn invert(self) -> Self {
1059 MutMutable => MutImmutable,
1060 MutImmutable => MutMutable,
1065 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Hash, HashStable)]
1066 pub enum BinOpKind {
1067 /// The `+` operator (addition).
1069 /// The `-` operator (subtraction).
1071 /// The `*` operator (multiplication).
1073 /// The `/` operator (division).
1075 /// The `%` operator (modulus).
1077 /// The `&&` operator (logical and).
1079 /// The `||` operator (logical or).
1081 /// The `^` operator (bitwise xor).
1083 /// The `&` operator (bitwise and).
1085 /// The `|` operator (bitwise or).
1087 /// The `<<` operator (shift left).
1089 /// The `>>` operator (shift right).
1091 /// The `==` operator (equality).
1093 /// The `<` operator (less than).
1095 /// The `<=` operator (less than or equal to).
1097 /// The `!=` operator (not equal to).
1099 /// The `>=` operator (greater than or equal to).
1101 /// The `>` operator (greater than).
1106 pub fn as_str(self) -> &'static str {
1108 BinOpKind::Add => "+",
1109 BinOpKind::Sub => "-",
1110 BinOpKind::Mul => "*",
1111 BinOpKind::Div => "/",
1112 BinOpKind::Rem => "%",
1113 BinOpKind::And => "&&",
1114 BinOpKind::Or => "||",
1115 BinOpKind::BitXor => "^",
1116 BinOpKind::BitAnd => "&",
1117 BinOpKind::BitOr => "|",
1118 BinOpKind::Shl => "<<",
1119 BinOpKind::Shr => ">>",
1120 BinOpKind::Eq => "==",
1121 BinOpKind::Lt => "<",
1122 BinOpKind::Le => "<=",
1123 BinOpKind::Ne => "!=",
1124 BinOpKind::Ge => ">=",
1125 BinOpKind::Gt => ">",
1129 pub fn is_lazy(self) -> bool {
1131 BinOpKind::And | BinOpKind::Or => true,
1136 pub fn is_shift(self) -> bool {
1138 BinOpKind::Shl | BinOpKind::Shr => true,
1143 pub fn is_comparison(self) -> bool {
1150 BinOpKind::Ge => true,
1162 BinOpKind::Shr => false,
1166 /// Returns `true` if the binary operator takes its arguments by value.
1167 pub fn is_by_value(self) -> bool {
1168 !self.is_comparison()
1172 impl Into<ast::BinOpKind> for BinOpKind {
1173 fn into(self) -> ast::BinOpKind {
1175 BinOpKind::Add => ast::BinOpKind::Add,
1176 BinOpKind::Sub => ast::BinOpKind::Sub,
1177 BinOpKind::Mul => ast::BinOpKind::Mul,
1178 BinOpKind::Div => ast::BinOpKind::Div,
1179 BinOpKind::Rem => ast::BinOpKind::Rem,
1180 BinOpKind::And => ast::BinOpKind::And,
1181 BinOpKind::Or => ast::BinOpKind::Or,
1182 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1183 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1184 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1185 BinOpKind::Shl => ast::BinOpKind::Shl,
1186 BinOpKind::Shr => ast::BinOpKind::Shr,
1187 BinOpKind::Eq => ast::BinOpKind::Eq,
1188 BinOpKind::Lt => ast::BinOpKind::Lt,
1189 BinOpKind::Le => ast::BinOpKind::Le,
1190 BinOpKind::Ne => ast::BinOpKind::Ne,
1191 BinOpKind::Ge => ast::BinOpKind::Ge,
1192 BinOpKind::Gt => ast::BinOpKind::Gt,
1197 pub type BinOp = Spanned<BinOpKind>;
1199 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Hash, HashStable)]
1201 /// The `*` operator (deferencing).
1203 /// The `!` operator (logical negation).
1205 /// The `-` operator (negation).
1210 pub fn as_str(self) -> &'static str {
1218 /// Returns `true` if the unary operator takes its argument by value.
1219 pub fn is_by_value(self) -> bool {
1221 UnNeg | UnNot => true,
1228 #[derive(RustcEncodable, RustcDecodable)]
1235 impl fmt::Debug for Stmt {
1236 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1237 write!(f, "stmt({}: {})", self.hir_id,
1238 print::to_string(print::NO_ANN, |s| s.print_stmt(self)))
1242 /// The contents of a statement.
1243 #[derive(RustcEncodable, RustcDecodable, HashStable)]
1245 /// A local (`let`) binding.
1248 /// An item binding.
1251 /// An expression without a trailing semi-colon (must have unit type).
1254 /// An expression with a trailing semi-colon (may have any type).
1259 pub fn attrs(&self) -> &[Attribute] {
1261 StmtKind::Local(ref l) => &l.attrs,
1262 StmtKind::Item(_) => &[],
1263 StmtKind::Expr(ref e) |
1264 StmtKind::Semi(ref e) => &e.attrs,
1269 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1270 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1273 /// Type annotation, if any (otherwise the type will be inferred).
1274 pub ty: Option<P<Ty>>,
1275 /// Initializer expression to set the value, if any.
1276 pub init: Option<P<Expr>>,
1279 pub attrs: ThinVec<Attribute>,
1280 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1281 /// desugaring. Otherwise will be `Normal`.
1282 pub source: LocalSource,
1285 /// Represents a single arm of a `match` expression, e.g.
1286 /// `<pat> (if <guard>) => <body>`.
1287 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1289 #[stable_hasher(ignore)]
1292 pub attrs: HirVec<Attribute>,
1293 /// If this pattern and the optional guard matches, then `body` is evaluated.
1295 /// Optional guard clause.
1296 pub guard: Option<Guard>,
1297 /// The expression the arm evaluates to if this arm matches.
1301 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1306 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1308 #[stable_hasher(ignore)]
1313 pub is_shorthand: bool,
1316 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1317 pub enum BlockCheckMode {
1319 UnsafeBlock(UnsafeSource),
1320 PushUnsafeBlock(UnsafeSource),
1321 PopUnsafeBlock(UnsafeSource),
1324 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1325 pub enum UnsafeSource {
1330 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1335 /// The body of a function, closure, or constant value. In the case of
1336 /// a function, the body contains not only the function body itself
1337 /// (which is an expression), but also the argument patterns, since
1338 /// those are something that the caller doesn't really care about.
1343 /// fn foo((x, y): (u32, u32)) -> u32 {
1348 /// Here, the `Body` associated with `foo()` would contain:
1350 /// - an `params` array containing the `(x, y)` pattern
1351 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1352 /// - `generator_kind` would be `None`
1354 /// All bodies have an **owner**, which can be accessed via the HIR
1355 /// map using `body_owner_def_id()`.
1356 #[derive(RustcEncodable, RustcDecodable, Debug)]
1358 pub params: HirVec<Param>,
1360 pub generator_kind: Option<GeneratorKind>,
1364 pub fn id(&self) -> BodyId {
1366 hir_id: self.value.hir_id,
1370 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1375 /// The type of source expression that caused this generator to be created.
1376 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, HashStable,
1377 RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1378 pub enum GeneratorKind {
1379 /// An explicit `async` block or the body of an async function.
1380 Async(AsyncGeneratorKind),
1382 /// A generator literal created via a `yield` inside a closure.
1386 impl fmt::Display for GeneratorKind {
1387 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1389 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1390 GeneratorKind::Gen => f.write_str("generator"),
1395 /// In the case of a generator created as part of an async construct,
1396 /// which kind of async construct caused it to be created?
1398 /// This helps error messages but is also used to drive coercions in
1399 /// type-checking (see #60424).
1400 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, HashStable,
1401 RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1402 pub enum AsyncGeneratorKind {
1403 /// An explicit `async` block written by the user.
1406 /// An explicit `async` block written by the user.
1409 /// The `async` block generated as the body of an async function.
1413 impl fmt::Display for AsyncGeneratorKind {
1414 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1415 f.write_str(match self {
1416 AsyncGeneratorKind::Block => "`async` block",
1417 AsyncGeneratorKind::Closure => "`async` closure body",
1418 AsyncGeneratorKind::Fn => "`async fn` body",
1423 #[derive(Copy, Clone, Debug)]
1424 pub enum BodyOwnerKind {
1425 /// Functions and methods.
1431 /// Constants and associated constants.
1434 /// Initializer of a `static` item.
1438 impl BodyOwnerKind {
1439 pub fn is_fn_or_closure(self) -> bool {
1441 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1442 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1448 pub type Lit = Spanned<LitKind>;
1450 /// A constant (expression) that's not an item or associated item,
1451 /// but needs its own `DefId` for type-checking, const-eval, etc.
1452 /// These are usually found nested inside types (e.g., array lengths)
1453 /// or expressions (e.g., repeat counts), and also used to define
1454 /// explicit discriminant values for enum variants.
1455 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1456 pub struct AnonConst {
1462 #[derive(RustcEncodable, RustcDecodable)]
1466 pub attrs: ThinVec<Attribute>,
1470 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1471 #[cfg(target_arch = "x86_64")]
1472 static_assert_size!(Expr, 72);
1475 pub fn precedence(&self) -> ExprPrecedence {
1477 ExprKind::Box(_) => ExprPrecedence::Box,
1478 ExprKind::Array(_) => ExprPrecedence::Array,
1479 ExprKind::Call(..) => ExprPrecedence::Call,
1480 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1481 ExprKind::Tup(_) => ExprPrecedence::Tup,
1482 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1483 ExprKind::Unary(..) => ExprPrecedence::Unary,
1484 ExprKind::Lit(_) => ExprPrecedence::Lit,
1485 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1486 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1487 ExprKind::Loop(..) => ExprPrecedence::Loop,
1488 ExprKind::Match(..) => ExprPrecedence::Match,
1489 ExprKind::Closure(..) => ExprPrecedence::Closure,
1490 ExprKind::Block(..) => ExprPrecedence::Block,
1491 ExprKind::Assign(..) => ExprPrecedence::Assign,
1492 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1493 ExprKind::Field(..) => ExprPrecedence::Field,
1494 ExprKind::Index(..) => ExprPrecedence::Index,
1495 ExprKind::Path(..) => ExprPrecedence::Path,
1496 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1497 ExprKind::Break(..) => ExprPrecedence::Break,
1498 ExprKind::Continue(..) => ExprPrecedence::Continue,
1499 ExprKind::Ret(..) => ExprPrecedence::Ret,
1500 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1501 ExprKind::Struct(..) => ExprPrecedence::Struct,
1502 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1503 ExprKind::Yield(..) => ExprPrecedence::Yield,
1504 ExprKind::Err => ExprPrecedence::Err,
1508 pub fn is_place_expr(&self) -> bool {
1510 ExprKind::Path(QPath::Resolved(_, ref path)) => {
1513 | Res::Def(DefKind::Static, _)
1519 ExprKind::Type(ref e, _) => {
1523 ExprKind::Unary(UnDeref, _) |
1524 ExprKind::Field(..) |
1525 ExprKind::Index(..) => {
1529 // Partially qualified paths in expressions can only legally
1530 // refer to associated items which are always rvalues.
1531 ExprKind::Path(QPath::TypeRelative(..)) |
1533 ExprKind::Call(..) |
1534 ExprKind::MethodCall(..) |
1535 ExprKind::Struct(..) |
1537 ExprKind::Match(..) |
1538 ExprKind::Closure(..) |
1539 ExprKind::Block(..) |
1540 ExprKind::Repeat(..) |
1541 ExprKind::Array(..) |
1542 ExprKind::Break(..) |
1543 ExprKind::Continue(..) |
1545 ExprKind::Loop(..) |
1546 ExprKind::Assign(..) |
1547 ExprKind::InlineAsm(..) |
1548 ExprKind::AssignOp(..) |
1550 ExprKind::Unary(..) |
1552 ExprKind::AddrOf(..) |
1553 ExprKind::Binary(..) |
1554 ExprKind::Yield(..) |
1555 ExprKind::Cast(..) |
1556 ExprKind::DropTemps(..) |
1563 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1564 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1565 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1566 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1567 /// beyond remembering to call this function before doing analysis on it.
1568 pub fn peel_drop_temps(&self) -> &Self {
1569 let mut expr = self;
1570 while let ExprKind::DropTemps(inner) = &expr.kind {
1577 impl fmt::Debug for Expr {
1578 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1579 write!(f, "expr({}: {})", self.hir_id,
1580 print::to_string(print::NO_ANN, |s| s.print_expr(self)))
1584 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1586 /// A `box x` expression.
1588 /// An array (e.g., `[a, b, c, d]`).
1589 Array(HirVec<Expr>),
1590 /// A function call.
1592 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1593 /// and the second field is the list of arguments.
1594 /// This also represents calling the constructor of
1595 /// tuple-like ADTs such as tuple structs and enum variants.
1596 Call(P<Expr>, HirVec<Expr>),
1597 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1599 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1600 /// (within the angle brackets).
1601 /// The first element of the vector of `Expr`s is the expression that evaluates
1602 /// to the object on which the method is being called on (the receiver),
1603 /// and the remaining elements are the rest of the arguments.
1604 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1605 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1606 MethodCall(P<PathSegment>, Span, HirVec<Expr>),
1607 /// A tuple (e.g., `(a, b, c, d)`).
1609 /// A binary operation (e.g., `a + b`, `a * b`).
1610 Binary(BinOp, P<Expr>, P<Expr>),
1611 /// A unary operation (e.g., `!x`, `*x`).
1612 Unary(UnOp, P<Expr>),
1613 /// A literal (e.g., `1`, `"foo"`).
1615 /// A cast (e.g., `foo as f64`).
1616 Cast(P<Expr>, P<Ty>),
1617 /// A type reference (e.g., `Foo`).
1618 Type(P<Expr>, P<Ty>),
1619 /// Wraps the expression in a terminating scope.
1620 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1622 /// This construct only exists to tweak the drop order in HIR lowering.
1623 /// An example of that is the desugaring of `for` loops.
1625 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1627 /// I.e., `'label: loop { <block> }`.
1628 Loop(P<Block>, Option<Label>, LoopSource),
1629 /// A `match` block, with a source that indicates whether or not it is
1630 /// the result of a desugaring, and if so, which kind.
1631 Match(P<Expr>, HirVec<Arm>, MatchSource),
1632 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1634 /// The `Span` is the argument block `|...|`.
1636 /// This may also be a generator literal or an `async block` as indicated by the
1637 /// `Option<GeneratorMovability>`.
1638 Closure(CaptureClause, P<FnDecl>, BodyId, Span, Option<GeneratorMovability>),
1639 /// A block (e.g., `'label: { ... }`).
1640 Block(P<Block>, Option<Label>),
1642 /// An assignment (e.g., `a = foo()`).
1643 Assign(P<Expr>, P<Expr>),
1644 /// An assignment with an operator.
1647 AssignOp(BinOp, P<Expr>, P<Expr>),
1648 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1649 Field(P<Expr>, Ident),
1650 /// An indexing operation (`foo[2]`).
1651 Index(P<Expr>, P<Expr>),
1653 /// Path to a definition, possibly containing lifetime or type parameters.
1656 /// A referencing operation (i.e., `&a` or `&mut a`).
1657 AddrOf(Mutability, P<Expr>),
1658 /// A `break`, with an optional label to break.
1659 Break(Destination, Option<P<Expr>>),
1660 /// A `continue`, with an optional label.
1661 Continue(Destination),
1662 /// A `return`, with an optional value to be returned.
1663 Ret(Option<P<Expr>>),
1665 /// Inline assembly (from `asm!`), with its outputs and inputs.
1666 InlineAsm(P<InlineAsm>, HirVec<Expr>, HirVec<Expr>),
1668 /// A struct or struct-like variant literal expression.
1670 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1671 /// where `base` is the `Option<Expr>`.
1672 Struct(P<QPath>, HirVec<Field>, Option<P<Expr>>),
1674 /// An array literal constructed from one repeated element.
1676 /// E.g., `[1; 5]`. The first expression is the element
1677 /// to be repeated; the second is the number of times to repeat it.
1678 Repeat(P<Expr>, AnonConst),
1680 /// A suspension point for generators (i.e., `yield <expr>`).
1681 Yield(P<Expr>, YieldSource),
1683 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1687 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1688 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1690 /// Path to a definition, optionally "fully-qualified" with a `Self`
1691 /// type, if the path points to an associated item in a trait.
1693 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1694 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1695 /// even though they both have the same two-segment `Clone::clone` `Path`.
1696 Resolved(Option<P<Ty>>, P<Path>),
1698 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1699 /// Will be resolved by type-checking to an associated item.
1701 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1702 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1703 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1704 TypeRelative(P<Ty>, P<PathSegment>)
1707 /// Hints at the original code for a let statement.
1708 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1709 pub enum LocalSource {
1710 /// A `match _ { .. }`.
1712 /// A desugared `for _ in _ { .. }` loop.
1714 /// When lowering async functions, we create locals within the `async move` so that
1715 /// all parameters are dropped after the future is polled.
1717 /// ```ignore (pseudo-Rust)
1718 /// async fn foo(<pattern> @ x: Type) {
1720 /// let <pattern> = x;
1725 /// A desugared `<expr>.await`.
1729 /// Hints at the original code for a `match _ { .. }`.
1730 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
1731 pub enum MatchSource {
1732 /// A `match _ { .. }`.
1734 /// An `if _ { .. }` (optionally with `else { .. }`).
1736 contains_else_clause: bool,
1738 /// An `if let _ = _ { .. }` (optionally with `else { .. }`).
1740 contains_else_clause: bool,
1742 /// A `while _ { .. }` (which was desugared to a `loop { match _ { .. } }`).
1744 /// A `while let _ = _ { .. }` (which was desugared to a
1745 /// `loop { match _ { .. } }`).
1747 /// A desugared `for _ in _ { .. }` loop.
1749 /// A desugared `?` operator.
1751 /// A desugared `<expr>.await`.
1755 /// The loop type that yielded an `ExprKind::Loop`.
1756 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1757 pub enum LoopSource {
1758 /// A `loop { .. }` loop.
1760 /// A `while _ { .. }` loop.
1762 /// A `while let _ = _ { .. }` loop.
1764 /// A `for _ in _ { .. }` loop.
1769 pub fn name(self) -> &'static str {
1771 LoopSource::Loop => "loop",
1772 LoopSource::While => "while",
1773 LoopSource::WhileLet => "while let",
1774 LoopSource::ForLoop => "for",
1779 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1780 pub enum LoopIdError {
1782 UnlabeledCfInWhileCondition,
1786 impl fmt::Display for LoopIdError {
1787 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1788 f.write_str(match self {
1789 LoopIdError::OutsideLoopScope => "not inside loop scope",
1790 LoopIdError::UnlabeledCfInWhileCondition =>
1791 "unlabeled control flow (break or continue) in while condition",
1792 LoopIdError::UnresolvedLabel => "label not found",
1797 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1798 pub struct Destination {
1799 // This is `Some(_)` iff there is an explicit user-specified `label
1800 pub label: Option<Label>,
1802 // These errors are caught and then reported during the diagnostics pass in
1803 // librustc_passes/loops.rs
1804 pub target_id: Result<HirId, LoopIdError>,
1807 /// Whether a generator contains self-references, causing it to be `!Unpin`.
1808 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, HashStable,
1809 RustcEncodable, RustcDecodable, Hash, Debug)]
1810 pub enum GeneratorMovability {
1811 /// May contain self-references, `!Unpin`.
1814 /// Must not contain self-references, `Unpin`.
1818 /// The yield kind that caused an `ExprKind::Yield`.
1819 #[derive(Copy, Clone, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable, HashStable)]
1820 pub enum YieldSource {
1821 /// An `<expr>.await`.
1823 /// A plain `yield`.
1827 impl fmt::Display for YieldSource {
1828 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1829 f.write_str(match self {
1830 YieldSource::Await => "`await`",
1831 YieldSource::Yield => "`yield`",
1836 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1837 pub enum CaptureClause {
1842 // N.B., if you change this, you'll probably want to change the corresponding
1843 // type structure in middle/ty.rs as well.
1844 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1847 pub mutbl: Mutability,
1850 /// Represents a method's signature in a trait declaration or implementation.
1851 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1852 pub struct MethodSig {
1853 pub header: FnHeader,
1854 pub decl: P<FnDecl>,
1857 // The bodies for items are stored "out of line", in a separate
1858 // hashmap in the `Crate`. Here we just record the node-id of the item
1859 // so it can fetched later.
1860 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1861 pub struct TraitItemId {
1865 /// Represents an item declaration within a trait declaration,
1866 /// possibly including a default implementation. A trait item is
1867 /// either required (meaning it doesn't have an implementation, just a
1868 /// signature) or provided (meaning it has a default implementation).
1869 #[derive(RustcEncodable, RustcDecodable, Debug)]
1870 pub struct TraitItem {
1873 pub attrs: HirVec<Attribute>,
1874 pub generics: Generics,
1875 pub kind: TraitItemKind,
1879 /// Represents a trait method's body (or just argument names).
1880 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1881 pub enum TraitMethod {
1882 /// No default body in the trait, just a signature.
1883 Required(HirVec<Ident>),
1885 /// Both signature and body are provided in the trait.
1889 /// Represents a trait method or associated constant or type
1890 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1891 pub enum TraitItemKind {
1892 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
1893 Const(P<Ty>, Option<BodyId>),
1894 /// A method with an optional body.
1895 Method(MethodSig, TraitMethod),
1896 /// An associated type with (possibly empty) bounds and optional concrete
1898 Type(GenericBounds, Option<P<Ty>>),
1901 // The bodies for items are stored "out of line", in a separate
1902 // hashmap in the `Crate`. Here we just record the node-id of the item
1903 // so it can fetched later.
1904 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1905 pub struct ImplItemId {
1909 /// Represents anything within an `impl` block.
1910 #[derive(RustcEncodable, RustcDecodable, Debug)]
1911 pub struct ImplItem {
1914 pub vis: Visibility,
1915 pub defaultness: Defaultness,
1916 pub attrs: HirVec<Attribute>,
1917 pub generics: Generics,
1918 pub kind: ImplItemKind,
1922 /// Represents various kinds of content within an `impl`.
1923 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1924 pub enum ImplItemKind {
1925 /// An associated constant of the given type, set to the constant result
1926 /// of the expression.
1927 Const(P<Ty>, BodyId),
1928 /// A method implementation with the given signature and body.
1929 Method(MethodSig, BodyId),
1930 /// An associated type.
1932 /// An associated `type = impl Trait`.
1933 OpaqueTy(GenericBounds),
1936 /// Bind a type to an associated type (i.e., `A = Foo`).
1938 /// Bindings like `A: Debug` are represented as a special type `A =
1939 /// $::Debug` that is understood by the astconv code.
1941 /// FIXME(alexreg) -- why have a separate type for the binding case,
1942 /// wouldn't it be better to make the `ty` field an enum like:
1945 /// enum TypeBindingKind {
1950 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1951 pub struct TypeBinding {
1953 #[stable_hasher(project(name))]
1955 pub kind: TypeBindingKind,
1959 // Represents the two kinds of type bindings.
1960 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1961 pub enum TypeBindingKind {
1962 /// E.g., `Foo<Bar: Send>`.
1964 bounds: HirVec<GenericBound>,
1966 /// E.g., `Foo<Bar = ()>`.
1973 pub fn ty(&self) -> &Ty {
1975 TypeBindingKind::Equality { ref ty } => ty,
1976 _ => bug!("expected equality type binding for parenthesized generic args"),
1981 #[derive(RustcEncodable, RustcDecodable)]
1988 impl fmt::Debug for Ty {
1989 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1990 write!(f, "type({})",
1991 print::to_string(print::NO_ANN, |s| s.print_type(self)))
1995 /// Not represented directly in the AST; referred to by name through a `ty_path`.
1996 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
2006 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2007 pub struct BareFnTy {
2008 pub unsafety: Unsafety,
2010 pub generic_params: HirVec<GenericParam>,
2011 pub decl: P<FnDecl>,
2012 pub param_names: HirVec<Ident>,
2015 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2016 pub struct OpaqueTy {
2017 pub generics: Generics,
2018 pub bounds: GenericBounds,
2019 pub impl_trait_fn: Option<DefId>,
2020 pub origin: OpaqueTyOrigin,
2023 /// From whence the opaque type came.
2024 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2025 pub enum OpaqueTyOrigin {
2026 /// `type Foo = impl Trait;`
2034 /// The various kinds of types recognized by the compiler.
2035 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2037 /// A variable length slice (i.e., `[T]`).
2039 /// A fixed length array (i.e., `[T; n]`).
2040 Array(P<Ty>, AnonConst),
2041 /// A raw pointer (i.e., `*const T` or `*mut T`).
2043 /// A reference (i.e., `&'a T` or `&'a mut T`).
2044 Rptr(Lifetime, MutTy),
2045 /// A bare function (e.g., `fn(usize) -> bool`).
2046 BareFn(P<BareFnTy>),
2047 /// The never type (`!`).
2049 /// A tuple (`(A, B, C, D, ...)`).
2051 /// A path to a type definition (`module::module::...::Type`), or an
2052 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2054 /// Type parameters may be stored in each `PathSegment`.
2056 /// A type definition itself. This is currently only used for the `type Foo = impl Trait`
2057 /// item that `impl Trait` in return position desugars to.
2059 /// The generic argument list contains the lifetimes (and in the future possibly parameters)
2060 /// that are actually bound on the `impl Trait`.
2061 Def(ItemId, HirVec<GenericArg>),
2062 /// A trait object type `Bound1 + Bound2 + Bound3`
2063 /// where `Bound` is a trait or a lifetime.
2064 TraitObject(HirVec<PolyTraitRef>, Lifetime),
2067 /// `TyKind::Infer` means the type should be inferred instead of it having been
2068 /// specified. This can appear anywhere in a type.
2070 /// Placeholder for a type that has failed to be defined.
2074 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2075 pub struct InlineAsmOutput {
2076 pub constraint: Symbol,
2078 pub is_indirect: bool,
2082 // NOTE(eddyb) This is used within MIR as well, so unlike the rest of the HIR,
2083 // it needs to be `Clone` and use plain `Vec<T>` instead of `HirVec<T>`.
2084 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2085 pub struct InlineAsm {
2087 pub asm_str_style: StrStyle,
2088 pub outputs: Vec<InlineAsmOutput>,
2089 pub inputs: Vec<Symbol>,
2090 pub clobbers: Vec<Symbol>,
2092 pub alignstack: bool,
2093 pub dialect: AsmDialect,
2096 /// Represents a parameter in a function header.
2097 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2099 pub attrs: HirVec<Attribute>,
2105 /// Represents the header (not the body) of a function declaration.
2106 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2108 /// The types of the function's parameters.
2110 /// Additional argument data is stored in the function's [body](Body::parameters).
2111 pub inputs: HirVec<Ty>,
2112 pub output: FunctionRetTy,
2113 pub c_variadic: bool,
2114 /// Does the function have an implicit self?
2115 pub implicit_self: ImplicitSelfKind,
2118 /// Represents what type of implicit self a function has, if any.
2119 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2120 pub enum ImplicitSelfKind {
2121 /// Represents a `fn x(self);`.
2123 /// Represents a `fn x(mut self);`.
2125 /// Represents a `fn x(&self);`.
2127 /// Represents a `fn x(&mut self);`.
2129 /// Represents when a function does not have a self argument or
2130 /// when a function has a `self: X` argument.
2134 impl ImplicitSelfKind {
2135 /// Does this represent an implicit self?
2136 pub fn has_implicit_self(&self) -> bool {
2138 ImplicitSelfKind::None => false,
2144 /// Is the trait definition an auto trait?
2145 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2151 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, HashStable,
2152 Ord, RustcEncodable, RustcDecodable, Debug)]
2158 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, HashStable,
2159 RustcEncodable, RustcDecodable, Hash, Debug)]
2165 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2166 pub enum Constness {
2171 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2172 pub enum Defaultness {
2173 Default { has_value: bool },
2178 pub fn has_value(&self) -> bool {
2180 Defaultness::Default { has_value, .. } => has_value,
2181 Defaultness::Final => true,
2185 pub fn is_final(&self) -> bool {
2186 *self == Defaultness::Final
2189 pub fn is_default(&self) -> bool {
2191 Defaultness::Default { .. } => true,
2197 impl fmt::Display for Unsafety {
2198 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2199 f.write_str(match self {
2200 Unsafety::Normal => "normal",
2201 Unsafety::Unsafe => "unsafe",
2206 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2207 pub enum ImplPolarity {
2208 /// `impl Trait for Type`
2210 /// `impl !Trait for Type`
2214 impl fmt::Debug for ImplPolarity {
2215 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2216 f.write_str(match self {
2217 ImplPolarity::Positive => "positive",
2218 ImplPolarity::Negative => "negative",
2224 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2225 pub enum FunctionRetTy {
2226 /// Return type is not specified.
2228 /// Functions default to `()` and
2229 /// closures default to inference. Span points to where return
2230 /// type would be inserted.
2231 DefaultReturn(Span),
2232 /// Everything else.
2236 impl fmt::Display for FunctionRetTy {
2237 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2239 Return(ref ty) => print::to_string(print::NO_ANN, |s| s.print_type(ty)).fmt(f),
2240 DefaultReturn(_) => "()".fmt(f),
2245 impl FunctionRetTy {
2246 pub fn span(&self) -> Span {
2248 DefaultReturn(span) => span,
2249 Return(ref ty) => ty.span,
2254 #[derive(RustcEncodable, RustcDecodable, Debug)]
2256 /// A span from the first token past `{` to the last token until `}`.
2257 /// For `mod foo;`, the inner span ranges from the first token
2258 /// to the last token in the external file.
2260 pub item_ids: HirVec<ItemId>,
2263 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2264 pub struct ForeignMod {
2266 pub items: HirVec<ForeignItem>,
2269 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2270 pub struct GlobalAsm {
2274 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2275 pub struct EnumDef {
2276 pub variants: HirVec<Variant>,
2279 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2280 pub struct Variant {
2281 /// Name of the variant.
2282 #[stable_hasher(project(name))]
2284 /// Attributes of the variant.
2285 pub attrs: HirVec<Attribute>,
2286 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2288 /// Fields and constructor id of the variant.
2289 pub data: VariantData,
2290 /// Explicit discriminant (e.g., `Foo = 1`).
2291 pub disr_expr: Option<AnonConst>,
2296 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2298 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2299 /// Also produced for each element of a list `use`, e.g.
2300 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2303 /// Glob import, e.g., `use foo::*`.
2306 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2307 /// an additional `use foo::{}` for performing checks such as
2308 /// unstable feature gating. May be removed in the future.
2312 /// References to traits in impls.
2314 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2315 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2316 /// trait being referred to but just a unique `HirId` that serves as a key
2317 /// within the resolution map.
2318 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2319 pub struct TraitRef {
2321 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2322 #[stable_hasher(ignore)]
2323 pub hir_ref_id: HirId,
2327 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2328 pub fn trait_def_id(&self) -> DefId {
2329 match self.path.res {
2330 Res::Def(DefKind::Trait, did) => did,
2331 Res::Def(DefKind::TraitAlias, did) => did,
2335 _ => unreachable!(),
2340 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2341 pub struct PolyTraitRef {
2342 /// The `'a` in `<'a> Foo<&'a T>`.
2343 pub bound_generic_params: HirVec<GenericParam>,
2345 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2346 pub trait_ref: TraitRef,
2351 pub type Visibility = Spanned<VisibilityKind>;
2353 #[derive(RustcEncodable, RustcDecodable, Debug)]
2354 pub enum VisibilityKind {
2357 Restricted { path: P<Path>, hir_id: HirId },
2361 impl VisibilityKind {
2362 pub fn is_pub(&self) -> bool {
2364 VisibilityKind::Public => true,
2369 pub fn is_pub_restricted(&self) -> bool {
2371 VisibilityKind::Public |
2372 VisibilityKind::Inherited => false,
2373 VisibilityKind::Crate(..) |
2374 VisibilityKind::Restricted { .. } => true,
2378 pub fn descr(&self) -> &'static str {
2380 VisibilityKind::Public => "public",
2381 VisibilityKind::Inherited => "private",
2382 VisibilityKind::Crate(..) => "crate-visible",
2383 VisibilityKind::Restricted { .. } => "restricted",
2388 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2389 pub struct StructField {
2391 #[stable_hasher(project(name))]
2393 pub vis: Visibility,
2396 pub attrs: HirVec<Attribute>,
2400 // Still necessary in couple of places
2401 pub fn is_positional(&self) -> bool {
2402 let first = self.ident.as_str().as_bytes()[0];
2403 first >= b'0' && first <= b'9'
2407 /// Fields and constructor IDs of enum variants and structs.
2408 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2409 pub enum VariantData {
2410 /// A struct variant.
2412 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2413 Struct(HirVec<StructField>, /* recovered */ bool),
2414 /// A tuple variant.
2416 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2417 Tuple(HirVec<StructField>, HirId),
2420 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2425 /// Return the fields of this variant.
2426 pub fn fields(&self) -> &[StructField] {
2428 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2433 /// Return the `HirId` of this variant's constructor, if it has one.
2434 pub fn ctor_hir_id(&self) -> Option<HirId> {
2436 VariantData::Struct(_, _) => None,
2437 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2442 // The bodies for items are stored "out of line", in a separate
2443 // hashmap in the `Crate`. Here we just record the node-id of the item
2444 // so it can fetched later.
2445 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2452 /// The name might be a dummy name in case of anonymous items
2453 #[derive(RustcEncodable, RustcDecodable, Debug)]
2457 pub attrs: HirVec<Attribute>,
2459 pub vis: Visibility,
2463 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2464 pub struct FnHeader {
2465 pub unsafety: Unsafety,
2466 pub constness: Constness,
2467 pub asyncness: IsAsync,
2472 pub fn is_const(&self) -> bool {
2473 match &self.constness {
2474 Constness::Const => true,
2480 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2482 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2484 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2485 ExternCrate(Option<Name>),
2487 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2491 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2492 Use(P<Path>, UseKind),
2494 /// A `static` item.
2495 Static(P<Ty>, Mutability, BodyId),
2497 Const(P<Ty>, BodyId),
2498 /// A function declaration.
2499 Fn(P<FnDecl>, FnHeader, Generics, BodyId),
2502 /// An external module.
2503 ForeignMod(ForeignMod),
2504 /// Module-level inline assembly (from `global_asm!`).
2505 GlobalAsm(P<GlobalAsm>),
2506 /// A type alias, e.g., `type Foo = Bar<u8>`.
2507 TyAlias(P<Ty>, Generics),
2508 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2510 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2511 Enum(EnumDef, Generics),
2512 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2513 Struct(VariantData, Generics),
2514 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2515 Union(VariantData, Generics),
2516 /// A trait definition.
2517 Trait(IsAuto, Unsafety, Generics, GenericBounds, HirVec<TraitItemRef>),
2519 TraitAlias(Generics, GenericBounds),
2521 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2526 Option<TraitRef>, // (optional) trait this impl implements
2528 HirVec<ImplItemRef>),
2532 pub fn descriptive_variant(&self) -> &str {
2534 ItemKind::ExternCrate(..) => "extern crate",
2535 ItemKind::Use(..) => "use",
2536 ItemKind::Static(..) => "static item",
2537 ItemKind::Const(..) => "constant item",
2538 ItemKind::Fn(..) => "function",
2539 ItemKind::Mod(..) => "module",
2540 ItemKind::ForeignMod(..) => "foreign module",
2541 ItemKind::GlobalAsm(..) => "global asm",
2542 ItemKind::TyAlias(..) => "type alias",
2543 ItemKind::OpaqueTy(..) => "opaque type",
2544 ItemKind::Enum(..) => "enum",
2545 ItemKind::Struct(..) => "struct",
2546 ItemKind::Union(..) => "union",
2547 ItemKind::Trait(..) => "trait",
2548 ItemKind::TraitAlias(..) => "trait alias",
2549 ItemKind::Impl(..) => "impl",
2553 pub fn adt_kind(&self) -> Option<AdtKind> {
2555 ItemKind::Struct(..) => Some(AdtKind::Struct),
2556 ItemKind::Union(..) => Some(AdtKind::Union),
2557 ItemKind::Enum(..) => Some(AdtKind::Enum),
2562 pub fn generics(&self) -> Option<&Generics> {
2564 ItemKind::Fn(_, _, ref generics, _) |
2565 ItemKind::TyAlias(_, ref generics) |
2566 ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. }) |
2567 ItemKind::Enum(_, ref generics) |
2568 ItemKind::Struct(_, ref generics) |
2569 ItemKind::Union(_, ref generics) |
2570 ItemKind::Trait(_, _, ref generics, _, _) |
2571 ItemKind::Impl(_, _, _, ref generics, _, _, _)=> generics,
2577 /// A reference from an trait to one of its associated items. This
2578 /// contains the item's id, naturally, but also the item's name and
2579 /// some other high-level details (like whether it is an associated
2580 /// type or method, and whether it is public). This allows other
2581 /// passes to find the impl they want without loading the ID (which
2582 /// means fewer edges in the incremental compilation graph).
2583 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2584 pub struct TraitItemRef {
2585 pub id: TraitItemId,
2586 #[stable_hasher(project(name))]
2588 pub kind: AssocItemKind,
2590 pub defaultness: Defaultness,
2593 /// A reference from an impl to one of its associated items. This
2594 /// contains the item's ID, naturally, but also the item's name and
2595 /// some other high-level details (like whether it is an associated
2596 /// type or method, and whether it is public). This allows other
2597 /// passes to find the impl they want without loading the ID (which
2598 /// means fewer edges in the incremental compilation graph).
2599 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2600 pub struct ImplItemRef {
2602 #[stable_hasher(project(name))]
2604 pub kind: AssocItemKind,
2606 pub vis: Visibility,
2607 pub defaultness: Defaultness,
2610 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2611 pub enum AssocItemKind {
2613 Method { has_self: bool },
2618 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2619 pub struct ForeignItem {
2620 #[stable_hasher(project(name))]
2622 pub attrs: HirVec<Attribute>,
2623 pub kind: ForeignItemKind,
2626 pub vis: Visibility,
2629 /// An item within an `extern` block.
2630 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2631 pub enum ForeignItemKind {
2632 /// A foreign function.
2633 Fn(P<FnDecl>, HirVec<Ident>, Generics),
2634 /// A foreign static item (`static ext: u8`).
2635 Static(P<Ty>, Mutability),
2640 impl ForeignItemKind {
2641 pub fn descriptive_variant(&self) -> &str {
2643 ForeignItemKind::Fn(..) => "foreign function",
2644 ForeignItemKind::Static(..) => "foreign static item",
2645 ForeignItemKind::Type => "foreign type",
2650 /// A variable captured by a closure.
2651 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable, HashStable)]
2653 // First span where it is accessed (there can be multiple).
2657 pub type CaptureModeMap = NodeMap<CaptureClause>;
2659 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2660 // has length > 0 if the trait is found through an chain of imports, starting with the
2661 // import/use statement in the scope where the trait is used.
2662 #[derive(Clone, Debug)]
2663 pub struct TraitCandidate {
2665 pub import_ids: SmallVec<[NodeId; 1]>,
2668 // Trait method resolution
2669 pub type TraitMap = NodeMap<Vec<TraitCandidate>>;
2671 // Map from the NodeId of a glob import to a list of items which are actually
2673 pub type GlobMap = NodeMap<FxHashSet<Name>>;
2675 pub fn provide(providers: &mut Providers<'_>) {
2676 check_attr::provide(providers);
2677 map::provide(providers);
2678 upvars::provide(providers);
2681 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
2682 pub struct CodegenFnAttrs {
2683 pub flags: CodegenFnAttrFlags,
2684 /// Parsed representation of the `#[inline]` attribute
2685 pub inline: InlineAttr,
2686 /// Parsed representation of the `#[optimize]` attribute
2687 pub optimize: OptimizeAttr,
2688 /// The `#[export_name = "..."]` attribute, indicating a custom symbol a
2689 /// function should be exported under
2690 pub export_name: Option<Symbol>,
2691 /// The `#[link_name = "..."]` attribute, indicating a custom symbol an
2692 /// imported function should be imported as. Note that `export_name`
2693 /// probably isn't set when this is set, this is for foreign items while
2694 /// `#[export_name]` is for Rust-defined functions.
2695 pub link_name: Option<Symbol>,
2696 /// The `#[link_ordinal = "..."]` attribute, indicating an ordinal an
2697 /// imported function has in the dynamic library. Note that this must not
2698 /// be set when `link_name` is set. This is for foreign items with the
2699 /// "raw-dylib" kind.
2700 pub link_ordinal: Option<usize>,
2701 /// The `#[target_feature(enable = "...")]` attribute and the enabled
2702 /// features (only enabled features are supported right now).
2703 pub target_features: Vec<Symbol>,
2704 /// The `#[linkage = "..."]` attribute and the value we found.
2705 pub linkage: Option<Linkage>,
2706 /// The `#[link_section = "..."]` attribute, or what executable section this
2707 /// should be placed in.
2708 pub link_section: Option<Symbol>,
2712 #[derive(RustcEncodable, RustcDecodable, HashStable)]
2713 pub struct CodegenFnAttrFlags: u32 {
2714 /// `#[cold]`: a hint to LLVM that this function, when called, is never on
2716 const COLD = 1 << 0;
2717 /// `#[rustc_allocator]`: a hint to LLVM that the pointer returned from this
2718 /// function is never null.
2719 const ALLOCATOR = 1 << 1;
2720 /// `#[unwind]`: an indicator that this function may unwind despite what
2721 /// its ABI signature may otherwise imply.
2722 const UNWIND = 1 << 2;
2723 /// `#[rust_allocator_nounwind]`, an indicator that an imported FFI
2724 /// function will never unwind. Probably obsolete by recent changes with
2725 /// #[unwind], but hasn't been removed/migrated yet
2726 const RUSTC_ALLOCATOR_NOUNWIND = 1 << 3;
2727 /// `#[naked]`: an indicator to LLVM that no function prologue/epilogue
2728 /// should be generated.
2729 const NAKED = 1 << 4;
2730 /// `#[no_mangle]`: an indicator that the function's name should be the same
2732 const NO_MANGLE = 1 << 5;
2733 /// `#[rustc_std_internal_symbol]`: an indicator that this symbol is a
2734 /// "weird symbol" for the standard library in that it has slightly
2735 /// different linkage, visibility, and reachability rules.
2736 const RUSTC_STD_INTERNAL_SYMBOL = 1 << 6;
2737 /// `#[no_debug]`: an indicator that no debugging information should be
2738 /// generated for this function by LLVM.
2739 const NO_DEBUG = 1 << 7;
2740 /// `#[thread_local]`: indicates a static is actually a thread local
2742 const THREAD_LOCAL = 1 << 8;
2743 /// `#[used]`: indicates that LLVM can't eliminate this function (but the
2745 const USED = 1 << 9;
2746 /// #[ffi_returns_twice], indicates that an extern function can return
2748 const FFI_RETURNS_TWICE = 1 << 10;
2749 /// #[track_caller]: allow access to the caller location
2750 const TRACK_CALLER = 1 << 11;
2754 impl CodegenFnAttrs {
2755 pub fn new() -> CodegenFnAttrs {
2757 flags: CodegenFnAttrFlags::empty(),
2758 inline: InlineAttr::None,
2759 optimize: OptimizeAttr::None,
2763 target_features: vec![],
2769 /// Returns `true` if `#[inline]` or `#[inline(always)]` is present.
2770 pub fn requests_inline(&self) -> bool {
2772 InlineAttr::Hint | InlineAttr::Always => true,
2773 InlineAttr::None | InlineAttr::Never => false,
2777 /// Returns `true` if it looks like this symbol needs to be exported, for example:
2779 /// * `#[no_mangle]` is present
2780 /// * `#[export_name(...)]` is present
2781 /// * `#[linkage]` is present
2782 pub fn contains_extern_indicator(&self) -> bool {
2783 self.flags.contains(CodegenFnAttrFlags::NO_MANGLE) ||
2784 self.export_name.is_some() ||
2785 match self.linkage {
2786 // These are private, so make sure we don't try to consider
2789 Some(Linkage::Internal) |
2790 Some(Linkage::Private) => false,
2796 #[derive(Copy, Clone, Debug)]
2797 pub enum Node<'hir> {
2800 ForeignItem(&'hir ForeignItem),
2801 TraitItem(&'hir TraitItem),
2802 ImplItem(&'hir ImplItem),
2803 Variant(&'hir Variant),
2804 Field(&'hir StructField),
2805 AnonConst(&'hir AnonConst),
2808 PathSegment(&'hir PathSegment),
2810 TraitRef(&'hir TraitRef),
2816 MacroDef(&'hir MacroDef),
2818 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
2819 /// with synthesized constructors.
2820 Ctor(&'hir VariantData),
2822 Lifetime(&'hir Lifetime),
2823 GenericParam(&'hir GenericParam),
2824 Visibility(&'hir Visibility),
2830 pub fn ident(&self) -> Option<Ident> {
2832 Node::TraitItem(TraitItem { ident, .. }) |
2833 Node::ImplItem(ImplItem { ident, .. }) |
2834 Node::ForeignItem(ForeignItem { ident, .. }) |
2835 Node::Item(Item { ident, .. }) => Some(*ident),