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::FunctionRetTy::*;
7 pub use self::PrimTy::*;
9 pub use self::UnsafeSource::*;
11 use crate::hir::def::{Res, DefKind};
12 use crate::hir::def_id::{DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX};
13 use crate::hir::ptr::P;
14 use crate::mir::mono::Linkage;
15 use crate::ty::AdtKind;
16 use crate::ty::query::Providers;
17 use crate::util::nodemap::{NodeMap, FxHashSet};
19 use errors::FatalError;
20 use syntax_pos::{Span, DUMMY_SP, MultiSpan};
21 use syntax::source_map::Spanned;
22 use syntax::ast::{self, CrateSugar, Ident, Name, NodeId, AsmDialect};
23 use syntax::ast::{AttrVec, Attribute, Label, LitKind, StrStyle, FloatTy, IntTy, UintTy};
24 pub use syntax::ast::{Mutability, Constness, Unsafety, Movability, CaptureBy};
25 pub use syntax::ast::{IsAuto, ImplPolarity, BorrowKind};
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_macros::HashStable;
33 use rustc_serialize::{self, Encoder, Encodable, Decoder, Decodable};
34 use std::collections::{BTreeSet, BTreeMap};
36 use smallvec::SmallVec;
38 /// HIR doesn't commit to a concrete storage type and has its own alias for a vector.
39 /// It can be `Vec`, `P<[T]>` or potentially `Box<[T]>`, or some other container with similar
40 /// behavior. Unlike AST, HIR is mostly a static structure, so we can use an owned slice instead
41 /// of `Vec` to avoid keeping extra capacity.
42 pub type HirVec<T> = P<[T]>;
44 macro_rules! hir_vec {
45 ($elem:expr; $n:expr) => (
46 $crate::hir::HirVec::from(vec![$elem; $n])
49 $crate::hir::HirVec::from(vec![$($x),*])
57 pub mod itemlikevisit;
65 /// Uniquely identifies a node in the HIR of the current crate. It is
66 /// composed of the `owner`, which is the `DefIndex` of the directly enclosing
67 /// `hir::Item`, `hir::TraitItem`, or `hir::ImplItem` (i.e., the closest "item-like"),
68 /// and the `local_id` which is unique within the given owner.
70 /// This two-level structure makes for more stable values: One can move an item
71 /// around within the source code, or add or remove stuff before it, without
72 /// the `local_id` part of the `HirId` changing, which is a very useful property in
73 /// incremental compilation where we have to persist things through changes to
75 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)]
78 pub local_id: ItemLocalId,
82 pub fn owner_def_id(self) -> DefId {
83 DefId::local(self.owner)
86 pub fn owner_local_def_id(self) -> LocalDefId {
87 LocalDefId::from_def_id(DefId::local(self.owner))
91 impl rustc_serialize::UseSpecializedEncodable for HirId {
92 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
104 impl rustc_serialize::UseSpecializedDecodable for HirId {
105 fn default_decode<D: Decoder>(d: &mut D) -> Result<HirId, D::Error> {
106 let owner = DefIndex::decode(d)?;
107 let local_id = ItemLocalId::decode(d)?;
116 impl fmt::Display for HirId {
117 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118 write!(f, "{:?}", self)
122 // Hack to ensure that we don't try to access the private parts of `ItemLocalId` in this module.
123 mod item_local_id_inner {
124 use rustc_index::vec::Idx;
125 use rustc_macros::HashStable;
126 rustc_index::newtype_index! {
127 /// An `ItemLocalId` uniquely identifies something within a given "item-like";
128 /// that is, within a `hir::Item`, `hir::TraitItem`, or `hir::ImplItem`. There is no
129 /// guarantee that the numerical value of a given `ItemLocalId` corresponds to
130 /// the node's position within the owning item in any way, but there is a
131 /// guarantee that the `LocalItemId`s within an owner occupy a dense range of
132 /// integers starting at zero, so a mapping that maps all or most nodes within
133 /// an "item-like" to something else can be implemented by a `Vec` instead of a
134 /// tree or hash map.
135 pub struct ItemLocalId {
141 pub use self::item_local_id_inner::ItemLocalId;
143 /// The `HirId` corresponding to `CRATE_NODE_ID` and `CRATE_DEF_INDEX`.
144 pub const CRATE_HIR_ID: HirId = HirId {
145 owner: CRATE_DEF_INDEX,
146 local_id: ItemLocalId::from_u32_const(0)
149 pub const DUMMY_HIR_ID: HirId = HirId {
150 owner: CRATE_DEF_INDEX,
151 local_id: DUMMY_ITEM_LOCAL_ID,
154 pub const DUMMY_ITEM_LOCAL_ID: ItemLocalId = ItemLocalId::MAX;
156 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, HashStable)]
157 pub struct Lifetime {
161 /// Either "`'a`", referring to a named lifetime definition,
162 /// or "``" (i.e., `kw::Invalid`), for elision placeholders.
164 /// HIR lowering inserts these placeholders in type paths that
165 /// refer to type definitions needing lifetime parameters,
166 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
167 pub name: LifetimeName,
170 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy, HashStable)]
172 /// Some user-given name like `T` or `'x`.
175 /// Synthetic name generated when user elided a lifetime in an impl header.
177 /// E.g., the lifetimes in cases like these:
179 /// impl Foo for &u32
180 /// impl Foo<'_> for u32
182 /// in that case, we rewrite to
184 /// impl<'f> Foo for &'f u32
185 /// impl<'f> Foo<'f> for u32
187 /// where `'f` is something like `Fresh(0)`. The indices are
188 /// unique per impl, but not necessarily continuous.
191 /// Indicates an illegal name was given and an error has been
192 /// reported (so we should squelch other derived errors). Occurs
193 /// when, e.g., `'_` is used in the wrong place.
198 pub fn ident(&self) -> Ident {
200 ParamName::Plain(ident) => ident,
201 ParamName::Fresh(_) |
202 ParamName::Error => Ident::with_dummy_span(kw::UnderscoreLifetime),
206 pub fn modern(&self) -> ParamName {
208 ParamName::Plain(ident) => ParamName::Plain(ident.modern()),
209 param_name => param_name,
214 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy, HashStable)]
215 pub enum LifetimeName {
216 /// User-given names or fresh (synthetic) names.
219 /// User wrote nothing (e.g., the lifetime in `&u32`).
222 /// Implicit lifetime in a context like `dyn Foo`. This is
223 /// distinguished from implicit lifetimes elsewhere because the
224 /// lifetime that they default to must appear elsewhere within the
225 /// enclosing type. This means that, in an `impl Trait` context, we
226 /// don't have to create a parameter for them. That is, `impl
227 /// Trait<Item = &u32>` expands to an opaque type like `type
228 /// Foo<'a> = impl Trait<Item = &'a u32>`, but `impl Trait<item =
229 /// dyn Bar>` expands to `type Foo = impl Trait<Item = dyn Bar +
230 /// 'static>`. The latter uses `ImplicitObjectLifetimeDefault` so
231 /// that surrounding code knows not to create a lifetime
233 ImplicitObjectLifetimeDefault,
235 /// Indicates an error during lowering (usually `'_` in wrong place)
236 /// that was already reported.
239 /// User wrote specifies `'_`.
242 /// User wrote `'static`.
247 pub fn ident(&self) -> Ident {
249 LifetimeName::ImplicitObjectLifetimeDefault
250 | LifetimeName::Implicit
251 | LifetimeName::Error => Ident::invalid(),
252 LifetimeName::Underscore => Ident::with_dummy_span(kw::UnderscoreLifetime),
253 LifetimeName::Static => Ident::with_dummy_span(kw::StaticLifetime),
254 LifetimeName::Param(param_name) => param_name.ident(),
258 pub fn is_elided(&self) -> bool {
260 LifetimeName::ImplicitObjectLifetimeDefault
261 | LifetimeName::Implicit
262 | LifetimeName::Underscore => true,
264 // It might seem surprising that `Fresh(_)` counts as
265 // *not* elided -- but this is because, as far as the code
266 // in the compiler is concerned -- `Fresh(_)` variants act
267 // equivalently to "some fresh name". They correspond to
268 // early-bound regions on an impl, in other words.
269 LifetimeName::Error | LifetimeName::Param(_) | LifetimeName::Static => false,
273 fn is_static(&self) -> bool {
274 self == &LifetimeName::Static
277 pub fn modern(&self) -> LifetimeName {
279 LifetimeName::Param(param_name) => LifetimeName::Param(param_name.modern()),
280 lifetime_name => lifetime_name,
285 impl fmt::Display for Lifetime {
286 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
287 self.name.ident().fmt(f)
291 impl fmt::Debug for Lifetime {
292 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
296 print::to_string(print::NO_ANN, |s| s.print_lifetime(self)))
301 pub fn is_elided(&self) -> bool {
302 self.name.is_elided()
305 pub fn is_static(&self) -> bool {
306 self.name.is_static()
310 /// A `Path` is essentially Rust's notion of a name; for instance,
311 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
312 /// along with a bunch of supporting information.
313 #[derive(RustcEncodable, RustcDecodable, HashStable)]
316 /// The resolution for the path.
318 /// The segments in the path: the things separated by `::`.
319 pub segments: HirVec<PathSegment>,
323 pub fn is_global(&self) -> bool {
324 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
328 impl fmt::Debug for Path {
329 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
330 write!(f, "path({})", self)
334 impl fmt::Display for Path {
335 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
336 write!(f, "{}", print::to_string(print::NO_ANN, |s| s.print_path(self, false)))
340 /// A segment of a path: an identifier, an optional lifetime, and a set of
342 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
343 pub struct PathSegment {
344 /// The identifier portion of this path segment.
345 #[stable_hasher(project(name))]
347 // `id` and `res` are optional. We currently only use these in save-analysis,
348 // any path segments without these will not have save-analysis info and
349 // therefore will not have 'jump to def' in IDEs, but otherwise will not be
350 // affected. (In general, we don't bother to get the defs for synthesized
351 // segments, only for segments which have come from the AST).
352 pub hir_id: Option<HirId>,
353 pub res: Option<Res>,
355 /// Type/lifetime parameters attached to this path. They come in
356 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
357 /// this is more than just simple syntactic sugar; the use of
358 /// parens affects the region binding rules, so we preserve the
360 pub args: Option<P<GenericArgs>>,
362 /// Whether to infer remaining type parameters, if any.
363 /// This only applies to expression and pattern paths, and
364 /// out of those only the segments with no type parameters
365 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
366 pub infer_args: bool,
370 /// Converts an identifier to the corresponding segment.
371 pub fn from_ident(ident: Ident) -> PathSegment {
383 hir_id: Option<HirId>,
393 args: if args.is_empty() {
401 pub fn generic_args(&self) -> &GenericArgs {
402 if let Some(ref args) = self.args {
405 const DUMMY: &GenericArgs = &GenericArgs::none();
411 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
412 pub struct ConstArg {
413 pub value: AnonConst,
417 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
418 pub enum GenericArg {
425 pub fn span(&self) -> Span {
427 GenericArg::Lifetime(l) => l.span,
428 GenericArg::Type(t) => t.span,
429 GenericArg::Const(c) => c.span,
433 pub fn id(&self) -> HirId {
435 GenericArg::Lifetime(l) => l.hir_id,
436 GenericArg::Type(t) => t.hir_id,
437 GenericArg::Const(c) => c.value.hir_id,
441 pub fn is_const(&self) -> bool {
443 GenericArg::Const(_) => true,
449 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
450 pub struct GenericArgs {
451 /// The generic arguments for this path segment.
452 pub args: HirVec<GenericArg>,
453 /// Bindings (equality constraints) on associated types, if present.
454 /// E.g., `Foo<A = Bar>`.
455 pub bindings: HirVec<TypeBinding>,
456 /// Were arguments written in parenthesized form `Fn(T) -> U`?
457 /// This is required mostly for pretty-printing and diagnostics,
458 /// but also for changing lifetime elision rules to be "function-like".
459 pub parenthesized: bool,
463 pub const fn none() -> Self {
466 bindings: HirVec::new(),
467 parenthesized: false,
471 pub fn is_empty(&self) -> bool {
472 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
475 pub fn inputs(&self) -> &[Ty] {
476 if self.parenthesized {
477 for arg in &self.args {
479 GenericArg::Lifetime(_) => {}
480 GenericArg::Type(ref ty) => {
481 if let TyKind::Tup(ref tys) = ty.kind {
486 GenericArg::Const(_) => {}
490 bug!("GenericArgs::inputs: not a `Fn(T) -> U`");
493 pub fn own_counts(&self) -> GenericParamCount {
494 // We could cache this as a property of `GenericParamCount`, but
495 // the aim is to refactor this away entirely eventually and the
496 // presence of this method will be a constant reminder.
497 let mut own_counts: GenericParamCount = Default::default();
499 for arg in &self.args {
501 GenericArg::Lifetime(_) => own_counts.lifetimes += 1,
502 GenericArg::Type(_) => own_counts.types += 1,
503 GenericArg::Const(_) => own_counts.consts += 1,
511 /// A modifier on a bound, currently this is only used for `?Sized`, where the
512 /// modifier is `Maybe`. Negative bounds should also be handled here.
513 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
514 pub enum TraitBoundModifier {
519 /// The AST represents all type param bounds as types.
520 /// `typeck::collect::compute_bounds` matches these against
521 /// the "special" built-in traits (see `middle::lang_items`) and
522 /// detects `Copy`, `Send` and `Sync`.
523 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
524 pub enum GenericBound {
525 Trait(PolyTraitRef, TraitBoundModifier),
530 pub fn span(&self) -> Span {
532 &GenericBound::Trait(ref t, ..) => t.span,
533 &GenericBound::Outlives(ref l) => l.span,
538 pub type GenericBounds = HirVec<GenericBound>;
540 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable)]
541 pub enum LifetimeParamKind {
542 // Indicates that the lifetime definition was explicitly declared (e.g., in
543 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
546 // Indicates that the lifetime definition was synthetically added
547 // as a result of an in-band lifetime usage (e.g., in
548 // `fn foo(x: &'a u8) -> &'a u8 { x }`).
551 // Indication that the lifetime was elided (e.g., in both cases in
552 // `fn foo(x: &u8) -> &'_ u8 { x }`).
555 // Indication that the lifetime name was somehow in error.
559 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
560 pub enum GenericParamKind {
561 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
563 kind: LifetimeParamKind,
566 default: Option<P<Ty>>,
567 synthetic: Option<SyntheticTyParamKind>,
574 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
575 pub struct GenericParam {
578 pub attrs: HirVec<Attribute>,
579 pub bounds: GenericBounds,
581 pub pure_wrt_drop: bool,
582 pub kind: GenericParamKind,
586 pub struct GenericParamCount {
587 pub lifetimes: usize,
592 /// Represents lifetimes and type parameters attached to a declaration
593 /// of a function, enum, trait, etc.
594 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
595 pub struct Generics {
596 pub params: HirVec<GenericParam>,
597 pub where_clause: WhereClause,
602 pub const fn empty() -> Generics {
604 params: HirVec::new(),
605 where_clause: WhereClause {
606 predicates: HirVec::new(),
613 pub fn own_counts(&self) -> GenericParamCount {
614 // We could cache this as a property of `GenericParamCount`, but
615 // the aim is to refactor this away entirely eventually and the
616 // presence of this method will be a constant reminder.
617 let mut own_counts: GenericParamCount = Default::default();
619 for param in &self.params {
621 GenericParamKind::Lifetime { .. } => own_counts.lifetimes += 1,
622 GenericParamKind::Type { .. } => own_counts.types += 1,
623 GenericParamKind::Const { .. } => own_counts.consts += 1,
630 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam> {
631 for param in &self.params {
632 if name == param.name.ident().name {
639 pub fn spans(&self) -> MultiSpan {
640 if self.params.is_empty() {
643 self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
648 /// Synthetic type parameters are converted to another form during lowering; this allows
649 /// us to track the original form they had, and is useful for error messages.
650 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
651 pub enum SyntheticTyParamKind {
655 /// A where-clause in a definition.
656 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
657 pub struct WhereClause {
658 pub predicates: HirVec<WherePredicate>,
659 // Only valid if predicates isn't empty.
664 pub fn span(&self) -> Option<Span> {
665 if self.predicates.is_empty() {
672 /// The `WhereClause` under normal circumstances points at either the predicates or the empty
673 /// space where the `where` clause should be. Only of use for diagnostic suggestions.
674 pub fn span_for_predicates_or_empty_place(&self) -> Span {
679 /// A single predicate in a where-clause.
680 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
681 pub enum WherePredicate {
682 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
683 BoundPredicate(WhereBoundPredicate),
684 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
685 RegionPredicate(WhereRegionPredicate),
686 /// An equality predicate (unsupported).
687 EqPredicate(WhereEqPredicate),
690 impl WherePredicate {
691 pub fn span(&self) -> Span {
693 &WherePredicate::BoundPredicate(ref p) => p.span,
694 &WherePredicate::RegionPredicate(ref p) => p.span,
695 &WherePredicate::EqPredicate(ref p) => p.span,
700 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
701 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
702 pub struct WhereBoundPredicate {
704 /// Any generics from a `for` binding.
705 pub bound_generic_params: HirVec<GenericParam>,
706 /// The type being bounded.
707 pub bounded_ty: P<Ty>,
708 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
709 pub bounds: GenericBounds,
712 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
713 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
714 pub struct WhereRegionPredicate {
716 pub lifetime: Lifetime,
717 pub bounds: GenericBounds,
720 /// An equality predicate (e.g., `T = int`); currently unsupported.
721 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
722 pub struct WhereEqPredicate {
729 #[derive(RustcEncodable, RustcDecodable, Debug)]
730 pub struct ModuleItems {
731 // Use BTreeSets here so items are in the same order as in the
732 // list of all items in Crate
733 pub items: BTreeSet<HirId>,
734 pub trait_items: BTreeSet<TraitItemId>,
735 pub impl_items: BTreeSet<ImplItemId>,
738 /// The top-level data structure that stores the entire contents of
739 /// the crate currently being compiled.
741 /// For more details, see the [rustc guide].
743 /// [rustc guide]: https://rust-lang.github.io/rustc-guide/hir.html
744 #[derive(RustcEncodable, RustcDecodable, Debug)]
745 pub struct Crate<'hir> {
747 pub attrs: &'hir [Attribute],
749 pub exported_macros: &'hir [MacroDef<'hir>],
750 // Attributes from non-exported macros, kept only for collecting the library feature list.
751 pub non_exported_macro_attrs: &'hir [Attribute],
753 // N.B., we use a `BTreeMap` here so that `visit_all_items` iterates
754 // over the ids in increasing order. In principle it should not
755 // matter what order we visit things in, but in *practice* it
756 // does, because it can affect the order in which errors are
757 // detected, which in turn can make compile-fail tests yield
758 // slightly different results.
759 pub items: BTreeMap<HirId, Item<'hir>>,
761 pub trait_items: BTreeMap<TraitItemId, TraitItem<'hir>>,
762 pub impl_items: BTreeMap<ImplItemId, ImplItem<'hir>>,
763 pub bodies: BTreeMap<BodyId, Body>,
764 pub trait_impls: BTreeMap<DefId, Vec<HirId>>,
766 /// A list of the body ids written out in the order in which they
767 /// appear in the crate. If you're going to process all the bodies
768 /// in the crate, you should iterate over this list rather than the keys
770 pub body_ids: Vec<BodyId>,
772 /// A list of modules written out in the order in which they
773 /// appear in the crate. This includes the main crate module.
774 pub modules: BTreeMap<HirId, ModuleItems>,
778 pub fn item(&self, id: HirId) -> &Item<'hir> {
782 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem<'hir> {
783 &self.trait_items[&id]
786 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem<'hir> {
787 &self.impl_items[&id]
790 pub fn body(&self, id: BodyId) -> &Body {
796 /// Visits all items in the crate in some deterministic (but
797 /// unspecified) order. If you just need to process every item,
798 /// but don't care about nesting, this method is the best choice.
800 /// If you do care about nesting -- usually because your algorithm
801 /// follows lexical scoping rules -- then you want a different
802 /// approach. You should override `visit_nested_item` in your
803 /// visitor and then call `intravisit::walk_crate` instead.
804 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
805 where V: itemlikevisit::ItemLikeVisitor<'hir>
807 for (_, item) in &self.items {
808 visitor.visit_item(item);
811 for (_, trait_item) in &self.trait_items {
812 visitor.visit_trait_item(trait_item);
815 for (_, impl_item) in &self.impl_items {
816 visitor.visit_impl_item(impl_item);
820 /// A parallel version of `visit_all_item_likes`.
821 pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
822 where V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send
825 par_for_each_in(&self.items, |(_, item)| {
826 visitor.visit_item(item);
829 par_for_each_in(&self.trait_items, |(_, trait_item)| {
830 visitor.visit_trait_item(trait_item);
833 par_for_each_in(&self.impl_items, |(_, impl_item)| {
834 visitor.visit_impl_item(impl_item);
840 /// A macro definition, in this crate or imported from another.
842 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
843 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
844 pub struct MacroDef<'hir> {
847 pub attrs: &'hir [Attribute],
850 pub body: TokenStream,
854 /// A block of statements `{ .. }`, which may have a label (in this case the
855 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
856 /// the `rules` being anything but `DefaultBlock`.
857 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
859 /// Statements in a block.
860 pub stmts: HirVec<Stmt>,
861 /// An expression at the end of the block
862 /// without a semicolon, if any.
863 pub expr: Option<P<Expr>>,
864 #[stable_hasher(ignore)]
866 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
867 pub rules: BlockCheckMode,
869 /// If true, then there may exist `break 'a` values that aim to
870 /// break out of this block early.
871 /// Used by `'label: {}` blocks and by `try {}` blocks.
872 pub targeted_by_break: bool,
875 #[derive(RustcEncodable, RustcDecodable, HashStable)]
877 #[stable_hasher(ignore)]
883 impl fmt::Debug for Pat {
884 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
885 write!(f, "pat({}: {})", self.hir_id,
886 print::to_string(print::NO_ANN, |s| s.print_pat(self)))
891 // FIXME(#19596) this is a workaround, but there should be a better way
892 fn walk_short_(&self, it: &mut impl FnMut(&Pat) -> bool) -> bool {
899 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
900 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
901 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
902 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
903 Slice(before, slice, after) => {
907 .all(|p| p.walk_short_(it))
912 /// Walk the pattern in left-to-right order,
913 /// short circuiting (with `.all(..)`) if `false` is returned.
915 /// Note that when visiting e.g. `Tuple(ps)`,
916 /// if visiting `ps[0]` returns `false`,
917 /// then `ps[1]` will not be visited.
918 pub fn walk_short(&self, mut it: impl FnMut(&Pat) -> bool) -> bool {
919 self.walk_short_(&mut it)
922 // FIXME(#19596) this is a workaround, but there should be a better way
923 fn walk_(&self, it: &mut impl FnMut(&Pat) -> bool) {
930 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {},
931 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
932 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
933 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
934 Slice(before, slice, after) => {
938 .for_each(|p| p.walk_(it))
943 /// Walk the pattern in left-to-right order.
945 /// If `it(pat)` returns `false`, the children are not visited.
946 pub fn walk(&self, mut it: impl FnMut(&Pat) -> bool) {
951 /// A single field in a struct pattern.
953 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
954 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
955 /// except `is_shorthand` is true.
956 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
957 pub struct FieldPat {
958 #[stable_hasher(ignore)]
960 /// The identifier for the field.
961 #[stable_hasher(project(name))]
963 /// The pattern the field is destructured to.
965 pub is_shorthand: bool,
969 /// Explicit binding annotations given in the HIR for a binding. Note
970 /// that this is not the final binding *mode* that we infer after type
972 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
973 pub enum BindingAnnotation {
974 /// No binding annotation given: this means that the final binding mode
975 /// will depend on whether we have skipped through a `&` reference
976 /// when matching. For example, the `x` in `Some(x)` will have binding
977 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
978 /// ultimately be inferred to be by-reference.
980 /// Note that implicit reference skipping is not implemented yet (#42640).
983 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
986 /// Annotated as `ref`, like `ref x`
989 /// Annotated as `ref mut x`.
993 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
999 impl fmt::Display for RangeEnd {
1000 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1001 f.write_str(match self {
1002 RangeEnd::Included => "..=",
1003 RangeEnd::Excluded => "..",
1008 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1010 /// Represents a wildcard pattern (i.e., `_`).
1013 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
1014 /// The `HirId` is the canonical ID for the variable being bound,
1015 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
1016 /// which is the pattern ID of the first `x`.
1017 Binding(BindingAnnotation, HirId, Ident, Option<P<Pat>>),
1019 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
1020 /// The `bool` is `true` in the presence of a `..`.
1021 Struct(QPath, HirVec<FieldPat>, bool),
1023 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
1024 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
1025 /// `0 <= position <= subpats.len()`
1026 TupleStruct(QPath, HirVec<P<Pat>>, Option<usize>),
1028 /// An or-pattern `A | B | C`.
1029 /// Invariant: `pats.len() >= 2`.
1032 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
1035 /// A tuple pattern (e.g., `(a, b)`).
1036 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
1037 /// `0 <= position <= subpats.len()`
1038 Tuple(HirVec<P<Pat>>, Option<usize>),
1040 /// A `box` pattern.
1043 /// A reference pattern (e.g., `&mut (a, b)`).
1044 Ref(P<Pat>, Mutability),
1049 /// A range pattern (e.g., `1..=2` or `1..2`).
1050 Range(P<Expr>, P<Expr>, RangeEnd),
1052 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
1054 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
1055 /// If `slice` exists, then `after` can be non-empty.
1057 /// The representation for e.g., `[a, b, .., c, d]` is:
1059 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
1061 Slice(HirVec<P<Pat>>, Option<P<Pat>>, HirVec<P<Pat>>),
1064 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1065 pub enum BinOpKind {
1066 /// The `+` operator (addition).
1068 /// The `-` operator (subtraction).
1070 /// The `*` operator (multiplication).
1072 /// The `/` operator (division).
1074 /// The `%` operator (modulus).
1076 /// The `&&` operator (logical and).
1078 /// The `||` operator (logical or).
1080 /// The `^` operator (bitwise xor).
1082 /// The `&` operator (bitwise and).
1084 /// The `|` operator (bitwise or).
1086 /// The `<<` operator (shift left).
1088 /// The `>>` operator (shift right).
1090 /// The `==` operator (equality).
1092 /// The `<` operator (less than).
1094 /// The `<=` operator (less than or equal to).
1096 /// The `!=` operator (not equal to).
1098 /// The `>=` operator (greater than or equal to).
1100 /// The `>` operator (greater than).
1105 pub fn as_str(self) -> &'static str {
1107 BinOpKind::Add => "+",
1108 BinOpKind::Sub => "-",
1109 BinOpKind::Mul => "*",
1110 BinOpKind::Div => "/",
1111 BinOpKind::Rem => "%",
1112 BinOpKind::And => "&&",
1113 BinOpKind::Or => "||",
1114 BinOpKind::BitXor => "^",
1115 BinOpKind::BitAnd => "&",
1116 BinOpKind::BitOr => "|",
1117 BinOpKind::Shl => "<<",
1118 BinOpKind::Shr => ">>",
1119 BinOpKind::Eq => "==",
1120 BinOpKind::Lt => "<",
1121 BinOpKind::Le => "<=",
1122 BinOpKind::Ne => "!=",
1123 BinOpKind::Ge => ">=",
1124 BinOpKind::Gt => ">",
1128 pub fn is_lazy(self) -> bool {
1130 BinOpKind::And | BinOpKind::Or => true,
1135 pub fn is_shift(self) -> bool {
1137 BinOpKind::Shl | BinOpKind::Shr => true,
1142 pub fn is_comparison(self) -> bool {
1149 BinOpKind::Ge => true,
1161 BinOpKind::Shr => false,
1165 /// Returns `true` if the binary operator takes its arguments by value.
1166 pub fn is_by_value(self) -> bool {
1167 !self.is_comparison()
1171 impl Into<ast::BinOpKind> for BinOpKind {
1172 fn into(self) -> ast::BinOpKind {
1174 BinOpKind::Add => ast::BinOpKind::Add,
1175 BinOpKind::Sub => ast::BinOpKind::Sub,
1176 BinOpKind::Mul => ast::BinOpKind::Mul,
1177 BinOpKind::Div => ast::BinOpKind::Div,
1178 BinOpKind::Rem => ast::BinOpKind::Rem,
1179 BinOpKind::And => ast::BinOpKind::And,
1180 BinOpKind::Or => ast::BinOpKind::Or,
1181 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1182 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1183 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1184 BinOpKind::Shl => ast::BinOpKind::Shl,
1185 BinOpKind::Shr => ast::BinOpKind::Shr,
1186 BinOpKind::Eq => ast::BinOpKind::Eq,
1187 BinOpKind::Lt => ast::BinOpKind::Lt,
1188 BinOpKind::Le => ast::BinOpKind::Le,
1189 BinOpKind::Ne => ast::BinOpKind::Ne,
1190 BinOpKind::Ge => ast::BinOpKind::Ge,
1191 BinOpKind::Gt => ast::BinOpKind::Gt,
1196 pub type BinOp = Spanned<BinOpKind>;
1198 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1200 /// The `*` operator (deferencing).
1202 /// The `!` operator (logical negation).
1204 /// The `-` operator (negation).
1209 pub fn as_str(self) -> &'static str {
1217 /// Returns `true` if the unary operator takes its argument by value.
1218 pub fn is_by_value(self) -> bool {
1220 UnNeg | UnNot => true,
1227 #[derive(RustcEncodable, RustcDecodable, HashStable)]
1234 impl fmt::Debug for Stmt {
1235 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1236 write!(f, "stmt({}: {})", self.hir_id,
1237 print::to_string(print::NO_ANN, |s| s.print_stmt(self)))
1241 /// The contents of a statement.
1242 #[derive(RustcEncodable, RustcDecodable, HashStable)]
1244 /// A local (`let`) binding.
1247 /// An item binding.
1250 /// An expression without a trailing semi-colon (must have unit type).
1253 /// An expression with a trailing semi-colon (may have any type).
1258 pub fn attrs(&self) -> &[Attribute] {
1260 StmtKind::Local(ref l) => &l.attrs,
1261 StmtKind::Item(_) => &[],
1262 StmtKind::Expr(ref e) |
1263 StmtKind::Semi(ref e) => &e.attrs,
1268 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1269 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1272 /// Type annotation, if any (otherwise the type will be inferred).
1273 pub ty: Option<P<Ty>>,
1274 /// Initializer expression to set the value, if any.
1275 pub init: Option<P<Expr>>,
1279 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1280 /// desugaring. Otherwise will be `Normal`.
1281 pub source: LocalSource,
1284 /// Represents a single arm of a `match` expression, e.g.
1285 /// `<pat> (if <guard>) => <body>`.
1286 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1288 #[stable_hasher(ignore)]
1291 pub attrs: HirVec<Attribute>,
1292 /// If this pattern and the optional guard matches, then `body` is evaluated.
1294 /// Optional guard clause.
1295 pub guard: Option<Guard>,
1296 /// The expression the arm evaluates to if this arm matches.
1300 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1305 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1307 #[stable_hasher(ignore)]
1312 pub is_shorthand: bool,
1315 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1316 pub enum BlockCheckMode {
1318 UnsafeBlock(UnsafeSource),
1319 PushUnsafeBlock(UnsafeSource),
1320 PopUnsafeBlock(UnsafeSource),
1323 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1324 pub enum UnsafeSource {
1329 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1334 /// The body of a function, closure, or constant value. In the case of
1335 /// a function, the body contains not only the function body itself
1336 /// (which is an expression), but also the argument patterns, since
1337 /// those are something that the caller doesn't really care about.
1342 /// fn foo((x, y): (u32, u32)) -> u32 {
1347 /// Here, the `Body` associated with `foo()` would contain:
1349 /// - an `params` array containing the `(x, y)` pattern
1350 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1351 /// - `generator_kind` would be `None`
1353 /// All bodies have an **owner**, which can be accessed via the HIR
1354 /// map using `body_owner_def_id()`.
1355 #[derive(RustcEncodable, RustcDecodable, Debug)]
1357 pub params: HirVec<Param>,
1359 pub generator_kind: Option<GeneratorKind>,
1363 pub fn id(&self) -> BodyId {
1365 hir_id: self.value.hir_id,
1369 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1374 /// The type of source expression that caused this generator to be created.
1375 #[derive(Clone, PartialEq, Eq, HashStable, RustcEncodable, RustcDecodable, Debug, Copy)]
1376 pub enum GeneratorKind {
1377 /// An explicit `async` block or the body of an async function.
1378 Async(AsyncGeneratorKind),
1380 /// A generator literal created via a `yield` inside a closure.
1384 impl fmt::Display for GeneratorKind {
1385 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1387 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1388 GeneratorKind::Gen => f.write_str("generator"),
1393 /// In the case of a generator created as part of an async construct,
1394 /// which kind of async construct caused it to be created?
1396 /// This helps error messages but is also used to drive coercions in
1397 /// type-checking (see #60424).
1398 #[derive(Clone, PartialEq, Eq, HashStable, RustcEncodable, RustcDecodable, Debug, Copy)]
1399 pub enum AsyncGeneratorKind {
1400 /// An explicit `async` block written by the user.
1403 /// An explicit `async` block written by the user.
1406 /// The `async` block generated as the body of an async function.
1410 impl fmt::Display for AsyncGeneratorKind {
1411 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1412 f.write_str(match self {
1413 AsyncGeneratorKind::Block => "`async` block",
1414 AsyncGeneratorKind::Closure => "`async` closure body",
1415 AsyncGeneratorKind::Fn => "`async fn` body",
1420 #[derive(Copy, Clone, Debug)]
1421 pub enum BodyOwnerKind {
1422 /// Functions and methods.
1428 /// Constants and associated constants.
1431 /// Initializer of a `static` item.
1435 impl BodyOwnerKind {
1436 pub fn is_fn_or_closure(self) -> bool {
1438 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1439 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1445 pub type Lit = Spanned<LitKind>;
1447 /// A constant (expression) that's not an item or associated item,
1448 /// but needs its own `DefId` for type-checking, const-eval, etc.
1449 /// These are usually found nested inside types (e.g., array lengths)
1450 /// or expressions (e.g., repeat counts), and also used to define
1451 /// explicit discriminant values for enum variants.
1452 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1453 pub struct AnonConst {
1459 #[derive(RustcEncodable, RustcDecodable)]
1467 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1468 #[cfg(target_arch = "x86_64")]
1469 static_assert_size!(Expr, 64);
1472 pub fn precedence(&self) -> ExprPrecedence {
1474 ExprKind::Box(_) => ExprPrecedence::Box,
1475 ExprKind::Array(_) => ExprPrecedence::Array,
1476 ExprKind::Call(..) => ExprPrecedence::Call,
1477 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1478 ExprKind::Tup(_) => ExprPrecedence::Tup,
1479 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1480 ExprKind::Unary(..) => ExprPrecedence::Unary,
1481 ExprKind::Lit(_) => ExprPrecedence::Lit,
1482 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1483 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1484 ExprKind::Loop(..) => ExprPrecedence::Loop,
1485 ExprKind::Match(..) => ExprPrecedence::Match,
1486 ExprKind::Closure(..) => ExprPrecedence::Closure,
1487 ExprKind::Block(..) => ExprPrecedence::Block,
1488 ExprKind::Assign(..) => ExprPrecedence::Assign,
1489 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1490 ExprKind::Field(..) => ExprPrecedence::Field,
1491 ExprKind::Index(..) => ExprPrecedence::Index,
1492 ExprKind::Path(..) => ExprPrecedence::Path,
1493 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1494 ExprKind::Break(..) => ExprPrecedence::Break,
1495 ExprKind::Continue(..) => ExprPrecedence::Continue,
1496 ExprKind::Ret(..) => ExprPrecedence::Ret,
1497 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1498 ExprKind::Struct(..) => ExprPrecedence::Struct,
1499 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1500 ExprKind::Yield(..) => ExprPrecedence::Yield,
1501 ExprKind::Err => ExprPrecedence::Err,
1505 // Whether this looks like a place expr, without checking for deref
1507 // This will return `true` in some potentially surprising cases such as
1508 // `CONSTANT.field`.
1509 pub fn is_syntactic_place_expr(&self) -> bool {
1510 self.is_place_expr(|_| true)
1513 // Whether this is a place expression.
1514 // `allow_projections_from` should return `true` if indexing a field or
1515 // index expression based on the given expression should be considered a
1516 // place expression.
1517 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1519 ExprKind::Path(QPath::Resolved(_, ref path)) => {
1522 | Res::Def(DefKind::Static, _)
1528 // Type ascription inherits its place expression kind from its
1530 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1531 ExprKind::Type(ref e, _) => {
1532 e.is_place_expr(allow_projections_from)
1535 ExprKind::Unary(UnDeref, _) => true,
1537 ExprKind::Field(ref base, _) |
1538 ExprKind::Index(ref base, _) => {
1539 allow_projections_from(base)
1540 || base.is_place_expr(allow_projections_from)
1543 // Partially qualified paths in expressions can only legally
1544 // refer to associated items which are always rvalues.
1545 ExprKind::Path(QPath::TypeRelative(..)) |
1547 ExprKind::Call(..) |
1548 ExprKind::MethodCall(..) |
1549 ExprKind::Struct(..) |
1551 ExprKind::Match(..) |
1552 ExprKind::Closure(..) |
1553 ExprKind::Block(..) |
1554 ExprKind::Repeat(..) |
1555 ExprKind::Array(..) |
1556 ExprKind::Break(..) |
1557 ExprKind::Continue(..) |
1559 ExprKind::Loop(..) |
1560 ExprKind::Assign(..) |
1561 ExprKind::InlineAsm(..) |
1562 ExprKind::AssignOp(..) |
1564 ExprKind::Unary(..) |
1566 ExprKind::AddrOf(..) |
1567 ExprKind::Binary(..) |
1568 ExprKind::Yield(..) |
1569 ExprKind::Cast(..) |
1570 ExprKind::DropTemps(..) |
1577 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1578 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1579 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1580 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1581 /// beyond remembering to call this function before doing analysis on it.
1582 pub fn peel_drop_temps(&self) -> &Self {
1583 let mut expr = self;
1584 while let ExprKind::DropTemps(inner) = &expr.kind {
1591 impl fmt::Debug for Expr {
1592 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1593 write!(f, "expr({}: {})", self.hir_id,
1594 print::to_string(print::NO_ANN, |s| s.print_expr(self)))
1598 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1600 /// A `box x` expression.
1602 /// An array (e.g., `[a, b, c, d]`).
1603 Array(HirVec<Expr>),
1604 /// A function call.
1606 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1607 /// and the second field is the list of arguments.
1608 /// This also represents calling the constructor of
1609 /// tuple-like ADTs such as tuple structs and enum variants.
1610 Call(P<Expr>, HirVec<Expr>),
1611 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1613 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1614 /// (within the angle brackets).
1615 /// The first element of the vector of `Expr`s is the expression that evaluates
1616 /// to the object on which the method is being called on (the receiver),
1617 /// and the remaining elements are the rest of the arguments.
1618 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1619 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1621 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1622 /// the `hir_id` of the `MethodCall` node itself.
1624 /// [`type_dependent_def_id`]: ../ty/struct.TypeckTables.html#method.type_dependent_def_id
1625 MethodCall(P<PathSegment>, Span, HirVec<Expr>),
1626 /// A tuple (e.g., `(a, b, c, d)`).
1628 /// A binary operation (e.g., `a + b`, `a * b`).
1629 Binary(BinOp, P<Expr>, P<Expr>),
1630 /// A unary operation (e.g., `!x`, `*x`).
1631 Unary(UnOp, P<Expr>),
1632 /// A literal (e.g., `1`, `"foo"`).
1634 /// A cast (e.g., `foo as f64`).
1635 Cast(P<Expr>, P<Ty>),
1636 /// A type reference (e.g., `Foo`).
1637 Type(P<Expr>, P<Ty>),
1638 /// Wraps the expression in a terminating scope.
1639 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1641 /// This construct only exists to tweak the drop order in HIR lowering.
1642 /// An example of that is the desugaring of `for` loops.
1644 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1646 /// I.e., `'label: loop { <block> }`.
1647 Loop(P<Block>, Option<Label>, LoopSource),
1648 /// A `match` block, with a source that indicates whether or not it is
1649 /// the result of a desugaring, and if so, which kind.
1650 Match(P<Expr>, HirVec<Arm>, MatchSource),
1651 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1653 /// The `Span` is the argument block `|...|`.
1655 /// This may also be a generator literal or an `async block` as indicated by the
1656 /// `Option<Movability>`.
1657 Closure(CaptureBy, P<FnDecl>, BodyId, Span, Option<Movability>),
1658 /// A block (e.g., `'label: { ... }`).
1659 Block(P<Block>, Option<Label>),
1661 /// An assignment (e.g., `a = foo()`).
1662 Assign(P<Expr>, P<Expr>),
1663 /// An assignment with an operator.
1666 AssignOp(BinOp, P<Expr>, P<Expr>),
1667 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1668 Field(P<Expr>, Ident),
1669 /// An indexing operation (`foo[2]`).
1670 Index(P<Expr>, P<Expr>),
1672 /// Path to a definition, possibly containing lifetime or type parameters.
1675 /// A referencing operation (i.e., `&a`, `&mut a`, `&raw const a`, or `&raw mut a`).
1676 AddrOf(BorrowKind, Mutability, P<Expr>),
1677 /// A `break`, with an optional label to break.
1678 Break(Destination, Option<P<Expr>>),
1679 /// A `continue`, with an optional label.
1680 Continue(Destination),
1681 /// A `return`, with an optional value to be returned.
1682 Ret(Option<P<Expr>>),
1684 /// Inline assembly (from `asm!`), with its outputs and inputs.
1685 InlineAsm(P<InlineAsm>),
1687 /// A struct or struct-like variant literal expression.
1689 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1690 /// where `base` is the `Option<Expr>`.
1691 Struct(P<QPath>, HirVec<Field>, Option<P<Expr>>),
1693 /// An array literal constructed from one repeated element.
1695 /// E.g., `[1; 5]`. The first expression is the element
1696 /// to be repeated; the second is the number of times to repeat it.
1697 Repeat(P<Expr>, AnonConst),
1699 /// A suspension point for generators (i.e., `yield <expr>`).
1700 Yield(P<Expr>, YieldSource),
1702 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1706 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1708 /// To resolve the path to a `DefId`, call [`qpath_res`].
1710 /// [`qpath_res`]: ../ty/struct.TypeckTables.html#method.qpath_res
1711 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1713 /// Path to a definition, optionally "fully-qualified" with a `Self`
1714 /// type, if the path points to an associated item in a trait.
1716 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1717 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1718 /// even though they both have the same two-segment `Clone::clone` `Path`.
1719 Resolved(Option<P<Ty>>, P<Path>),
1721 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1722 /// Will be resolved by type-checking to an associated item.
1724 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1725 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1726 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1727 TypeRelative(P<Ty>, P<PathSegment>)
1730 /// Hints at the original code for a let statement.
1731 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1732 pub enum LocalSource {
1733 /// A `match _ { .. }`.
1735 /// A desugared `for _ in _ { .. }` loop.
1737 /// When lowering async functions, we create locals within the `async move` so that
1738 /// all parameters are dropped after the future is polled.
1740 /// ```ignore (pseudo-Rust)
1741 /// async fn foo(<pattern> @ x: Type) {
1743 /// let <pattern> = x;
1748 /// A desugared `<expr>.await`.
1752 /// Hints at the original code for a `match _ { .. }`.
1753 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
1754 pub enum MatchSource {
1755 /// A `match _ { .. }`.
1757 /// An `if _ { .. }` (optionally with `else { .. }`).
1759 contains_else_clause: bool,
1761 /// An `if let _ = _ { .. }` (optionally with `else { .. }`).
1763 contains_else_clause: bool,
1765 /// A `while _ { .. }` (which was desugared to a `loop { match _ { .. } }`).
1767 /// A `while let _ = _ { .. }` (which was desugared to a
1768 /// `loop { match _ { .. } }`).
1770 /// A desugared `for _ in _ { .. }` loop.
1772 /// A desugared `?` operator.
1774 /// A desugared `<expr>.await`.
1779 pub fn name(self) -> &'static str {
1783 IfDesugar { .. } | IfLetDesugar { .. } => "if",
1784 WhileDesugar | WhileLetDesugar => "while",
1785 ForLoopDesugar => "for",
1787 AwaitDesugar => ".await",
1792 /// The loop type that yielded an `ExprKind::Loop`.
1793 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1794 pub enum LoopSource {
1795 /// A `loop { .. }` loop.
1797 /// A `while _ { .. }` loop.
1799 /// A `while let _ = _ { .. }` loop.
1801 /// A `for _ in _ { .. }` loop.
1806 pub fn name(self) -> &'static str {
1808 LoopSource::Loop => "loop",
1809 LoopSource::While | LoopSource::WhileLet => "while",
1810 LoopSource::ForLoop => "for",
1815 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1816 pub enum LoopIdError {
1818 UnlabeledCfInWhileCondition,
1822 impl fmt::Display for LoopIdError {
1823 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1824 f.write_str(match self {
1825 LoopIdError::OutsideLoopScope => "not inside loop scope",
1826 LoopIdError::UnlabeledCfInWhileCondition =>
1827 "unlabeled control flow (break or continue) in while condition",
1828 LoopIdError::UnresolvedLabel => "label not found",
1833 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1834 pub struct Destination {
1835 // This is `Some(_)` iff there is an explicit user-specified `label
1836 pub label: Option<Label>,
1838 // These errors are caught and then reported during the diagnostics pass in
1839 // librustc_passes/loops.rs
1840 pub target_id: Result<HirId, LoopIdError>,
1843 /// The yield kind that caused an `ExprKind::Yield`.
1844 #[derive(Copy, Clone, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable, HashStable)]
1845 pub enum YieldSource {
1846 /// An `<expr>.await`.
1848 /// A plain `yield`.
1852 impl fmt::Display for YieldSource {
1853 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1854 f.write_str(match self {
1855 YieldSource::Await => "`await`",
1856 YieldSource::Yield => "`yield`",
1861 impl From<GeneratorKind> for YieldSource {
1862 fn from(kind: GeneratorKind) -> Self {
1864 // Guess based on the kind of the current generator.
1865 GeneratorKind::Gen => Self::Yield,
1866 GeneratorKind::Async(_) => Self::Await,
1871 // N.B., if you change this, you'll probably want to change the corresponding
1872 // type structure in middle/ty.rs as well.
1873 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1876 pub mutbl: Mutability,
1879 /// Represents a function's signature in a trait declaration,
1880 /// trait implementation, or a free function.
1881 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1883 pub header: FnHeader,
1884 pub decl: P<FnDecl>,
1887 // The bodies for items are stored "out of line", in a separate
1888 // hashmap in the `Crate`. Here we just record the node-id of the item
1889 // so it can fetched later.
1890 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1891 pub struct TraitItemId {
1895 /// Represents an item declaration within a trait declaration,
1896 /// possibly including a default implementation. A trait item is
1897 /// either required (meaning it doesn't have an implementation, just a
1898 /// signature) or provided (meaning it has a default implementation).
1899 #[derive(RustcEncodable, RustcDecodable, Debug)]
1900 pub struct TraitItem<'hir> {
1903 pub attrs: &'hir [Attribute],
1904 pub generics: Generics,
1905 pub kind: TraitItemKind<'hir>,
1909 /// Represents a trait method's body (or just argument names).
1910 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1911 pub enum TraitMethod {
1912 /// No default body in the trait, just a signature.
1913 Required(HirVec<Ident>),
1915 /// Both signature and body are provided in the trait.
1919 /// Represents a trait method or associated constant or type
1920 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1921 pub enum TraitItemKind<'hir> {
1922 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
1923 Const(&'hir Ty, Option<BodyId>),
1924 /// A method with an optional body.
1925 Method(FnSig, TraitMethod),
1926 /// An associated type with (possibly empty) bounds and optional concrete
1928 Type(GenericBounds, Option<&'hir Ty>),
1931 // The bodies for items are stored "out of line", in a separate
1932 // hashmap in the `Crate`. Here we just record the node-id of the item
1933 // so it can fetched later.
1934 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1935 pub struct ImplItemId {
1939 /// Represents anything within an `impl` block.
1940 #[derive(RustcEncodable, RustcDecodable, Debug)]
1941 pub struct ImplItem<'hir> {
1944 pub vis: Visibility,
1945 pub defaultness: Defaultness,
1946 pub attrs: &'hir [Attribute],
1947 pub generics: Generics,
1948 pub kind: ImplItemKind<'hir>,
1952 /// Represents various kinds of content within an `impl`.
1953 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1954 pub enum ImplItemKind<'hir> {
1955 /// An associated constant of the given type, set to the constant result
1956 /// of the expression.
1957 Const(&'hir Ty, BodyId),
1958 /// A method implementation with the given signature and body.
1959 Method(FnSig, BodyId),
1960 /// An associated type.
1962 /// An associated `type = impl Trait`.
1963 OpaqueTy(GenericBounds),
1966 /// Bind a type to an associated type (i.e., `A = Foo`).
1968 /// Bindings like `A: Debug` are represented as a special type `A =
1969 /// $::Debug` that is understood by the astconv code.
1971 /// FIXME(alexreg): why have a separate type for the binding case,
1972 /// wouldn't it be better to make the `ty` field an enum like the
1976 /// enum TypeBindingKind {
1981 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1982 pub struct TypeBinding {
1984 #[stable_hasher(project(name))]
1986 pub kind: TypeBindingKind,
1990 // Represents the two kinds of type bindings.
1991 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1992 pub enum TypeBindingKind {
1993 /// E.g., `Foo<Bar: Send>`.
1995 bounds: HirVec<GenericBound>,
1997 /// E.g., `Foo<Bar = ()>`.
2004 pub fn ty(&self) -> &Ty {
2006 TypeBindingKind::Equality { ref ty } => ty,
2007 _ => bug!("expected equality type binding for parenthesized generic args"),
2012 #[derive(RustcEncodable, RustcDecodable)]
2019 impl fmt::Debug for Ty {
2020 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2021 write!(f, "type({})",
2022 print::to_string(print::NO_ANN, |s| s.print_type(self)))
2026 /// Not represented directly in the AST; referred to by name through a `ty_path`.
2027 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
2037 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2038 pub struct BareFnTy {
2039 pub unsafety: Unsafety,
2041 pub generic_params: HirVec<GenericParam>,
2042 pub decl: P<FnDecl>,
2043 pub param_names: HirVec<Ident>,
2046 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2047 pub struct OpaqueTy {
2048 pub generics: Generics,
2049 pub bounds: GenericBounds,
2050 pub impl_trait_fn: Option<DefId>,
2051 pub origin: OpaqueTyOrigin,
2054 /// From whence the opaque type came.
2055 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2056 pub enum OpaqueTyOrigin {
2057 /// `type Foo = impl Trait;`
2065 /// The various kinds of types recognized by the compiler.
2066 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2068 /// A variable length slice (i.e., `[T]`).
2070 /// A fixed length array (i.e., `[T; n]`).
2071 Array(P<Ty>, AnonConst),
2072 /// A raw pointer (i.e., `*const T` or `*mut T`).
2074 /// A reference (i.e., `&'a T` or `&'a mut T`).
2075 Rptr(Lifetime, MutTy),
2076 /// A bare function (e.g., `fn(usize) -> bool`).
2077 BareFn(P<BareFnTy>),
2078 /// The never type (`!`).
2080 /// A tuple (`(A, B, C, D, ...)`).
2082 /// A path to a type definition (`module::module::...::Type`), or an
2083 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2085 /// Type parameters may be stored in each `PathSegment`.
2087 /// A type definition itself. This is currently only used for the `type Foo = impl Trait`
2088 /// item that `impl Trait` in return position desugars to.
2090 /// The generic argument list contains the lifetimes (and in the future possibly parameters)
2091 /// that are actually bound on the `impl Trait`.
2092 Def(ItemId, HirVec<GenericArg>),
2093 /// A trait object type `Bound1 + Bound2 + Bound3`
2094 /// where `Bound` is a trait or a lifetime.
2095 TraitObject(HirVec<PolyTraitRef>, Lifetime),
2098 /// `TyKind::Infer` means the type should be inferred instead of it having been
2099 /// specified. This can appear anywhere in a type.
2101 /// Placeholder for a type that has failed to be defined.
2105 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable, PartialEq)]
2106 pub struct InlineAsmOutput {
2107 pub constraint: Symbol,
2109 pub is_indirect: bool,
2113 // NOTE(eddyb) This is used within MIR as well, so unlike the rest of the HIR,
2114 // it needs to be `Clone` and use plain `Vec<T>` instead of `HirVec<T>`.
2115 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable, PartialEq)]
2116 pub struct InlineAsmInner {
2118 pub asm_str_style: StrStyle,
2119 pub outputs: Vec<InlineAsmOutput>,
2120 pub inputs: Vec<Symbol>,
2121 pub clobbers: Vec<Symbol>,
2123 pub alignstack: bool,
2124 pub dialect: AsmDialect,
2127 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2128 pub struct InlineAsm {
2129 pub inner: InlineAsmInner,
2130 pub outputs_exprs: HirVec<Expr>,
2131 pub inputs_exprs: HirVec<Expr>,
2134 /// Represents a parameter in a function header.
2135 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2137 pub attrs: HirVec<Attribute>,
2143 /// Represents the header (not the body) of a function declaration.
2144 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2146 /// The types of the function's parameters.
2148 /// Additional argument data is stored in the function's [body](Body::parameters).
2149 pub inputs: HirVec<Ty>,
2150 pub output: FunctionRetTy,
2151 pub c_variadic: bool,
2152 /// Does the function have an implicit self?
2153 pub implicit_self: ImplicitSelfKind,
2156 /// Represents what type of implicit self a function has, if any.
2157 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2158 pub enum ImplicitSelfKind {
2159 /// Represents a `fn x(self);`.
2161 /// Represents a `fn x(mut self);`.
2163 /// Represents a `fn x(&self);`.
2165 /// Represents a `fn x(&mut self);`.
2167 /// Represents when a function does not have a self argument or
2168 /// when a function has a `self: X` argument.
2172 impl ImplicitSelfKind {
2173 /// Does this represent an implicit self?
2174 pub fn has_implicit_self(&self) -> bool {
2176 ImplicitSelfKind::None => false,
2182 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, HashStable,
2183 Ord, RustcEncodable, RustcDecodable, Debug)]
2189 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2190 pub enum Defaultness {
2191 Default { has_value: bool },
2196 pub fn has_value(&self) -> bool {
2198 Defaultness::Default { has_value, .. } => has_value,
2199 Defaultness::Final => true,
2203 pub fn is_final(&self) -> bool {
2204 *self == Defaultness::Final
2207 pub fn is_default(&self) -> bool {
2209 Defaultness::Default { .. } => true,
2215 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2216 pub enum FunctionRetTy {
2217 /// Return type is not specified.
2219 /// Functions default to `()` and
2220 /// closures default to inference. Span points to where return
2221 /// type would be inserted.
2222 DefaultReturn(Span),
2223 /// Everything else.
2227 impl fmt::Display for FunctionRetTy {
2228 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2230 Return(ref ty) => print::to_string(print::NO_ANN, |s| s.print_type(ty)).fmt(f),
2231 DefaultReturn(_) => "()".fmt(f),
2236 impl FunctionRetTy {
2237 pub fn span(&self) -> Span {
2239 DefaultReturn(span) => span,
2240 Return(ref ty) => ty.span,
2245 #[derive(RustcEncodable, RustcDecodable, Debug)]
2247 /// A span from the first token past `{` to the last token until `}`.
2248 /// For `mod foo;`, the inner span ranges from the first token
2249 /// to the last token in the external file.
2251 pub item_ids: HirVec<ItemId>,
2254 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2255 pub struct ForeignMod<'hir> {
2257 pub items: &'hir [ForeignItem<'hir>],
2260 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2261 pub struct GlobalAsm {
2265 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2266 pub struct EnumDef<'hir> {
2267 pub variants: &'hir [Variant<'hir>],
2270 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2271 pub struct Variant<'hir> {
2272 /// Name of the variant.
2273 #[stable_hasher(project(name))]
2275 /// Attributes of the variant.
2276 pub attrs: &'hir [Attribute],
2277 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2279 /// Fields and constructor id of the variant.
2280 pub data: VariantData<'hir>,
2281 /// Explicit discriminant (e.g., `Foo = 1`).
2282 pub disr_expr: Option<AnonConst>,
2287 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2289 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2290 /// Also produced for each element of a list `use`, e.g.
2291 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2294 /// Glob import, e.g., `use foo::*`.
2297 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2298 /// an additional `use foo::{}` for performing checks such as
2299 /// unstable feature gating. May be removed in the future.
2303 /// References to traits in impls.
2305 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2306 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2307 /// trait being referred to but just a unique `HirId` that serves as a key
2308 /// within the resolution map.
2309 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2310 pub struct TraitRef {
2312 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2313 #[stable_hasher(ignore)]
2314 pub hir_ref_id: HirId,
2318 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2319 pub fn trait_def_id(&self) -> DefId {
2320 match self.path.res {
2321 Res::Def(DefKind::Trait, did) => did,
2322 Res::Def(DefKind::TraitAlias, did) => did,
2326 _ => unreachable!(),
2331 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2332 pub struct PolyTraitRef {
2333 /// The `'a` in `<'a> Foo<&'a T>`.
2334 pub bound_generic_params: HirVec<GenericParam>,
2336 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2337 pub trait_ref: TraitRef,
2342 pub type Visibility = Spanned<VisibilityKind>;
2344 #[derive(RustcEncodable, RustcDecodable, Debug)]
2345 pub enum VisibilityKind {
2348 Restricted { path: P<Path>, hir_id: HirId },
2352 impl VisibilityKind {
2353 pub fn is_pub(&self) -> bool {
2355 VisibilityKind::Public => true,
2360 pub fn is_pub_restricted(&self) -> bool {
2362 VisibilityKind::Public |
2363 VisibilityKind::Inherited => false,
2364 VisibilityKind::Crate(..) |
2365 VisibilityKind::Restricted { .. } => true,
2369 pub fn descr(&self) -> &'static str {
2371 VisibilityKind::Public => "public",
2372 VisibilityKind::Inherited => "private",
2373 VisibilityKind::Crate(..) => "crate-visible",
2374 VisibilityKind::Restricted { .. } => "restricted",
2379 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2380 pub struct StructField {
2382 #[stable_hasher(project(name))]
2384 pub vis: Visibility,
2387 pub attrs: HirVec<Attribute>,
2391 // Still necessary in couple of places
2392 pub fn is_positional(&self) -> bool {
2393 let first = self.ident.as_str().as_bytes()[0];
2394 first >= b'0' && first <= b'9'
2398 /// Fields and constructor IDs of enum variants and structs.
2399 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2400 pub enum VariantData<'hir> {
2401 /// A struct variant.
2403 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2404 Struct(&'hir [StructField], /* recovered */ bool),
2405 /// A tuple variant.
2407 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2408 Tuple(&'hir [StructField], HirId),
2411 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2415 impl VariantData<'hir> {
2416 /// Return the fields of this variant.
2417 pub fn fields(&self) -> &'hir [StructField] {
2419 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2424 /// Return the `HirId` of this variant's constructor, if it has one.
2425 pub fn ctor_hir_id(&self) -> Option<HirId> {
2427 VariantData::Struct(_, _) => None,
2428 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2433 // The bodies for items are stored "out of line", in a separate
2434 // hashmap in the `Crate`. Here we just record the node-id of the item
2435 // so it can fetched later.
2436 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2443 /// The name might be a dummy name in case of anonymous items
2444 #[derive(RustcEncodable, RustcDecodable, Debug)]
2445 pub struct Item<'hir> {
2448 pub attrs: &'hir [Attribute],
2449 pub kind: ItemKind<'hir>,
2450 pub vis: Visibility,
2454 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2455 pub struct FnHeader {
2456 pub unsafety: Unsafety,
2457 pub constness: Constness,
2458 pub asyncness: IsAsync,
2463 pub fn is_const(&self) -> bool {
2464 match &self.constness {
2465 Constness::Const => true,
2471 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2472 pub enum ItemKind<'hir> {
2473 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2475 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2476 ExternCrate(Option<Name>),
2478 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2482 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2483 Use(&'hir Path, UseKind),
2485 /// A `static` item.
2486 Static(&'hir Ty, Mutability, BodyId),
2488 Const(&'hir Ty, BodyId),
2489 /// A function declaration.
2490 Fn(FnSig, Generics, BodyId),
2493 /// An external module, e.g. `extern { .. }`.
2494 ForeignMod(ForeignMod<'hir>),
2495 /// Module-level inline assembly (from `global_asm!`).
2496 GlobalAsm(&'hir GlobalAsm),
2497 /// A type alias, e.g., `type Foo = Bar<u8>`.
2498 TyAlias(&'hir Ty, Generics),
2499 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2501 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2502 Enum(EnumDef<'hir>, Generics),
2503 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2504 Struct(VariantData<'hir>, Generics),
2505 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2506 Union(VariantData<'hir>, Generics),
2507 /// A trait definition.
2508 Trait(IsAuto, Unsafety, Generics, GenericBounds, &'hir [TraitItemRef]),
2510 TraitAlias(Generics, GenericBounds),
2512 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2517 Option<TraitRef>, // (optional) trait this impl implements
2519 &'hir [ImplItemRef]),
2523 pub fn descriptive_variant(&self) -> &str {
2525 ItemKind::ExternCrate(..) => "extern crate",
2526 ItemKind::Use(..) => "use",
2527 ItemKind::Static(..) => "static item",
2528 ItemKind::Const(..) => "constant item",
2529 ItemKind::Fn(..) => "function",
2530 ItemKind::Mod(..) => "module",
2531 ItemKind::ForeignMod(..) => "foreign module",
2532 ItemKind::GlobalAsm(..) => "global asm",
2533 ItemKind::TyAlias(..) => "type alias",
2534 ItemKind::OpaqueTy(..) => "opaque type",
2535 ItemKind::Enum(..) => "enum",
2536 ItemKind::Struct(..) => "struct",
2537 ItemKind::Union(..) => "union",
2538 ItemKind::Trait(..) => "trait",
2539 ItemKind::TraitAlias(..) => "trait alias",
2540 ItemKind::Impl(..) => "impl",
2544 pub fn adt_kind(&self) -> Option<AdtKind> {
2546 ItemKind::Struct(..) => Some(AdtKind::Struct),
2547 ItemKind::Union(..) => Some(AdtKind::Union),
2548 ItemKind::Enum(..) => Some(AdtKind::Enum),
2553 pub fn generics(&self) -> Option<&Generics> {
2555 ItemKind::Fn(_, ref generics, _) |
2556 ItemKind::TyAlias(_, ref generics) |
2557 ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. }) |
2558 ItemKind::Enum(_, ref generics) |
2559 ItemKind::Struct(_, ref generics) |
2560 ItemKind::Union(_, ref generics) |
2561 ItemKind::Trait(_, _, ref generics, _, _) |
2562 ItemKind::Impl(_, _, _, ref generics, _, _, _)=> generics,
2568 /// A reference from an trait to one of its associated items. This
2569 /// contains the item's id, naturally, but also the item's name and
2570 /// some other high-level details (like whether it is an associated
2571 /// type or method, and whether it is public). This allows other
2572 /// passes to find the impl they want without loading the ID (which
2573 /// means fewer edges in the incremental compilation graph).
2574 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2575 pub struct TraitItemRef {
2576 pub id: TraitItemId,
2577 #[stable_hasher(project(name))]
2579 pub kind: AssocItemKind,
2581 pub defaultness: Defaultness,
2584 /// A reference from an impl to one of its associated items. This
2585 /// contains the item's ID, naturally, but also the item's name and
2586 /// some other high-level details (like whether it is an associated
2587 /// type or method, and whether it is public). This allows other
2588 /// passes to find the impl they want without loading the ID (which
2589 /// means fewer edges in the incremental compilation graph).
2590 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2591 pub struct ImplItemRef {
2593 #[stable_hasher(project(name))]
2595 pub kind: AssocItemKind,
2597 pub vis: Visibility,
2598 pub defaultness: Defaultness,
2601 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2602 pub enum AssocItemKind {
2604 Method { has_self: bool },
2609 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2610 pub struct ForeignItem<'hir> {
2611 #[stable_hasher(project(name))]
2613 pub attrs: &'hir [Attribute],
2614 pub kind: ForeignItemKind<'hir>,
2617 pub vis: Visibility,
2620 /// An item within an `extern` block.
2621 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2622 pub enum ForeignItemKind<'hir> {
2623 /// A foreign function.
2624 Fn(&'hir FnDecl, &'hir [Ident], Generics),
2625 /// A foreign static item (`static ext: u8`).
2626 Static(&'hir Ty, Mutability),
2631 impl ForeignItemKind<'hir> {
2632 pub fn descriptive_variant(&self) -> &str {
2634 ForeignItemKind::Fn(..) => "foreign function",
2635 ForeignItemKind::Static(..) => "foreign static item",
2636 ForeignItemKind::Type => "foreign type",
2641 /// A variable captured by a closure.
2642 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable, HashStable)]
2644 // First span where it is accessed (there can be multiple).
2648 pub type CaptureModeMap = NodeMap<CaptureBy>;
2650 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2651 // has length > 0 if the trait is found through an chain of imports, starting with the
2652 // import/use statement in the scope where the trait is used.
2653 #[derive(Clone, Debug)]
2654 pub struct TraitCandidate {
2656 pub import_ids: SmallVec<[NodeId; 1]>,
2659 // Trait method resolution
2660 pub type TraitMap = NodeMap<Vec<TraitCandidate>>;
2662 // Map from the NodeId of a glob import to a list of items which are actually
2664 pub type GlobMap = NodeMap<FxHashSet<Name>>;
2666 pub fn provide(providers: &mut Providers<'_>) {
2667 check_attr::provide(providers);
2668 map::provide(providers);
2669 upvars::provide(providers);
2672 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
2673 pub struct CodegenFnAttrs {
2674 pub flags: CodegenFnAttrFlags,
2675 /// Parsed representation of the `#[inline]` attribute
2676 pub inline: InlineAttr,
2677 /// Parsed representation of the `#[optimize]` attribute
2678 pub optimize: OptimizeAttr,
2679 /// The `#[export_name = "..."]` attribute, indicating a custom symbol a
2680 /// function should be exported under
2681 pub export_name: Option<Symbol>,
2682 /// The `#[link_name = "..."]` attribute, indicating a custom symbol an
2683 /// imported function should be imported as. Note that `export_name`
2684 /// probably isn't set when this is set, this is for foreign items while
2685 /// `#[export_name]` is for Rust-defined functions.
2686 pub link_name: Option<Symbol>,
2687 /// The `#[link_ordinal = "..."]` attribute, indicating an ordinal an
2688 /// imported function has in the dynamic library. Note that this must not
2689 /// be set when `link_name` is set. This is for foreign items with the
2690 /// "raw-dylib" kind.
2691 pub link_ordinal: Option<usize>,
2692 /// The `#[target_feature(enable = "...")]` attribute and the enabled
2693 /// features (only enabled features are supported right now).
2694 pub target_features: Vec<Symbol>,
2695 /// The `#[linkage = "..."]` attribute and the value we found.
2696 pub linkage: Option<Linkage>,
2697 /// The `#[link_section = "..."]` attribute, or what executable section this
2698 /// should be placed in.
2699 pub link_section: Option<Symbol>,
2703 #[derive(RustcEncodable, RustcDecodable, HashStable)]
2704 pub struct CodegenFnAttrFlags: u32 {
2705 /// `#[cold]`: a hint to LLVM that this function, when called, is never on
2707 const COLD = 1 << 0;
2708 /// `#[rustc_allocator]`: a hint to LLVM that the pointer returned from this
2709 /// function is never null.
2710 const ALLOCATOR = 1 << 1;
2711 /// `#[unwind]`: an indicator that this function may unwind despite what
2712 /// its ABI signature may otherwise imply.
2713 const UNWIND = 1 << 2;
2714 /// `#[rust_allocator_nounwind]`, an indicator that an imported FFI
2715 /// function will never unwind. Probably obsolete by recent changes with
2716 /// #[unwind], but hasn't been removed/migrated yet
2717 const RUSTC_ALLOCATOR_NOUNWIND = 1 << 3;
2718 /// `#[naked]`: an indicator to LLVM that no function prologue/epilogue
2719 /// should be generated.
2720 const NAKED = 1 << 4;
2721 /// `#[no_mangle]`: an indicator that the function's name should be the same
2723 const NO_MANGLE = 1 << 5;
2724 /// `#[rustc_std_internal_symbol]`: an indicator that this symbol is a
2725 /// "weird symbol" for the standard library in that it has slightly
2726 /// different linkage, visibility, and reachability rules.
2727 const RUSTC_STD_INTERNAL_SYMBOL = 1 << 6;
2728 /// `#[no_debug]`: an indicator that no debugging information should be
2729 /// generated for this function by LLVM.
2730 const NO_DEBUG = 1 << 7;
2731 /// `#[thread_local]`: indicates a static is actually a thread local
2733 const THREAD_LOCAL = 1 << 8;
2734 /// `#[used]`: indicates that LLVM can't eliminate this function (but the
2736 const USED = 1 << 9;
2737 /// `#[ffi_returns_twice]`, indicates that an extern function can return
2739 const FFI_RETURNS_TWICE = 1 << 10;
2740 /// `#[track_caller]`: allow access to the caller location
2741 const TRACK_CALLER = 1 << 11;
2745 impl CodegenFnAttrs {
2746 pub fn new() -> CodegenFnAttrs {
2748 flags: CodegenFnAttrFlags::empty(),
2749 inline: InlineAttr::None,
2750 optimize: OptimizeAttr::None,
2754 target_features: vec![],
2760 /// Returns `true` if `#[inline]` or `#[inline(always)]` is present.
2761 pub fn requests_inline(&self) -> bool {
2763 InlineAttr::Hint | InlineAttr::Always => true,
2764 InlineAttr::None | InlineAttr::Never => false,
2768 /// Returns `true` if it looks like this symbol needs to be exported, for example:
2770 /// * `#[no_mangle]` is present
2771 /// * `#[export_name(...)]` is present
2772 /// * `#[linkage]` is present
2773 pub fn contains_extern_indicator(&self) -> bool {
2774 self.flags.contains(CodegenFnAttrFlags::NO_MANGLE) ||
2775 self.export_name.is_some() ||
2776 match self.linkage {
2777 // These are private, so make sure we don't try to consider
2780 Some(Linkage::Internal) |
2781 Some(Linkage::Private) => false,
2787 #[derive(Copy, Clone, Debug)]
2788 pub enum Node<'hir> {
2790 Item(&'hir Item<'hir>),
2791 ForeignItem(&'hir ForeignItem<'hir>),
2792 TraitItem(&'hir TraitItem<'hir>),
2793 ImplItem(&'hir ImplItem<'hir>),
2794 Variant(&'hir Variant<'hir>),
2795 Field(&'hir StructField),
2796 AnonConst(&'hir AnonConst),
2799 PathSegment(&'hir PathSegment),
2801 TraitRef(&'hir TraitRef),
2807 MacroDef(&'hir MacroDef<'hir>),
2809 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
2810 /// with synthesized constructors.
2811 Ctor(&'hir VariantData<'hir>),
2813 Lifetime(&'hir Lifetime),
2814 GenericParam(&'hir GenericParam),
2815 Visibility(&'hir Visibility),
2821 pub fn ident(&self) -> Option<Ident> {
2823 Node::TraitItem(TraitItem { ident, .. }) |
2824 Node::ImplItem(ImplItem { ident, .. }) |
2825 Node::ForeignItem(ForeignItem { ident, .. }) |
2826 Node::Item(Item { ident, .. }) => Some(*ident),