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::{Attribute, Label, LitKind, StrStyle, FloatTy, IntTy, UintTy};
24 pub use syntax::ast::{Mutability, Constness, Unsafety, Movability, CaptureBy, IsAuto, ImplPolarity};
25 use syntax::attr::{InlineAttr, OptimizeAttr};
26 use syntax::symbol::{Symbol, kw};
27 use syntax::tokenstream::TokenStream;
28 use syntax::util::parser::ExprPrecedence;
29 use rustc_target::spec::abi::Abi;
30 use rustc_data_structures::sync::{par_for_each_in, Send, Sync};
31 use rustc_data_structures::thin_vec::ThinVec;
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)]
747 pub attrs: HirVec<Attribute>,
749 pub exported_macros: HirVec<MacroDef>,
750 // Attributes from non-exported macros, kept only for collecting the library feature list.
751 pub non_exported_macro_attrs: HirVec<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>,
761 pub trait_items: BTreeMap<TraitItemId, TraitItem>,
762 pub impl_items: BTreeMap<ImplItemId, ImplItem>,
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 {
782 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem {
783 &self.trait_items[&id]
786 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem {
787 &self.impl_items[&id]
790 /// Visits all items in the crate in some deterministic (but
791 /// unspecified) order. If you just need to process every item,
792 /// but don't care about nesting, this method is the best choice.
794 /// If you do care about nesting -- usually because your algorithm
795 /// follows lexical scoping rules -- then you want a different
796 /// approach. You should override `visit_nested_item` in your
797 /// visitor and then call `intravisit::walk_crate` instead.
798 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
799 where V: itemlikevisit::ItemLikeVisitor<'hir>
801 for (_, item) in &self.items {
802 visitor.visit_item(item);
805 for (_, trait_item) in &self.trait_items {
806 visitor.visit_trait_item(trait_item);
809 for (_, impl_item) in &self.impl_items {
810 visitor.visit_impl_item(impl_item);
814 /// A parallel version of `visit_all_item_likes`.
815 pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
816 where V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send
819 par_for_each_in(&self.items, |(_, item)| {
820 visitor.visit_item(item);
823 par_for_each_in(&self.trait_items, |(_, trait_item)| {
824 visitor.visit_trait_item(trait_item);
827 par_for_each_in(&self.impl_items, |(_, impl_item)| {
828 visitor.visit_impl_item(impl_item);
833 pub fn body(&self, id: BodyId) -> &Body {
838 /// A macro definition, in this crate or imported from another.
840 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
841 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
842 pub struct MacroDef {
845 pub attrs: HirVec<Attribute>,
848 pub body: TokenStream,
852 /// A block of statements `{ .. }`, which may have a label (in this case the
853 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
854 /// the `rules` being anything but `DefaultBlock`.
855 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
857 /// Statements in a block.
858 pub stmts: HirVec<Stmt>,
859 /// An expression at the end of the block
860 /// without a semicolon, if any.
861 pub expr: Option<P<Expr>>,
862 #[stable_hasher(ignore)]
864 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
865 pub rules: BlockCheckMode,
867 /// If true, then there may exist `break 'a` values that aim to
868 /// break out of this block early.
869 /// Used by `'label: {}` blocks and by `try {}` blocks.
870 pub targeted_by_break: bool,
873 #[derive(RustcEncodable, RustcDecodable, HashStable)]
875 #[stable_hasher(ignore)]
881 impl fmt::Debug for Pat {
882 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
883 write!(f, "pat({}: {})", self.hir_id,
884 print::to_string(print::NO_ANN, |s| s.print_pat(self)))
889 // FIXME(#19596) this is a workaround, but there should be a better way
890 fn walk_short_(&self, it: &mut impl FnMut(&Pat) -> bool) -> bool {
897 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
898 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
899 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
900 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
901 Slice(before, slice, after) => {
905 .all(|p| p.walk_short_(it))
910 /// Walk the pattern in left-to-right order,
911 /// short circuiting (with `.all(..)`) if `false` is returned.
913 /// Note that when visiting e.g. `Tuple(ps)`,
914 /// if visiting `ps[0]` returns `false`,
915 /// then `ps[1]` will not be visited.
916 pub fn walk_short(&self, mut it: impl FnMut(&Pat) -> bool) -> bool {
917 self.walk_short_(&mut it)
920 // FIXME(#19596) this is a workaround, but there should be a better way
921 fn walk_(&self, it: &mut impl FnMut(&Pat) -> bool) {
928 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {},
929 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
930 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
931 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
932 Slice(before, slice, after) => {
936 .for_each(|p| p.walk_(it))
941 /// Walk the pattern in left-to-right order.
943 /// If `it(pat)` returns `false`, the children are not visited.
944 pub fn walk(&self, mut it: impl FnMut(&Pat) -> bool) {
949 /// A single field in a struct pattern.
951 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
952 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
953 /// except `is_shorthand` is true.
954 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
955 pub struct FieldPat {
956 #[stable_hasher(ignore)]
958 /// The identifier for the field.
959 #[stable_hasher(project(name))]
961 /// The pattern the field is destructured to.
963 pub is_shorthand: bool,
967 /// Explicit binding annotations given in the HIR for a binding. Note
968 /// that this is not the final binding *mode* that we infer after type
970 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
971 pub enum BindingAnnotation {
972 /// No binding annotation given: this means that the final binding mode
973 /// will depend on whether we have skipped through a `&` reference
974 /// when matching. For example, the `x` in `Some(x)` will have binding
975 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
976 /// ultimately be inferred to be by-reference.
978 /// Note that implicit reference skipping is not implemented yet (#42640).
981 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
984 /// Annotated as `ref`, like `ref x`
987 /// Annotated as `ref mut x`.
991 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
997 impl fmt::Display for RangeEnd {
998 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
999 f.write_str(match self {
1000 RangeEnd::Included => "..=",
1001 RangeEnd::Excluded => "..",
1006 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1008 /// Represents a wildcard pattern (i.e., `_`).
1011 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
1012 /// The `HirId` is the canonical ID for the variable being bound,
1013 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
1014 /// which is the pattern ID of the first `x`.
1015 Binding(BindingAnnotation, HirId, Ident, Option<P<Pat>>),
1017 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
1018 /// The `bool` is `true` in the presence of a `..`.
1019 Struct(QPath, HirVec<FieldPat>, bool),
1021 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
1022 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
1023 /// `0 <= position <= subpats.len()`
1024 TupleStruct(QPath, HirVec<P<Pat>>, Option<usize>),
1026 /// An or-pattern `A | B | C`.
1027 /// Invariant: `pats.len() >= 2`.
1030 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
1033 /// A tuple pattern (e.g., `(a, b)`).
1034 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
1035 /// `0 <= position <= subpats.len()`
1036 Tuple(HirVec<P<Pat>>, Option<usize>),
1038 /// A `box` pattern.
1041 /// A reference pattern (e.g., `&mut (a, b)`).
1042 Ref(P<Pat>, Mutability),
1047 /// A range pattern (e.g., `1..=2` or `1..2`).
1048 Range(P<Expr>, P<Expr>, RangeEnd),
1050 /// `[a, b, ..i, y, z]` is represented as:
1051 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`.
1052 Slice(HirVec<P<Pat>>, Option<P<Pat>>, HirVec<P<Pat>>),
1055 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1056 pub enum BinOpKind {
1057 /// The `+` operator (addition).
1059 /// The `-` operator (subtraction).
1061 /// The `*` operator (multiplication).
1063 /// The `/` operator (division).
1065 /// The `%` operator (modulus).
1067 /// The `&&` operator (logical and).
1069 /// The `||` operator (logical or).
1071 /// The `^` operator (bitwise xor).
1073 /// The `&` operator (bitwise and).
1075 /// The `|` operator (bitwise or).
1077 /// The `<<` operator (shift left).
1079 /// The `>>` operator (shift right).
1081 /// The `==` operator (equality).
1083 /// The `<` operator (less than).
1085 /// The `<=` operator (less than or equal to).
1087 /// The `!=` operator (not equal to).
1089 /// The `>=` operator (greater than or equal to).
1091 /// The `>` operator (greater than).
1096 pub fn as_str(self) -> &'static str {
1098 BinOpKind::Add => "+",
1099 BinOpKind::Sub => "-",
1100 BinOpKind::Mul => "*",
1101 BinOpKind::Div => "/",
1102 BinOpKind::Rem => "%",
1103 BinOpKind::And => "&&",
1104 BinOpKind::Or => "||",
1105 BinOpKind::BitXor => "^",
1106 BinOpKind::BitAnd => "&",
1107 BinOpKind::BitOr => "|",
1108 BinOpKind::Shl => "<<",
1109 BinOpKind::Shr => ">>",
1110 BinOpKind::Eq => "==",
1111 BinOpKind::Lt => "<",
1112 BinOpKind::Le => "<=",
1113 BinOpKind::Ne => "!=",
1114 BinOpKind::Ge => ">=",
1115 BinOpKind::Gt => ">",
1119 pub fn is_lazy(self) -> bool {
1121 BinOpKind::And | BinOpKind::Or => true,
1126 pub fn is_shift(self) -> bool {
1128 BinOpKind::Shl | BinOpKind::Shr => true,
1133 pub fn is_comparison(self) -> bool {
1140 BinOpKind::Ge => true,
1152 BinOpKind::Shr => false,
1156 /// Returns `true` if the binary operator takes its arguments by value.
1157 pub fn is_by_value(self) -> bool {
1158 !self.is_comparison()
1162 impl Into<ast::BinOpKind> for BinOpKind {
1163 fn into(self) -> ast::BinOpKind {
1165 BinOpKind::Add => ast::BinOpKind::Add,
1166 BinOpKind::Sub => ast::BinOpKind::Sub,
1167 BinOpKind::Mul => ast::BinOpKind::Mul,
1168 BinOpKind::Div => ast::BinOpKind::Div,
1169 BinOpKind::Rem => ast::BinOpKind::Rem,
1170 BinOpKind::And => ast::BinOpKind::And,
1171 BinOpKind::Or => ast::BinOpKind::Or,
1172 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1173 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1174 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1175 BinOpKind::Shl => ast::BinOpKind::Shl,
1176 BinOpKind::Shr => ast::BinOpKind::Shr,
1177 BinOpKind::Eq => ast::BinOpKind::Eq,
1178 BinOpKind::Lt => ast::BinOpKind::Lt,
1179 BinOpKind::Le => ast::BinOpKind::Le,
1180 BinOpKind::Ne => ast::BinOpKind::Ne,
1181 BinOpKind::Ge => ast::BinOpKind::Ge,
1182 BinOpKind::Gt => ast::BinOpKind::Gt,
1187 pub type BinOp = Spanned<BinOpKind>;
1189 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1191 /// The `*` operator (deferencing).
1193 /// The `!` operator (logical negation).
1195 /// The `-` operator (negation).
1200 pub fn as_str(self) -> &'static str {
1208 /// Returns `true` if the unary operator takes its argument by value.
1209 pub fn is_by_value(self) -> bool {
1211 UnNeg | UnNot => true,
1218 #[derive(RustcEncodable, RustcDecodable, HashStable)]
1225 impl fmt::Debug for Stmt {
1226 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1227 write!(f, "stmt({}: {})", self.hir_id,
1228 print::to_string(print::NO_ANN, |s| s.print_stmt(self)))
1232 /// The contents of a statement.
1233 #[derive(RustcEncodable, RustcDecodable, HashStable)]
1235 /// A local (`let`) binding.
1238 /// An item binding.
1241 /// An expression without a trailing semi-colon (must have unit type).
1244 /// An expression with a trailing semi-colon (may have any type).
1249 pub fn attrs(&self) -> &[Attribute] {
1251 StmtKind::Local(ref l) => &l.attrs,
1252 StmtKind::Item(_) => &[],
1253 StmtKind::Expr(ref e) |
1254 StmtKind::Semi(ref e) => &e.attrs,
1259 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1260 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1263 /// Type annotation, if any (otherwise the type will be inferred).
1264 pub ty: Option<P<Ty>>,
1265 /// Initializer expression to set the value, if any.
1266 pub init: Option<P<Expr>>,
1269 pub attrs: ThinVec<Attribute>,
1270 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1271 /// desugaring. Otherwise will be `Normal`.
1272 pub source: LocalSource,
1275 /// Represents a single arm of a `match` expression, e.g.
1276 /// `<pat> (if <guard>) => <body>`.
1277 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1279 #[stable_hasher(ignore)]
1282 pub attrs: HirVec<Attribute>,
1283 /// If this pattern and the optional guard matches, then `body` is evaluated.
1285 /// Optional guard clause.
1286 pub guard: Option<Guard>,
1287 /// The expression the arm evaluates to if this arm matches.
1291 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1296 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1298 #[stable_hasher(ignore)]
1303 pub is_shorthand: bool,
1306 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1307 pub enum BlockCheckMode {
1309 UnsafeBlock(UnsafeSource),
1310 PushUnsafeBlock(UnsafeSource),
1311 PopUnsafeBlock(UnsafeSource),
1314 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1315 pub enum UnsafeSource {
1320 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1325 /// The body of a function, closure, or constant value. In the case of
1326 /// a function, the body contains not only the function body itself
1327 /// (which is an expression), but also the argument patterns, since
1328 /// those are something that the caller doesn't really care about.
1333 /// fn foo((x, y): (u32, u32)) -> u32 {
1338 /// Here, the `Body` associated with `foo()` would contain:
1340 /// - an `params` array containing the `(x, y)` pattern
1341 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1342 /// - `generator_kind` would be `None`
1344 /// All bodies have an **owner**, which can be accessed via the HIR
1345 /// map using `body_owner_def_id()`.
1346 #[derive(RustcEncodable, RustcDecodable, Debug)]
1348 pub params: HirVec<Param>,
1350 pub generator_kind: Option<GeneratorKind>,
1354 pub fn id(&self) -> BodyId {
1356 hir_id: self.value.hir_id,
1360 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1365 /// The type of source expression that caused this generator to be created.
1366 #[derive(Clone, PartialEq, Eq, HashStable, RustcEncodable, RustcDecodable, Debug, Copy)]
1367 pub enum GeneratorKind {
1368 /// An explicit `async` block or the body of an async function.
1369 Async(AsyncGeneratorKind),
1371 /// A generator literal created via a `yield` inside a closure.
1375 impl fmt::Display for GeneratorKind {
1376 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1378 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1379 GeneratorKind::Gen => f.write_str("generator"),
1384 /// In the case of a generator created as part of an async construct,
1385 /// which kind of async construct caused it to be created?
1387 /// This helps error messages but is also used to drive coercions in
1388 /// type-checking (see #60424).
1389 #[derive(Clone, PartialEq, Eq, HashStable, RustcEncodable, RustcDecodable, Debug, Copy)]
1390 pub enum AsyncGeneratorKind {
1391 /// An explicit `async` block written by the user.
1394 /// An explicit `async` block written by the user.
1397 /// The `async` block generated as the body of an async function.
1401 impl fmt::Display for AsyncGeneratorKind {
1402 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1403 f.write_str(match self {
1404 AsyncGeneratorKind::Block => "`async` block",
1405 AsyncGeneratorKind::Closure => "`async` closure body",
1406 AsyncGeneratorKind::Fn => "`async fn` body",
1411 #[derive(Copy, Clone, Debug)]
1412 pub enum BodyOwnerKind {
1413 /// Functions and methods.
1419 /// Constants and associated constants.
1422 /// Initializer of a `static` item.
1426 impl BodyOwnerKind {
1427 pub fn is_fn_or_closure(self) -> bool {
1429 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1430 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1436 pub type Lit = Spanned<LitKind>;
1438 /// A constant (expression) that's not an item or associated item,
1439 /// but needs its own `DefId` for type-checking, const-eval, etc.
1440 /// These are usually found nested inside types (e.g., array lengths)
1441 /// or expressions (e.g., repeat counts), and also used to define
1442 /// explicit discriminant values for enum variants.
1443 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1444 pub struct AnonConst {
1450 #[derive(RustcEncodable, RustcDecodable)]
1454 pub attrs: ThinVec<Attribute>,
1458 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1459 #[cfg(target_arch = "x86_64")]
1460 static_assert_size!(Expr, 64);
1463 pub fn precedence(&self) -> ExprPrecedence {
1465 ExprKind::Box(_) => ExprPrecedence::Box,
1466 ExprKind::Array(_) => ExprPrecedence::Array,
1467 ExprKind::Call(..) => ExprPrecedence::Call,
1468 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1469 ExprKind::Tup(_) => ExprPrecedence::Tup,
1470 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1471 ExprKind::Unary(..) => ExprPrecedence::Unary,
1472 ExprKind::Lit(_) => ExprPrecedence::Lit,
1473 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1474 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1475 ExprKind::Loop(..) => ExprPrecedence::Loop,
1476 ExprKind::Match(..) => ExprPrecedence::Match,
1477 ExprKind::Closure(..) => ExprPrecedence::Closure,
1478 ExprKind::Block(..) => ExprPrecedence::Block,
1479 ExprKind::Assign(..) => ExprPrecedence::Assign,
1480 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1481 ExprKind::Field(..) => ExprPrecedence::Field,
1482 ExprKind::Index(..) => ExprPrecedence::Index,
1483 ExprKind::Path(..) => ExprPrecedence::Path,
1484 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1485 ExprKind::Break(..) => ExprPrecedence::Break,
1486 ExprKind::Continue(..) => ExprPrecedence::Continue,
1487 ExprKind::Ret(..) => ExprPrecedence::Ret,
1488 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1489 ExprKind::Struct(..) => ExprPrecedence::Struct,
1490 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1491 ExprKind::Yield(..) => ExprPrecedence::Yield,
1492 ExprKind::Err => ExprPrecedence::Err,
1496 pub fn is_place_expr(&self) -> bool {
1498 ExprKind::Path(QPath::Resolved(_, ref path)) => {
1501 | Res::Def(DefKind::Static, _)
1507 ExprKind::Type(ref e, _) => {
1511 ExprKind::Unary(UnDeref, _) |
1512 ExprKind::Field(..) |
1513 ExprKind::Index(..) => {
1517 // Partially qualified paths in expressions can only legally
1518 // refer to associated items which are always rvalues.
1519 ExprKind::Path(QPath::TypeRelative(..)) |
1521 ExprKind::Call(..) |
1522 ExprKind::MethodCall(..) |
1523 ExprKind::Struct(..) |
1525 ExprKind::Match(..) |
1526 ExprKind::Closure(..) |
1527 ExprKind::Block(..) |
1528 ExprKind::Repeat(..) |
1529 ExprKind::Array(..) |
1530 ExprKind::Break(..) |
1531 ExprKind::Continue(..) |
1533 ExprKind::Loop(..) |
1534 ExprKind::Assign(..) |
1535 ExprKind::InlineAsm(..) |
1536 ExprKind::AssignOp(..) |
1538 ExprKind::Unary(..) |
1540 ExprKind::AddrOf(..) |
1541 ExprKind::Binary(..) |
1542 ExprKind::Yield(..) |
1543 ExprKind::Cast(..) |
1544 ExprKind::DropTemps(..) |
1551 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1552 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1553 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1554 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1555 /// beyond remembering to call this function before doing analysis on it.
1556 pub fn peel_drop_temps(&self) -> &Self {
1557 let mut expr = self;
1558 while let ExprKind::DropTemps(inner) = &expr.kind {
1565 impl fmt::Debug for Expr {
1566 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1567 write!(f, "expr({}: {})", self.hir_id,
1568 print::to_string(print::NO_ANN, |s| s.print_expr(self)))
1572 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1574 /// A `box x` expression.
1576 /// An array (e.g., `[a, b, c, d]`).
1577 Array(HirVec<Expr>),
1578 /// A function call.
1580 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1581 /// and the second field is the list of arguments.
1582 /// This also represents calling the constructor of
1583 /// tuple-like ADTs such as tuple structs and enum variants.
1584 Call(P<Expr>, HirVec<Expr>),
1585 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1587 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1588 /// (within the angle brackets).
1589 /// The first element of the vector of `Expr`s is the expression that evaluates
1590 /// to the object on which the method is being called on (the receiver),
1591 /// and the remaining elements are the rest of the arguments.
1592 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1593 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1595 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1596 /// the `hir_id` of the `MethodCall` node itself.
1598 /// [`type_dependent_def_id`]: ../ty/struct.TypeckTables.html#method.type_dependent_def_id
1599 MethodCall(P<PathSegment>, Span, HirVec<Expr>),
1600 /// A tuple (e.g., `(a, b, c, d)`).
1602 /// A binary operation (e.g., `a + b`, `a * b`).
1603 Binary(BinOp, P<Expr>, P<Expr>),
1604 /// A unary operation (e.g., `!x`, `*x`).
1605 Unary(UnOp, P<Expr>),
1606 /// A literal (e.g., `1`, `"foo"`).
1608 /// A cast (e.g., `foo as f64`).
1609 Cast(P<Expr>, P<Ty>),
1610 /// A type reference (e.g., `Foo`).
1611 Type(P<Expr>, P<Ty>),
1612 /// Wraps the expression in a terminating scope.
1613 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1615 /// This construct only exists to tweak the drop order in HIR lowering.
1616 /// An example of that is the desugaring of `for` loops.
1618 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1620 /// I.e., `'label: loop { <block> }`.
1621 Loop(P<Block>, Option<Label>, LoopSource),
1622 /// A `match` block, with a source that indicates whether or not it is
1623 /// the result of a desugaring, and if so, which kind.
1624 Match(P<Expr>, HirVec<Arm>, MatchSource),
1625 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1627 /// The `Span` is the argument block `|...|`.
1629 /// This may also be a generator literal or an `async block` as indicated by the
1630 /// `Option<Movability>`.
1631 Closure(CaptureBy, P<FnDecl>, BodyId, Span, Option<Movability>),
1632 /// A block (e.g., `'label: { ... }`).
1633 Block(P<Block>, Option<Label>),
1635 /// An assignment (e.g., `a = foo()`).
1636 Assign(P<Expr>, P<Expr>),
1637 /// An assignment with an operator.
1640 AssignOp(BinOp, P<Expr>, P<Expr>),
1641 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1642 Field(P<Expr>, Ident),
1643 /// An indexing operation (`foo[2]`).
1644 Index(P<Expr>, P<Expr>),
1646 /// Path to a definition, possibly containing lifetime or type parameters.
1649 /// A referencing operation (i.e., `&a` or `&mut a`).
1650 AddrOf(Mutability, P<Expr>),
1651 /// A `break`, with an optional label to break.
1652 Break(Destination, Option<P<Expr>>),
1653 /// A `continue`, with an optional label.
1654 Continue(Destination),
1655 /// A `return`, with an optional value to be returned.
1656 Ret(Option<P<Expr>>),
1658 /// Inline assembly (from `asm!`), with its outputs and inputs.
1659 InlineAsm(P<InlineAsm>),
1661 /// A struct or struct-like variant literal expression.
1663 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1664 /// where `base` is the `Option<Expr>`.
1665 Struct(P<QPath>, HirVec<Field>, Option<P<Expr>>),
1667 /// An array literal constructed from one repeated element.
1669 /// E.g., `[1; 5]`. The first expression is the element
1670 /// to be repeated; the second is the number of times to repeat it.
1671 Repeat(P<Expr>, AnonConst),
1673 /// A suspension point for generators (i.e., `yield <expr>`).
1674 Yield(P<Expr>, YieldSource),
1676 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1680 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1682 /// To resolve the path to a `DefId`, call [`qpath_res`].
1684 /// [`qpath_res`]: ../ty/struct.TypeckTables.html#method.qpath_res
1685 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1687 /// Path to a definition, optionally "fully-qualified" with a `Self`
1688 /// type, if the path points to an associated item in a trait.
1690 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1691 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1692 /// even though they both have the same two-segment `Clone::clone` `Path`.
1693 Resolved(Option<P<Ty>>, P<Path>),
1695 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1696 /// Will be resolved by type-checking to an associated item.
1698 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1699 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1700 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1701 TypeRelative(P<Ty>, P<PathSegment>)
1704 /// Hints at the original code for a let statement.
1705 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1706 pub enum LocalSource {
1707 /// A `match _ { .. }`.
1709 /// A desugared `for _ in _ { .. }` loop.
1711 /// When lowering async functions, we create locals within the `async move` so that
1712 /// all parameters are dropped after the future is polled.
1714 /// ```ignore (pseudo-Rust)
1715 /// async fn foo(<pattern> @ x: Type) {
1717 /// let <pattern> = x;
1722 /// A desugared `<expr>.await`.
1726 /// Hints at the original code for a `match _ { .. }`.
1727 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
1728 pub enum MatchSource {
1729 /// A `match _ { .. }`.
1731 /// An `if _ { .. }` (optionally with `else { .. }`).
1733 contains_else_clause: bool,
1735 /// An `if let _ = _ { .. }` (optionally with `else { .. }`).
1737 contains_else_clause: bool,
1739 /// A `while _ { .. }` (which was desugared to a `loop { match _ { .. } }`).
1741 /// A `while let _ = _ { .. }` (which was desugared to a
1742 /// `loop { match _ { .. } }`).
1744 /// A desugared `for _ in _ { .. }` loop.
1746 /// A desugared `?` operator.
1748 /// A desugared `<expr>.await`.
1753 pub fn name(self) -> &'static str {
1757 IfDesugar { .. } | IfLetDesugar { .. } => "if",
1758 WhileDesugar | WhileLetDesugar => "while",
1759 ForLoopDesugar => "for",
1761 AwaitDesugar => ".await",
1766 /// The loop type that yielded an `ExprKind::Loop`.
1767 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1768 pub enum LoopSource {
1769 /// A `loop { .. }` loop.
1771 /// A `while _ { .. }` loop.
1773 /// A `while let _ = _ { .. }` loop.
1775 /// A `for _ in _ { .. }` loop.
1780 pub fn name(self) -> &'static str {
1782 LoopSource::Loop => "loop",
1783 LoopSource::While | LoopSource::WhileLet => "while",
1784 LoopSource::ForLoop => "for",
1789 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1790 pub enum LoopIdError {
1792 UnlabeledCfInWhileCondition,
1796 impl fmt::Display for LoopIdError {
1797 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1798 f.write_str(match self {
1799 LoopIdError::OutsideLoopScope => "not inside loop scope",
1800 LoopIdError::UnlabeledCfInWhileCondition =>
1801 "unlabeled control flow (break or continue) in while condition",
1802 LoopIdError::UnresolvedLabel => "label not found",
1807 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1808 pub struct Destination {
1809 // This is `Some(_)` iff there is an explicit user-specified `label
1810 pub label: Option<Label>,
1812 // These errors are caught and then reported during the diagnostics pass in
1813 // librustc_passes/loops.rs
1814 pub target_id: Result<HirId, LoopIdError>,
1817 /// The yield kind that caused an `ExprKind::Yield`.
1818 #[derive(Copy, Clone, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable, HashStable)]
1819 pub enum YieldSource {
1820 /// An `<expr>.await`.
1822 /// A plain `yield`.
1826 impl fmt::Display for YieldSource {
1827 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1828 f.write_str(match self {
1829 YieldSource::Await => "`await`",
1830 YieldSource::Yield => "`yield`",
1835 // N.B., if you change this, you'll probably want to change the corresponding
1836 // type structure in middle/ty.rs as well.
1837 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1840 pub mutbl: Mutability,
1843 /// Represents a function's signature in a trait declaration,
1844 /// trait implementation, or a free function.
1845 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1847 pub header: FnHeader,
1848 pub decl: P<FnDecl>,
1851 // The bodies for items are stored "out of line", in a separate
1852 // hashmap in the `Crate`. Here we just record the node-id of the item
1853 // so it can fetched later.
1854 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1855 pub struct TraitItemId {
1859 /// Represents an item declaration within a trait declaration,
1860 /// possibly including a default implementation. A trait item is
1861 /// either required (meaning it doesn't have an implementation, just a
1862 /// signature) or provided (meaning it has a default implementation).
1863 #[derive(RustcEncodable, RustcDecodable, Debug)]
1864 pub struct TraitItem {
1867 pub attrs: HirVec<Attribute>,
1868 pub generics: Generics,
1869 pub kind: TraitItemKind,
1873 /// Represents a trait method's body (or just argument names).
1874 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1875 pub enum TraitMethod {
1876 /// No default body in the trait, just a signature.
1877 Required(HirVec<Ident>),
1879 /// Both signature and body are provided in the trait.
1883 /// Represents a trait method or associated constant or type
1884 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1885 pub enum TraitItemKind {
1886 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
1887 Const(P<Ty>, Option<BodyId>),
1888 /// A method with an optional body.
1889 Method(FnSig, TraitMethod),
1890 /// An associated type with (possibly empty) bounds and optional concrete
1892 Type(GenericBounds, Option<P<Ty>>),
1895 // The bodies for items are stored "out of line", in a separate
1896 // hashmap in the `Crate`. Here we just record the node-id of the item
1897 // so it can fetched later.
1898 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1899 pub struct ImplItemId {
1903 /// Represents anything within an `impl` block.
1904 #[derive(RustcEncodable, RustcDecodable, Debug)]
1905 pub struct ImplItem {
1908 pub vis: Visibility,
1909 pub defaultness: Defaultness,
1910 pub attrs: HirVec<Attribute>,
1911 pub generics: Generics,
1912 pub kind: ImplItemKind,
1916 /// Represents various kinds of content within an `impl`.
1917 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1918 pub enum ImplItemKind {
1919 /// An associated constant of the given type, set to the constant result
1920 /// of the expression.
1921 Const(P<Ty>, BodyId),
1922 /// A method implementation with the given signature and body.
1923 Method(FnSig, BodyId),
1924 /// An associated type.
1926 /// An associated `type = impl Trait`.
1927 OpaqueTy(GenericBounds),
1930 /// Bind a type to an associated type (i.e., `A = Foo`).
1932 /// Bindings like `A: Debug` are represented as a special type `A =
1933 /// $::Debug` that is understood by the astconv code.
1935 /// FIXME(alexreg): why have a separate type for the binding case,
1936 /// wouldn't it be better to make the `ty` field an enum like the
1940 /// enum TypeBindingKind {
1945 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1946 pub struct TypeBinding {
1948 #[stable_hasher(project(name))]
1950 pub kind: TypeBindingKind,
1954 // Represents the two kinds of type bindings.
1955 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1956 pub enum TypeBindingKind {
1957 /// E.g., `Foo<Bar: Send>`.
1959 bounds: HirVec<GenericBound>,
1961 /// E.g., `Foo<Bar = ()>`.
1968 pub fn ty(&self) -> &Ty {
1970 TypeBindingKind::Equality { ref ty } => ty,
1971 _ => bug!("expected equality type binding for parenthesized generic args"),
1976 #[derive(RustcEncodable, RustcDecodable)]
1983 impl fmt::Debug for Ty {
1984 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1985 write!(f, "type({})",
1986 print::to_string(print::NO_ANN, |s| s.print_type(self)))
1990 /// Not represented directly in the AST; referred to by name through a `ty_path`.
1991 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
2001 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2002 pub struct BareFnTy {
2003 pub unsafety: Unsafety,
2005 pub generic_params: HirVec<GenericParam>,
2006 pub decl: P<FnDecl>,
2007 pub param_names: HirVec<Ident>,
2010 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2011 pub struct OpaqueTy {
2012 pub generics: Generics,
2013 pub bounds: GenericBounds,
2014 pub impl_trait_fn: Option<DefId>,
2015 pub origin: OpaqueTyOrigin,
2018 /// From whence the opaque type came.
2019 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2020 pub enum OpaqueTyOrigin {
2021 /// `type Foo = impl Trait;`
2029 /// The various kinds of types recognized by the compiler.
2030 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2032 /// A variable length slice (i.e., `[T]`).
2034 /// A fixed length array (i.e., `[T; n]`).
2035 Array(P<Ty>, AnonConst),
2036 /// A raw pointer (i.e., `*const T` or `*mut T`).
2038 /// A reference (i.e., `&'a T` or `&'a mut T`).
2039 Rptr(Lifetime, MutTy),
2040 /// A bare function (e.g., `fn(usize) -> bool`).
2041 BareFn(P<BareFnTy>),
2042 /// The never type (`!`).
2044 /// A tuple (`(A, B, C, D, ...)`).
2046 /// A path to a type definition (`module::module::...::Type`), or an
2047 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2049 /// Type parameters may be stored in each `PathSegment`.
2051 /// A type definition itself. This is currently only used for the `type Foo = impl Trait`
2052 /// item that `impl Trait` in return position desugars to.
2054 /// The generic argument list contains the lifetimes (and in the future possibly parameters)
2055 /// that are actually bound on the `impl Trait`.
2056 Def(ItemId, HirVec<GenericArg>),
2057 /// A trait object type `Bound1 + Bound2 + Bound3`
2058 /// where `Bound` is a trait or a lifetime.
2059 TraitObject(HirVec<PolyTraitRef>, Lifetime),
2062 /// `TyKind::Infer` means the type should be inferred instead of it having been
2063 /// specified. This can appear anywhere in a type.
2065 /// Placeholder for a type that has failed to be defined.
2069 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable, PartialEq)]
2070 pub struct InlineAsmOutput {
2071 pub constraint: Symbol,
2073 pub is_indirect: bool,
2077 // NOTE(eddyb) This is used within MIR as well, so unlike the rest of the HIR,
2078 // it needs to be `Clone` and use plain `Vec<T>` instead of `HirVec<T>`.
2079 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable, PartialEq)]
2080 pub struct InlineAsmInner {
2082 pub asm_str_style: StrStyle,
2083 pub outputs: Vec<InlineAsmOutput>,
2084 pub inputs: Vec<Symbol>,
2085 pub clobbers: Vec<Symbol>,
2087 pub alignstack: bool,
2088 pub dialect: AsmDialect,
2091 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2092 pub struct InlineAsm {
2093 pub inner: InlineAsmInner,
2094 pub outputs_exprs: HirVec<Expr>,
2095 pub inputs_exprs: HirVec<Expr>,
2098 /// Represents a parameter in a function header.
2099 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2101 pub attrs: HirVec<Attribute>,
2107 /// Represents the header (not the body) of a function declaration.
2108 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2110 /// The types of the function's parameters.
2112 /// Additional argument data is stored in the function's [body](Body::parameters).
2113 pub inputs: HirVec<Ty>,
2114 pub output: FunctionRetTy,
2115 pub c_variadic: bool,
2116 /// Does the function have an implicit self?
2117 pub implicit_self: ImplicitSelfKind,
2120 /// Represents what type of implicit self a function has, if any.
2121 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2122 pub enum ImplicitSelfKind {
2123 /// Represents a `fn x(self);`.
2125 /// Represents a `fn x(mut self);`.
2127 /// Represents a `fn x(&self);`.
2129 /// Represents a `fn x(&mut self);`.
2131 /// Represents when a function does not have a self argument or
2132 /// when a function has a `self: X` argument.
2136 impl ImplicitSelfKind {
2137 /// Does this represent an implicit self?
2138 pub fn has_implicit_self(&self) -> bool {
2140 ImplicitSelfKind::None => false,
2146 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, HashStable,
2147 Ord, RustcEncodable, RustcDecodable, Debug)]
2153 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2154 pub enum Defaultness {
2155 Default { has_value: bool },
2160 pub fn has_value(&self) -> bool {
2162 Defaultness::Default { has_value, .. } => has_value,
2163 Defaultness::Final => true,
2167 pub fn is_final(&self) -> bool {
2168 *self == Defaultness::Final
2171 pub fn is_default(&self) -> bool {
2173 Defaultness::Default { .. } => true,
2179 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2180 pub enum FunctionRetTy {
2181 /// Return type is not specified.
2183 /// Functions default to `()` and
2184 /// closures default to inference. Span points to where return
2185 /// type would be inserted.
2186 DefaultReturn(Span),
2187 /// Everything else.
2191 impl fmt::Display for FunctionRetTy {
2192 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2194 Return(ref ty) => print::to_string(print::NO_ANN, |s| s.print_type(ty)).fmt(f),
2195 DefaultReturn(_) => "()".fmt(f),
2200 impl FunctionRetTy {
2201 pub fn span(&self) -> Span {
2203 DefaultReturn(span) => span,
2204 Return(ref ty) => ty.span,
2209 #[derive(RustcEncodable, RustcDecodable, Debug)]
2211 /// A span from the first token past `{` to the last token until `}`.
2212 /// For `mod foo;`, the inner span ranges from the first token
2213 /// to the last token in the external file.
2215 pub item_ids: HirVec<ItemId>,
2218 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2219 pub struct ForeignMod {
2221 pub items: HirVec<ForeignItem>,
2224 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2225 pub struct GlobalAsm {
2229 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2230 pub struct EnumDef {
2231 pub variants: HirVec<Variant>,
2234 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2235 pub struct Variant {
2236 /// Name of the variant.
2237 #[stable_hasher(project(name))]
2239 /// Attributes of the variant.
2240 pub attrs: HirVec<Attribute>,
2241 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2243 /// Fields and constructor id of the variant.
2244 pub data: VariantData,
2245 /// Explicit discriminant (e.g., `Foo = 1`).
2246 pub disr_expr: Option<AnonConst>,
2251 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2253 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2254 /// Also produced for each element of a list `use`, e.g.
2255 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2258 /// Glob import, e.g., `use foo::*`.
2261 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2262 /// an additional `use foo::{}` for performing checks such as
2263 /// unstable feature gating. May be removed in the future.
2267 /// References to traits in impls.
2269 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2270 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2271 /// trait being referred to but just a unique `HirId` that serves as a key
2272 /// within the resolution map.
2273 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2274 pub struct TraitRef {
2276 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2277 #[stable_hasher(ignore)]
2278 pub hir_ref_id: HirId,
2282 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2283 pub fn trait_def_id(&self) -> DefId {
2284 match self.path.res {
2285 Res::Def(DefKind::Trait, did) => did,
2286 Res::Def(DefKind::TraitAlias, did) => did,
2290 _ => unreachable!(),
2295 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2296 pub struct PolyTraitRef {
2297 /// The `'a` in `<'a> Foo<&'a T>`.
2298 pub bound_generic_params: HirVec<GenericParam>,
2300 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2301 pub trait_ref: TraitRef,
2306 pub type Visibility = Spanned<VisibilityKind>;
2308 #[derive(RustcEncodable, RustcDecodable, Debug)]
2309 pub enum VisibilityKind {
2312 Restricted { path: P<Path>, hir_id: HirId },
2316 impl VisibilityKind {
2317 pub fn is_pub(&self) -> bool {
2319 VisibilityKind::Public => true,
2324 pub fn is_pub_restricted(&self) -> bool {
2326 VisibilityKind::Public |
2327 VisibilityKind::Inherited => false,
2328 VisibilityKind::Crate(..) |
2329 VisibilityKind::Restricted { .. } => true,
2333 pub fn descr(&self) -> &'static str {
2335 VisibilityKind::Public => "public",
2336 VisibilityKind::Inherited => "private",
2337 VisibilityKind::Crate(..) => "crate-visible",
2338 VisibilityKind::Restricted { .. } => "restricted",
2343 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2344 pub struct StructField {
2346 #[stable_hasher(project(name))]
2348 pub vis: Visibility,
2351 pub attrs: HirVec<Attribute>,
2355 // Still necessary in couple of places
2356 pub fn is_positional(&self) -> bool {
2357 let first = self.ident.as_str().as_bytes()[0];
2358 first >= b'0' && first <= b'9'
2362 /// Fields and constructor IDs of enum variants and structs.
2363 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2364 pub enum VariantData {
2365 /// A struct variant.
2367 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2368 Struct(HirVec<StructField>, /* recovered */ bool),
2369 /// A tuple variant.
2371 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2372 Tuple(HirVec<StructField>, HirId),
2375 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2380 /// Return the fields of this variant.
2381 pub fn fields(&self) -> &[StructField] {
2383 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2388 /// Return the `HirId` of this variant's constructor, if it has one.
2389 pub fn ctor_hir_id(&self) -> Option<HirId> {
2391 VariantData::Struct(_, _) => None,
2392 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2397 // The bodies for items are stored "out of line", in a separate
2398 // hashmap in the `Crate`. Here we just record the node-id of the item
2399 // so it can fetched later.
2400 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2407 /// The name might be a dummy name in case of anonymous items
2408 #[derive(RustcEncodable, RustcDecodable, Debug)]
2412 pub attrs: HirVec<Attribute>,
2414 pub vis: Visibility,
2418 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2419 pub struct FnHeader {
2420 pub unsafety: Unsafety,
2421 pub constness: Constness,
2422 pub asyncness: IsAsync,
2427 pub fn is_const(&self) -> bool {
2428 match &self.constness {
2429 Constness::Const => true,
2435 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2437 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2439 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2440 ExternCrate(Option<Name>),
2442 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2446 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2447 Use(P<Path>, UseKind),
2449 /// A `static` item.
2450 Static(P<Ty>, Mutability, BodyId),
2452 Const(P<Ty>, BodyId),
2453 /// A function declaration.
2454 Fn(FnSig, Generics, BodyId),
2457 /// An external module, e.g. `extern { .. }`.
2458 ForeignMod(ForeignMod),
2459 /// Module-level inline assembly (from `global_asm!`).
2460 GlobalAsm(P<GlobalAsm>),
2461 /// A type alias, e.g., `type Foo = Bar<u8>`.
2462 TyAlias(P<Ty>, Generics),
2463 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2465 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2466 Enum(EnumDef, Generics),
2467 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2468 Struct(VariantData, Generics),
2469 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2470 Union(VariantData, Generics),
2471 /// A trait definition.
2472 Trait(IsAuto, Unsafety, Generics, GenericBounds, HirVec<TraitItemRef>),
2474 TraitAlias(Generics, GenericBounds),
2476 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2481 Option<TraitRef>, // (optional) trait this impl implements
2483 HirVec<ImplItemRef>),
2487 pub fn descriptive_variant(&self) -> &str {
2489 ItemKind::ExternCrate(..) => "extern crate",
2490 ItemKind::Use(..) => "use",
2491 ItemKind::Static(..) => "static item",
2492 ItemKind::Const(..) => "constant item",
2493 ItemKind::Fn(..) => "function",
2494 ItemKind::Mod(..) => "module",
2495 ItemKind::ForeignMod(..) => "foreign module",
2496 ItemKind::GlobalAsm(..) => "global asm",
2497 ItemKind::TyAlias(..) => "type alias",
2498 ItemKind::OpaqueTy(..) => "opaque type",
2499 ItemKind::Enum(..) => "enum",
2500 ItemKind::Struct(..) => "struct",
2501 ItemKind::Union(..) => "union",
2502 ItemKind::Trait(..) => "trait",
2503 ItemKind::TraitAlias(..) => "trait alias",
2504 ItemKind::Impl(..) => "impl",
2508 pub fn adt_kind(&self) -> Option<AdtKind> {
2510 ItemKind::Struct(..) => Some(AdtKind::Struct),
2511 ItemKind::Union(..) => Some(AdtKind::Union),
2512 ItemKind::Enum(..) => Some(AdtKind::Enum),
2517 pub fn generics(&self) -> Option<&Generics> {
2519 ItemKind::Fn(_, ref generics, _) |
2520 ItemKind::TyAlias(_, ref generics) |
2521 ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. }) |
2522 ItemKind::Enum(_, ref generics) |
2523 ItemKind::Struct(_, ref generics) |
2524 ItemKind::Union(_, ref generics) |
2525 ItemKind::Trait(_, _, ref generics, _, _) |
2526 ItemKind::Impl(_, _, _, ref generics, _, _, _)=> generics,
2532 /// A reference from an trait to one of its associated items. This
2533 /// contains the item's id, naturally, but also the item's name and
2534 /// some other high-level details (like whether it is an associated
2535 /// type or method, and whether it is public). This allows other
2536 /// passes to find the impl they want without loading the ID (which
2537 /// means fewer edges in the incremental compilation graph).
2538 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2539 pub struct TraitItemRef {
2540 pub id: TraitItemId,
2541 #[stable_hasher(project(name))]
2543 pub kind: AssocItemKind,
2545 pub defaultness: Defaultness,
2548 /// A reference from an impl to one of its associated items. This
2549 /// contains the item's ID, naturally, but also the item's name and
2550 /// some other high-level details (like whether it is an associated
2551 /// type or method, and whether it is public). This allows other
2552 /// passes to find the impl they want without loading the ID (which
2553 /// means fewer edges in the incremental compilation graph).
2554 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2555 pub struct ImplItemRef {
2557 #[stable_hasher(project(name))]
2559 pub kind: AssocItemKind,
2561 pub vis: Visibility,
2562 pub defaultness: Defaultness,
2565 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2566 pub enum AssocItemKind {
2568 Method { has_self: bool },
2573 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2574 pub struct ForeignItem {
2575 #[stable_hasher(project(name))]
2577 pub attrs: HirVec<Attribute>,
2578 pub kind: ForeignItemKind,
2581 pub vis: Visibility,
2584 /// An item within an `extern` block.
2585 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2586 pub enum ForeignItemKind {
2587 /// A foreign function.
2588 Fn(P<FnDecl>, HirVec<Ident>, Generics),
2589 /// A foreign static item (`static ext: u8`).
2590 Static(P<Ty>, Mutability),
2595 impl ForeignItemKind {
2596 pub fn descriptive_variant(&self) -> &str {
2598 ForeignItemKind::Fn(..) => "foreign function",
2599 ForeignItemKind::Static(..) => "foreign static item",
2600 ForeignItemKind::Type => "foreign type",
2605 /// A variable captured by a closure.
2606 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable, HashStable)]
2608 // First span where it is accessed (there can be multiple).
2612 pub type CaptureModeMap = NodeMap<CaptureBy>;
2614 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2615 // has length > 0 if the trait is found through an chain of imports, starting with the
2616 // import/use statement in the scope where the trait is used.
2617 #[derive(Clone, Debug)]
2618 pub struct TraitCandidate {
2620 pub import_ids: SmallVec<[NodeId; 1]>,
2623 // Trait method resolution
2624 pub type TraitMap = NodeMap<Vec<TraitCandidate>>;
2626 // Map from the NodeId of a glob import to a list of items which are actually
2628 pub type GlobMap = NodeMap<FxHashSet<Name>>;
2630 pub fn provide(providers: &mut Providers<'_>) {
2631 check_attr::provide(providers);
2632 map::provide(providers);
2633 upvars::provide(providers);
2636 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
2637 pub struct CodegenFnAttrs {
2638 pub flags: CodegenFnAttrFlags,
2639 /// Parsed representation of the `#[inline]` attribute
2640 pub inline: InlineAttr,
2641 /// Parsed representation of the `#[optimize]` attribute
2642 pub optimize: OptimizeAttr,
2643 /// The `#[export_name = "..."]` attribute, indicating a custom symbol a
2644 /// function should be exported under
2645 pub export_name: Option<Symbol>,
2646 /// The `#[link_name = "..."]` attribute, indicating a custom symbol an
2647 /// imported function should be imported as. Note that `export_name`
2648 /// probably isn't set when this is set, this is for foreign items while
2649 /// `#[export_name]` is for Rust-defined functions.
2650 pub link_name: Option<Symbol>,
2651 /// The `#[link_ordinal = "..."]` attribute, indicating an ordinal an
2652 /// imported function has in the dynamic library. Note that this must not
2653 /// be set when `link_name` is set. This is for foreign items with the
2654 /// "raw-dylib" kind.
2655 pub link_ordinal: Option<usize>,
2656 /// The `#[target_feature(enable = "...")]` attribute and the enabled
2657 /// features (only enabled features are supported right now).
2658 pub target_features: Vec<Symbol>,
2659 /// The `#[linkage = "..."]` attribute and the value we found.
2660 pub linkage: Option<Linkage>,
2661 /// The `#[link_section = "..."]` attribute, or what executable section this
2662 /// should be placed in.
2663 pub link_section: Option<Symbol>,
2667 #[derive(RustcEncodable, RustcDecodable, HashStable)]
2668 pub struct CodegenFnAttrFlags: u32 {
2669 /// `#[cold]`: a hint to LLVM that this function, when called, is never on
2671 const COLD = 1 << 0;
2672 /// `#[rustc_allocator]`: a hint to LLVM that the pointer returned from this
2673 /// function is never null.
2674 const ALLOCATOR = 1 << 1;
2675 /// `#[unwind]`: an indicator that this function may unwind despite what
2676 /// its ABI signature may otherwise imply.
2677 const UNWIND = 1 << 2;
2678 /// `#[rust_allocator_nounwind]`, an indicator that an imported FFI
2679 /// function will never unwind. Probably obsolete by recent changes with
2680 /// #[unwind], but hasn't been removed/migrated yet
2681 const RUSTC_ALLOCATOR_NOUNWIND = 1 << 3;
2682 /// `#[naked]`: an indicator to LLVM that no function prologue/epilogue
2683 /// should be generated.
2684 const NAKED = 1 << 4;
2685 /// `#[no_mangle]`: an indicator that the function's name should be the same
2687 const NO_MANGLE = 1 << 5;
2688 /// `#[rustc_std_internal_symbol]`: an indicator that this symbol is a
2689 /// "weird symbol" for the standard library in that it has slightly
2690 /// different linkage, visibility, and reachability rules.
2691 const RUSTC_STD_INTERNAL_SYMBOL = 1 << 6;
2692 /// `#[no_debug]`: an indicator that no debugging information should be
2693 /// generated for this function by LLVM.
2694 const NO_DEBUG = 1 << 7;
2695 /// `#[thread_local]`: indicates a static is actually a thread local
2697 const THREAD_LOCAL = 1 << 8;
2698 /// `#[used]`: indicates that LLVM can't eliminate this function (but the
2700 const USED = 1 << 9;
2701 /// `#[ffi_returns_twice]`, indicates that an extern function can return
2703 const FFI_RETURNS_TWICE = 1 << 10;
2704 /// `#[track_caller]`: allow access to the caller location
2705 const TRACK_CALLER = 1 << 11;
2709 impl CodegenFnAttrs {
2710 pub fn new() -> CodegenFnAttrs {
2712 flags: CodegenFnAttrFlags::empty(),
2713 inline: InlineAttr::None,
2714 optimize: OptimizeAttr::None,
2718 target_features: vec![],
2724 /// Returns `true` if `#[inline]` or `#[inline(always)]` is present.
2725 pub fn requests_inline(&self) -> bool {
2727 InlineAttr::Hint | InlineAttr::Always => true,
2728 InlineAttr::None | InlineAttr::Never => false,
2732 /// Returns `true` if it looks like this symbol needs to be exported, for example:
2734 /// * `#[no_mangle]` is present
2735 /// * `#[export_name(...)]` is present
2736 /// * `#[linkage]` is present
2737 pub fn contains_extern_indicator(&self) -> bool {
2738 self.flags.contains(CodegenFnAttrFlags::NO_MANGLE) ||
2739 self.export_name.is_some() ||
2740 match self.linkage {
2741 // These are private, so make sure we don't try to consider
2744 Some(Linkage::Internal) |
2745 Some(Linkage::Private) => false,
2751 #[derive(Copy, Clone, Debug)]
2752 pub enum Node<'hir> {
2755 ForeignItem(&'hir ForeignItem),
2756 TraitItem(&'hir TraitItem),
2757 ImplItem(&'hir ImplItem),
2758 Variant(&'hir Variant),
2759 Field(&'hir StructField),
2760 AnonConst(&'hir AnonConst),
2763 PathSegment(&'hir PathSegment),
2765 TraitRef(&'hir TraitRef),
2771 MacroDef(&'hir MacroDef),
2773 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
2774 /// with synthesized constructors.
2775 Ctor(&'hir VariantData),
2777 Lifetime(&'hir Lifetime),
2778 GenericParam(&'hir GenericParam),
2779 Visibility(&'hir Visibility),
2785 pub fn ident(&self) -> Option<Ident> {
2787 Node::TraitItem(TraitItem { ident, .. }) |
2788 Node::ImplItem(ImplItem { ident, .. }) |
2789 Node::ForeignItem(ForeignItem { ident, .. }) |
2790 Node::Item(Item { ident, .. }) => Some(*ident),