1 //! HIR datatypes. See the [rustc guide] for more info.
3 //! [rustc guide]: https://rust-lang.github.io/rustc-guide/hir.html
5 pub use self::BlockCheckMode::*;
6 pub use self::CaptureClause::*;
7 pub use self::FunctionRetTy::*;
8 pub use self::Mutability::*;
9 pub use self::PrimTy::*;
10 pub use self::UnOp::*;
11 pub use self::UnsafeSource::*;
13 use crate::hir::def::{Res, DefKind};
14 use crate::hir::def_id::{DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX};
15 use crate::hir::ptr::P;
16 use crate::util::nodemap::{NodeMap, FxHashSet};
17 use crate::mir::mono::Linkage;
19 use errors::FatalError;
20 use syntax_pos::{Span, DUMMY_SP, symbol::InternedString, MultiSpan};
21 use syntax::source_map::Spanned;
22 use rustc_target::spec::abi::Abi;
23 use syntax::ast::{self, CrateSugar, Ident, Name, NodeId, AsmDialect};
24 use syntax::ast::{Attribute, Label, LitKind, StrStyle, FloatTy, IntTy, UintTy};
25 use syntax::attr::{InlineAttr, OptimizeAttr};
26 use syntax::ext::hygiene::SyntaxContext;
27 use syntax::symbol::{Symbol, kw};
28 use syntax::tokenstream::TokenStream;
29 use syntax::util::parser::ExprPrecedence;
30 use crate::ty::AdtKind;
31 use crate::ty::query::Providers;
33 use rustc_data_structures::sync::{par_for_each_in, Send, Sync};
34 use rustc_data_structures::thin_vec::ThinVec;
35 use rustc_macros::HashStable;
37 use rustc_serialize::{self, Encoder, Encodable, Decoder, Decodable};
38 use std::collections::{BTreeSet, BTreeMap};
40 use smallvec::SmallVec;
42 /// HIR doesn't commit to a concrete storage type and has its own alias for a vector.
43 /// It can be `Vec`, `P<[T]>` or potentially `Box<[T]>`, or some other container with similar
44 /// behavior. Unlike AST, HIR is mostly a static structure, so we can use an owned slice instead
45 /// of `Vec` to avoid keeping extra capacity.
46 pub type HirVec<T> = P<[T]>;
48 macro_rules! hir_vec {
49 ($elem:expr; $n:expr) => (
50 $crate::hir::HirVec::from(vec![$elem; $n])
53 $crate::hir::HirVec::from(vec![$($x),*])
61 pub mod itemlikevisit;
69 /// Uniquely identifies a node in the HIR of the current crate. It is
70 /// composed of the `owner`, which is the `DefIndex` of the directly enclosing
71 /// `hir::Item`, `hir::TraitItem`, or `hir::ImplItem` (i.e., the closest "item-like"),
72 /// and the `local_id` which is unique within the given owner.
74 /// This two-level structure makes for more stable values: One can move an item
75 /// around within the source code, or add or remove stuff before it, without
76 /// the `local_id` part of the `HirId` changing, which is a very useful property in
77 /// incremental compilation where we have to persist things through changes to
79 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)]
82 pub local_id: ItemLocalId,
86 pub fn owner_def_id(self) -> DefId {
87 DefId::local(self.owner)
90 pub fn owner_local_def_id(self) -> LocalDefId {
91 LocalDefId::from_def_id(DefId::local(self.owner))
95 impl rustc_serialize::UseSpecializedEncodable for HirId {
96 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
107 impl rustc_serialize::UseSpecializedDecodable for HirId {
108 fn default_decode<D: Decoder>(d: &mut D) -> Result<HirId, D::Error> {
109 let owner = DefIndex::decode(d)?;
110 let local_id = ItemLocalId::decode(d)?;
119 impl fmt::Display for HirId {
120 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121 write!(f, "{:?}", self)
125 // Hack to ensure that we don't try to access the private parts of `ItemLocalId` in this module
126 mod item_local_id_inner {
127 use rustc_data_structures::indexed_vec::Idx;
128 use rustc_macros::HashStable;
130 /// An `ItemLocalId` uniquely identifies something within a given "item-like";
131 /// that is, within a `hir::Item`, `hir::TraitItem`, or `hir::ImplItem`. There is no
132 /// guarantee that the numerical value of a given `ItemLocalId` corresponds to
133 /// the node's position within the owning item in any way, but there is a
134 /// guarantee that the `LocalItemId`s within an owner occupy a dense range of
135 /// integers starting at zero, so a mapping that maps all or most nodes within
136 /// an "item-like" to something else can be implemented by a `Vec` instead of a
137 /// tree or hash map.
138 pub struct ItemLocalId {
144 pub use self::item_local_id_inner::ItemLocalId;
146 /// The `HirId` corresponding to `CRATE_NODE_ID` and `CRATE_DEF_INDEX`.
147 pub const CRATE_HIR_ID: HirId = HirId {
148 owner: CRATE_DEF_INDEX,
149 local_id: ItemLocalId::from_u32_const(0)
152 pub const DUMMY_HIR_ID: HirId = HirId {
153 owner: CRATE_DEF_INDEX,
154 local_id: DUMMY_ITEM_LOCAL_ID,
157 pub const DUMMY_ITEM_LOCAL_ID: ItemLocalId = ItemLocalId::MAX;
159 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, HashStable)]
160 pub struct Lifetime {
164 /// Either "`'a`", referring to a named lifetime definition,
165 /// or "``" (i.e., `kw::Invalid`), for elision placeholders.
167 /// HIR lowering inserts these placeholders in type paths that
168 /// refer to type definitions needing lifetime parameters,
169 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
170 pub name: LifetimeName,
173 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy, HashStable)]
175 /// Some user-given name like `T` or `'x`.
178 /// Synthetic name generated when user elided a lifetime in an impl header.
180 /// E.g., the lifetimes in cases like these:
182 /// impl Foo for &u32
183 /// impl Foo<'_> for u32
185 /// in that case, we rewrite to
187 /// impl<'f> Foo for &'f u32
188 /// impl<'f> Foo<'f> for u32
190 /// where `'f` is something like `Fresh(0)`. The indices are
191 /// unique per impl, but not necessarily continuous.
194 /// Indicates an illegal name was given and an error has been
195 /// repored (so we should squelch other derived errors). Occurs
196 /// when, e.g., `'_` is used in the wrong place.
201 pub fn ident(&self) -> Ident {
203 ParamName::Plain(ident) => ident,
204 ParamName::Fresh(_) |
205 ParamName::Error => Ident::with_dummy_span(kw::UnderscoreLifetime),
209 pub fn modern(&self) -> ParamName {
211 ParamName::Plain(ident) => ParamName::Plain(ident.modern()),
212 param_name => param_name,
217 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy, HashStable)]
218 pub enum LifetimeName {
219 /// User-given names or fresh (synthetic) names.
222 /// User wrote nothing (e.g., the lifetime in `&u32`).
225 /// Indicates an error during lowering (usually `'_` in wrong place)
226 /// that was already reported.
229 /// User wrote specifies `'_`.
232 /// User wrote `'static`.
237 pub fn ident(&self) -> Ident {
239 LifetimeName::Implicit | LifetimeName::Error => Ident::invalid(),
240 LifetimeName::Underscore => Ident::with_dummy_span(kw::UnderscoreLifetime),
241 LifetimeName::Static => Ident::with_dummy_span(kw::StaticLifetime),
242 LifetimeName::Param(param_name) => param_name.ident(),
246 pub fn is_elided(&self) -> bool {
248 LifetimeName::Implicit | LifetimeName::Underscore => true,
250 // It might seem surprising that `Fresh(_)` counts as
251 // *not* elided -- but this is because, as far as the code
252 // in the compiler is concerned -- `Fresh(_)` variants act
253 // equivalently to "some fresh name". They correspond to
254 // early-bound regions on an impl, in other words.
255 LifetimeName::Error | LifetimeName::Param(_) | LifetimeName::Static => false,
259 fn is_static(&self) -> bool {
260 self == &LifetimeName::Static
263 pub fn modern(&self) -> LifetimeName {
265 LifetimeName::Param(param_name) => LifetimeName::Param(param_name.modern()),
266 lifetime_name => lifetime_name,
271 impl fmt::Display for Lifetime {
272 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
273 self.name.ident().fmt(f)
277 impl fmt::Debug for Lifetime {
278 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
282 print::to_string(print::NO_ANN, |s| s.print_lifetime(self)))
287 pub fn is_elided(&self) -> bool {
288 self.name.is_elided()
291 pub fn is_static(&self) -> bool {
292 self.name.is_static()
296 /// A `Path` is essentially Rust's notion of a name; for instance,
297 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
298 /// along with a bunch of supporting information.
299 #[derive(RustcEncodable, RustcDecodable, HashStable)]
302 /// The resolution for the path.
304 /// The segments in the path: the things separated by `::`.
305 pub segments: HirVec<PathSegment>,
309 pub fn is_global(&self) -> bool {
310 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
314 impl fmt::Debug for Path {
315 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
316 write!(f, "path({})", self)
320 impl fmt::Display for Path {
321 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
322 write!(f, "{}", print::to_string(print::NO_ANN, |s| s.print_path(self, false)))
326 /// A segment of a path: an identifier, an optional lifetime, and a set of
328 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
329 pub struct PathSegment {
330 /// The identifier portion of this path segment.
331 #[stable_hasher(project(name))]
333 // `id` and `res` are optional. We currently only use these in save-analysis,
334 // any path segments without these will not have save-analysis info and
335 // therefore will not have 'jump to def' in IDEs, but otherwise will not be
336 // affected. (In general, we don't bother to get the defs for synthesized
337 // segments, only for segments which have come from the AST).
338 pub hir_id: Option<HirId>,
339 pub res: Option<Res>,
341 /// Type/lifetime parameters attached to this path. They come in
342 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
343 /// this is more than just simple syntactic sugar; the use of
344 /// parens affects the region binding rules, so we preserve the
346 pub args: Option<P<GenericArgs>>,
348 /// Whether to infer remaining type parameters, if any.
349 /// This only applies to expression and pattern paths, and
350 /// out of those only the segments with no type parameters
351 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
352 pub infer_args: bool,
356 /// Converts an identifier to the corresponding segment.
357 pub fn from_ident(ident: Ident) -> PathSegment {
369 hir_id: Option<HirId>,
379 args: if args.is_empty() {
387 pub fn generic_args(&self) -> &GenericArgs {
388 if let Some(ref args) = self.args {
391 const DUMMY: &GenericArgs = &GenericArgs::none();
397 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
398 pub struct ConstArg {
399 pub value: AnonConst,
403 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
404 pub enum GenericArg {
411 pub fn span(&self) -> Span {
413 GenericArg::Lifetime(l) => l.span,
414 GenericArg::Type(t) => t.span,
415 GenericArg::Const(c) => c.span,
419 pub fn id(&self) -> HirId {
421 GenericArg::Lifetime(l) => l.hir_id,
422 GenericArg::Type(t) => t.hir_id,
423 GenericArg::Const(c) => c.value.hir_id,
427 pub fn is_const(&self) -> bool {
429 GenericArg::Const(_) => true,
435 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
436 pub struct GenericArgs {
437 /// The generic arguments for this path segment.
438 pub args: HirVec<GenericArg>,
439 /// Bindings (equality constraints) on associated types, if present.
440 /// E.g., `Foo<A = Bar>`.
441 pub bindings: HirVec<TypeBinding>,
442 /// Were arguments written in parenthesized form `Fn(T) -> U`?
443 /// This is required mostly for pretty-printing and diagnostics,
444 /// but also for changing lifetime elision rules to be "function-like".
445 pub parenthesized: bool,
449 pub const fn none() -> Self {
452 bindings: HirVec::new(),
453 parenthesized: false,
457 pub fn is_empty(&self) -> bool {
458 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
461 pub fn inputs(&self) -> &[Ty] {
462 if self.parenthesized {
463 for arg in &self.args {
465 GenericArg::Lifetime(_) => {}
466 GenericArg::Type(ref ty) => {
467 if let TyKind::Tup(ref tys) = ty.node {
472 GenericArg::Const(_) => {}
476 bug!("GenericArgs::inputs: not a `Fn(T) -> U`");
479 pub fn own_counts(&self) -> GenericParamCount {
480 // We could cache this as a property of `GenericParamCount`, but
481 // the aim is to refactor this away entirely eventually and the
482 // presence of this method will be a constant reminder.
483 let mut own_counts: GenericParamCount = Default::default();
485 for arg in &self.args {
487 GenericArg::Lifetime(_) => own_counts.lifetimes += 1,
488 GenericArg::Type(_) => own_counts.types += 1,
489 GenericArg::Const(_) => own_counts.consts += 1,
497 /// A modifier on a bound, currently this is only used for `?Sized`, where the
498 /// modifier is `Maybe`. Negative bounds should also be handled here.
499 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
500 pub enum TraitBoundModifier {
505 /// The AST represents all type param bounds as types.
506 /// `typeck::collect::compute_bounds` matches these against
507 /// the "special" built-in traits (see `middle::lang_items`) and
508 /// detects `Copy`, `Send` and `Sync`.
509 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
510 pub enum GenericBound {
511 Trait(PolyTraitRef, TraitBoundModifier),
516 pub fn span(&self) -> Span {
518 &GenericBound::Trait(ref t, ..) => t.span,
519 &GenericBound::Outlives(ref l) => l.span,
524 pub type GenericBounds = HirVec<GenericBound>;
526 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable)]
527 pub enum LifetimeParamKind {
528 // Indicates that the lifetime definition was explicitly declared (e.g., in
529 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
532 // Indicates that the lifetime definition was synthetically added
533 // as a result of an in-band lifetime usage (e.g., in
534 // `fn foo(x: &'a u8) -> &'a u8 { x }`).
537 // Indication that the lifetime was elided (e.g., in both cases in
538 // `fn foo(x: &u8) -> &'_ u8 { x }`).
541 // Indication that the lifetime name was somehow in error.
545 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
546 pub enum GenericParamKind {
547 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
549 kind: LifetimeParamKind,
552 default: Option<P<Ty>>,
553 synthetic: Option<SyntheticTyParamKind>,
560 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
561 pub struct GenericParam {
564 pub attrs: HirVec<Attribute>,
565 pub bounds: GenericBounds,
567 pub pure_wrt_drop: bool,
568 pub kind: GenericParamKind,
572 pub struct GenericParamCount {
573 pub lifetimes: usize,
578 /// Represents lifetimes and type parameters attached to a declaration
579 /// of a function, enum, trait, etc.
580 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
581 pub struct Generics {
582 pub params: HirVec<GenericParam>,
583 pub where_clause: WhereClause,
588 pub const fn empty() -> Generics {
590 params: HirVec::new(),
591 where_clause: WhereClause {
592 predicates: HirVec::new(),
599 pub fn own_counts(&self) -> GenericParamCount {
600 // We could cache this as a property of `GenericParamCount`, but
601 // the aim is to refactor this away entirely eventually and the
602 // presence of this method will be a constant reminder.
603 let mut own_counts: GenericParamCount = Default::default();
605 for param in &self.params {
607 GenericParamKind::Lifetime { .. } => own_counts.lifetimes += 1,
608 GenericParamKind::Type { .. } => own_counts.types += 1,
609 GenericParamKind::Const { .. } => own_counts.consts += 1,
616 pub fn get_named(&self, name: InternedString) -> Option<&GenericParam> {
617 for param in &self.params {
618 if name == param.name.ident().as_interned_str() {
625 pub fn spans(&self) -> MultiSpan {
626 if self.params.is_empty() {
629 self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
634 /// Synthetic type parameters are converted to another form during lowering; this allows
635 /// us to track the original form they had, and is useful for error messages.
636 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
637 pub enum SyntheticTyParamKind {
641 /// A where-clause in a definition.
642 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
643 pub struct WhereClause {
644 pub predicates: HirVec<WherePredicate>,
645 // Only valid if predicates isn't empty.
650 pub fn span(&self) -> Option<Span> {
651 if self.predicates.is_empty() {
659 /// A single predicate in a where-clause.
660 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
661 pub enum WherePredicate {
662 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
663 BoundPredicate(WhereBoundPredicate),
664 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
665 RegionPredicate(WhereRegionPredicate),
666 /// An equality predicate (unsupported).
667 EqPredicate(WhereEqPredicate),
670 impl WherePredicate {
671 pub fn span(&self) -> Span {
673 &WherePredicate::BoundPredicate(ref p) => p.span,
674 &WherePredicate::RegionPredicate(ref p) => p.span,
675 &WherePredicate::EqPredicate(ref p) => p.span,
680 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
681 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
682 pub struct WhereBoundPredicate {
684 /// Any generics from a `for` binding.
685 pub bound_generic_params: HirVec<GenericParam>,
686 /// The type being bounded.
687 pub bounded_ty: P<Ty>,
688 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
689 pub bounds: GenericBounds,
692 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
693 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
694 pub struct WhereRegionPredicate {
696 pub lifetime: Lifetime,
697 pub bounds: GenericBounds,
700 /// An equality predicate (e.g., `T = int`); currently unsupported.
701 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
702 pub struct WhereEqPredicate {
709 #[derive(RustcEncodable, RustcDecodable, Debug)]
710 pub struct ModuleItems {
711 // Use BTreeSets here so items are in the same order as in the
712 // list of all items in Crate
713 pub items: BTreeSet<HirId>,
714 pub trait_items: BTreeSet<TraitItemId>,
715 pub impl_items: BTreeSet<ImplItemId>,
718 /// The top-level data structure that stores the entire contents of
719 /// the crate currently being compiled.
721 /// For more details, see the [rustc guide].
723 /// [rustc guide]: https://rust-lang.github.io/rustc-guide/hir.html
724 #[derive(RustcEncodable, RustcDecodable, Debug)]
727 pub attrs: HirVec<Attribute>,
729 pub exported_macros: HirVec<MacroDef>,
730 // Attributes from non-exported macros, kept only for collecting the library feature list.
731 pub non_exported_macro_attrs: HirVec<Attribute>,
733 // N.B., we use a BTreeMap here so that `visit_all_items` iterates
734 // over the ids in increasing order. In principle it should not
735 // matter what order we visit things in, but in *practice* it
736 // does, because it can affect the order in which errors are
737 // detected, which in turn can make compile-fail tests yield
738 // slightly different results.
739 pub items: BTreeMap<HirId, Item>,
741 pub trait_items: BTreeMap<TraitItemId, TraitItem>,
742 pub impl_items: BTreeMap<ImplItemId, ImplItem>,
743 pub bodies: BTreeMap<BodyId, Body>,
744 pub trait_impls: BTreeMap<DefId, Vec<HirId>>,
746 /// A list of the body ids written out in the order in which they
747 /// appear in the crate. If you're going to process all the bodies
748 /// in the crate, you should iterate over this list rather than the keys
750 pub body_ids: Vec<BodyId>,
752 /// A list of modules written out in the order in which they
753 /// appear in the crate. This includes the main crate module.
754 pub modules: BTreeMap<NodeId, ModuleItems>,
758 pub fn item(&self, id: HirId) -> &Item {
762 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem {
763 &self.trait_items[&id]
766 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem {
767 &self.impl_items[&id]
770 /// Visits all items in the crate in some deterministic (but
771 /// unspecified) order. If you just need to process every item,
772 /// but don't care about nesting, this method is the best choice.
774 /// If you do care about nesting -- usually because your algorithm
775 /// follows lexical scoping rules -- then you want a different
776 /// approach. You should override `visit_nested_item` in your
777 /// visitor and then call `intravisit::walk_crate` instead.
778 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
779 where V: itemlikevisit::ItemLikeVisitor<'hir>
781 for (_, item) in &self.items {
782 visitor.visit_item(item);
785 for (_, trait_item) in &self.trait_items {
786 visitor.visit_trait_item(trait_item);
789 for (_, impl_item) in &self.impl_items {
790 visitor.visit_impl_item(impl_item);
794 /// A parallel version of `visit_all_item_likes`.
795 pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
796 where V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send
799 par_for_each_in(&self.items, |(_, item)| {
800 visitor.visit_item(item);
803 par_for_each_in(&self.trait_items, |(_, trait_item)| {
804 visitor.visit_trait_item(trait_item);
807 par_for_each_in(&self.impl_items, |(_, impl_item)| {
808 visitor.visit_impl_item(impl_item);
813 pub fn body(&self, id: BodyId) -> &Body {
818 /// A macro definition, in this crate or imported from another.
820 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
821 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
822 pub struct MacroDef {
825 pub attrs: HirVec<Attribute>,
828 pub body: TokenStream,
832 /// A block of statements `{ .. }`, which may have a label (in this case the
833 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
834 /// the `rules` being anything but `DefaultBlock`.
835 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
837 /// Statements in a block.
838 pub stmts: HirVec<Stmt>,
839 /// An expression at the end of the block
840 /// without a semicolon, if any.
841 pub expr: Option<P<Expr>>,
842 #[stable_hasher(ignore)]
844 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
845 pub rules: BlockCheckMode,
847 /// If true, then there may exist `break 'a` values that aim to
848 /// break out of this block early.
849 /// Used by `'label: {}` blocks and by `catch` statements.
850 pub targeted_by_break: bool,
853 #[derive(RustcEncodable, RustcDecodable, HashStable)]
855 #[stable_hasher(ignore)]
861 impl fmt::Debug for Pat {
862 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
863 write!(f, "pat({}: {})", self.hir_id,
864 print::to_string(print::NO_ANN, |s| s.print_pat(self)))
869 // FIXME(#19596) this is a workaround, but there should be a better way
870 fn walk_<G>(&self, it: &mut G) -> bool
871 where G: FnMut(&Pat) -> bool
878 PatKind::Binding(.., Some(ref p)) => p.walk_(it),
879 PatKind::Struct(_, ref fields, _) => {
880 fields.iter().all(|field| field.pat.walk_(it))
882 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
883 s.iter().all(|p| p.walk_(it))
885 PatKind::Box(ref s) | PatKind::Ref(ref s, _) => {
888 PatKind::Slice(ref before, ref slice, ref after) => {
892 .all(|p| p.walk_(it))
897 PatKind::Binding(..) |
898 PatKind::Path(_) => {
904 pub fn walk<F>(&self, mut it: F) -> bool
905 where F: FnMut(&Pat) -> bool
911 /// A single field in a struct pattern.
913 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
914 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
915 /// except `is_shorthand` is true.
916 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
917 pub struct FieldPat {
918 #[stable_hasher(ignore)]
920 /// The identifier for the field.
921 #[stable_hasher(project(name))]
923 /// The pattern the field is destructured to.
925 pub is_shorthand: bool,
929 /// Explicit binding annotations given in the HIR for a binding. Note
930 /// that this is not the final binding *mode* that we infer after type
932 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
933 pub enum BindingAnnotation {
934 /// No binding annotation given: this means that the final binding mode
935 /// will depend on whether we have skipped through a `&` reference
936 /// when matching. For example, the `x` in `Some(x)` will have binding
937 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
938 /// ultimately be inferred to be by-reference.
940 /// Note that implicit reference skipping is not implemented yet (#42640).
943 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
946 /// Annotated as `ref`, like `ref x`
949 /// Annotated as `ref mut x`.
953 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
959 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
961 /// Represents a wildcard pattern (i.e., `_`).
964 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
965 /// The `HirId` is the canonical ID for the variable being bound,
966 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
967 /// which is the pattern ID of the first `x`.
968 Binding(BindingAnnotation, HirId, Ident, Option<P<Pat>>),
970 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
971 /// The `bool` is `true` in the presence of a `..`.
972 Struct(QPath, HirVec<FieldPat>, bool),
974 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
975 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
976 /// `0 <= position <= subpats.len()`
977 TupleStruct(QPath, HirVec<P<Pat>>, Option<usize>),
979 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
982 /// A tuple pattern (e.g., `(a, b)`).
983 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
984 /// `0 <= position <= subpats.len()`
985 Tuple(HirVec<P<Pat>>, Option<usize>),
990 /// A reference pattern (e.g., `&mut (a, b)`).
991 Ref(P<Pat>, Mutability),
996 /// A range pattern (e.g., `1..=2` or `1..2`).
997 Range(P<Expr>, P<Expr>, RangeEnd),
999 /// `[a, b, ..i, y, z]` is represented as:
1000 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`.
1001 Slice(HirVec<P<Pat>>, Option<P<Pat>>, HirVec<P<Pat>>),
1004 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, HashStable,
1005 RustcEncodable, RustcDecodable, Hash, Debug)]
1006 pub enum Mutability {
1012 /// Returns `MutMutable` only if both arguments are mutable.
1013 pub fn and(self, other: Self) -> Self {
1015 MutMutable => other,
1016 MutImmutable => MutImmutable,
1021 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Hash, HashStable)]
1022 pub enum BinOpKind {
1023 /// The `+` operator (addition).
1025 /// The `-` operator (subtraction).
1027 /// The `*` operator (multiplication).
1029 /// The `/` operator (division).
1031 /// The `%` operator (modulus).
1033 /// The `&&` operator (logical and).
1035 /// The `||` operator (logical or).
1037 /// The `^` operator (bitwise xor).
1039 /// The `&` operator (bitwise and).
1041 /// The `|` operator (bitwise or).
1043 /// The `<<` operator (shift left).
1045 /// The `>>` operator (shift right).
1047 /// The `==` operator (equality).
1049 /// The `<` operator (less than).
1051 /// The `<=` operator (less than or equal to).
1053 /// The `!=` operator (not equal to).
1055 /// The `>=` operator (greater than or equal to).
1057 /// The `>` operator (greater than).
1062 pub fn as_str(self) -> &'static str {
1064 BinOpKind::Add => "+",
1065 BinOpKind::Sub => "-",
1066 BinOpKind::Mul => "*",
1067 BinOpKind::Div => "/",
1068 BinOpKind::Rem => "%",
1069 BinOpKind::And => "&&",
1070 BinOpKind::Or => "||",
1071 BinOpKind::BitXor => "^",
1072 BinOpKind::BitAnd => "&",
1073 BinOpKind::BitOr => "|",
1074 BinOpKind::Shl => "<<",
1075 BinOpKind::Shr => ">>",
1076 BinOpKind::Eq => "==",
1077 BinOpKind::Lt => "<",
1078 BinOpKind::Le => "<=",
1079 BinOpKind::Ne => "!=",
1080 BinOpKind::Ge => ">=",
1081 BinOpKind::Gt => ">",
1085 pub fn is_lazy(self) -> bool {
1087 BinOpKind::And | BinOpKind::Or => true,
1092 pub fn is_shift(self) -> bool {
1094 BinOpKind::Shl | BinOpKind::Shr => true,
1099 pub fn is_comparison(self) -> bool {
1106 BinOpKind::Ge => true,
1118 BinOpKind::Shr => false,
1122 /// Returns `true` if the binary operator takes its arguments by value.
1123 pub fn is_by_value(self) -> bool {
1124 !self.is_comparison()
1128 impl Into<ast::BinOpKind> for BinOpKind {
1129 fn into(self) -> ast::BinOpKind {
1131 BinOpKind::Add => ast::BinOpKind::Add,
1132 BinOpKind::Sub => ast::BinOpKind::Sub,
1133 BinOpKind::Mul => ast::BinOpKind::Mul,
1134 BinOpKind::Div => ast::BinOpKind::Div,
1135 BinOpKind::Rem => ast::BinOpKind::Rem,
1136 BinOpKind::And => ast::BinOpKind::And,
1137 BinOpKind::Or => ast::BinOpKind::Or,
1138 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1139 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1140 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1141 BinOpKind::Shl => ast::BinOpKind::Shl,
1142 BinOpKind::Shr => ast::BinOpKind::Shr,
1143 BinOpKind::Eq => ast::BinOpKind::Eq,
1144 BinOpKind::Lt => ast::BinOpKind::Lt,
1145 BinOpKind::Le => ast::BinOpKind::Le,
1146 BinOpKind::Ne => ast::BinOpKind::Ne,
1147 BinOpKind::Ge => ast::BinOpKind::Ge,
1148 BinOpKind::Gt => ast::BinOpKind::Gt,
1153 pub type BinOp = Spanned<BinOpKind>;
1155 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Hash, HashStable)]
1157 /// The `*` operator (deferencing).
1159 /// The `!` operator (logical negation).
1161 /// The `-` operator (negation).
1166 pub fn as_str(self) -> &'static str {
1174 /// Returns `true` if the unary operator takes its argument by value.
1175 pub fn is_by_value(self) -> bool {
1177 UnNeg | UnNot => true,
1184 #[derive(RustcEncodable, RustcDecodable)]
1191 impl fmt::Debug for Stmt {
1192 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1193 write!(f, "stmt({}: {})", self.hir_id,
1194 print::to_string(print::NO_ANN, |s| s.print_stmt(self)))
1198 /// The contents of a statement.
1199 #[derive(RustcEncodable, RustcDecodable, HashStable)]
1201 /// A local (`let`) binding.
1204 /// An item binding.
1207 /// An expression without a trailing semi-colon (must have unit type).
1210 /// An expression with a trailing semi-colon (may have any type).
1215 pub fn attrs(&self) -> &[Attribute] {
1217 StmtKind::Local(ref l) => &l.attrs,
1218 StmtKind::Item(_) => &[],
1219 StmtKind::Expr(ref e) |
1220 StmtKind::Semi(ref e) => &e.attrs,
1225 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1226 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1229 /// Type annotation, if any (otherwise the type will be inferred).
1230 pub ty: Option<P<Ty>>,
1231 /// Initializer expression to set the value, if any.
1232 pub init: Option<P<Expr>>,
1235 pub attrs: ThinVec<Attribute>,
1236 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1237 /// desugaring. Otherwise will be `Normal`.
1238 pub source: LocalSource,
1241 /// Represents a single arm of a `match` expression, e.g.
1242 /// `<pats> (if <guard>) => <body>`.
1243 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1245 #[stable_hasher(ignore)]
1248 pub attrs: HirVec<Attribute>,
1249 /// Multiple patterns can be combined with `|`
1250 pub pats: HirVec<P<Pat>>,
1251 /// Optional guard clause.
1252 pub guard: Option<Guard>,
1253 /// The expression the arm evaluates to if this arm matches.
1257 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1262 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1264 #[stable_hasher(ignore)]
1269 pub is_shorthand: bool,
1272 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1273 pub enum BlockCheckMode {
1275 UnsafeBlock(UnsafeSource),
1276 PushUnsafeBlock(UnsafeSource),
1277 PopUnsafeBlock(UnsafeSource),
1280 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1281 pub enum UnsafeSource {
1286 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1291 /// The body of a function, closure, or constant value. In the case of
1292 /// a function, the body contains not only the function body itself
1293 /// (which is an expression), but also the argument patterns, since
1294 /// those are something that the caller doesn't really care about.
1299 /// fn foo((x, y): (u32, u32)) -> u32 {
1304 /// Here, the `Body` associated with `foo()` would contain:
1306 /// - an `arguments` array containing the `(x, y)` pattern
1307 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1308 /// - `generator_kind` would be `None`
1310 /// All bodies have an **owner**, which can be accessed via the HIR
1311 /// map using `body_owner_def_id()`.
1312 #[derive(RustcEncodable, RustcDecodable, Debug)]
1314 pub arguments: HirVec<Arg>,
1316 pub generator_kind: Option<GeneratorKind>,
1320 pub fn id(&self) -> BodyId {
1322 hir_id: self.value.hir_id,
1327 /// The type of source expression that caused this generator to be created.
1328 // Not `IsAsync` because we want to eventually add support for `AsyncGen`
1329 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, HashStable,
1330 RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1331 pub enum GeneratorKind {
1332 /// An `async` block or function.
1334 /// A generator literal created via a `yield` inside a closure.
1338 impl fmt::Display for GeneratorKind {
1339 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1340 f.write_str(match self {
1341 GeneratorKind::Async => "`async` object",
1342 GeneratorKind::Gen => "generator",
1347 #[derive(Copy, Clone, Debug)]
1348 pub enum BodyOwnerKind {
1349 /// Functions and methods.
1355 /// Constants and associated constants.
1358 /// Initializer of a `static` item.
1362 impl BodyOwnerKind {
1363 pub fn is_fn_or_closure(self) -> bool {
1365 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1366 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1372 pub type Lit = Spanned<LitKind>;
1374 /// A constant (expression) that's not an item or associated item,
1375 /// but needs its own `DefId` for type-checking, const-eval, etc.
1376 /// These are usually found nested inside types (e.g., array lengths)
1377 /// or expressions (e.g., repeat counts), and also used to define
1378 /// explicit discriminant values for enum variants.
1379 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1380 pub struct AnonConst {
1386 #[derive(RustcEncodable, RustcDecodable)]
1390 pub attrs: ThinVec<Attribute>,
1394 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1395 #[cfg(target_arch = "x86_64")]
1396 static_assert_size!(Expr, 72);
1399 pub fn precedence(&self) -> ExprPrecedence {
1401 ExprKind::Box(_) => ExprPrecedence::Box,
1402 ExprKind::Array(_) => ExprPrecedence::Array,
1403 ExprKind::Call(..) => ExprPrecedence::Call,
1404 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1405 ExprKind::Tup(_) => ExprPrecedence::Tup,
1406 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1407 ExprKind::Unary(..) => ExprPrecedence::Unary,
1408 ExprKind::Lit(_) => ExprPrecedence::Lit,
1409 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1410 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1411 ExprKind::Loop(..) => ExprPrecedence::Loop,
1412 ExprKind::Match(..) => ExprPrecedence::Match,
1413 ExprKind::Closure(..) => ExprPrecedence::Closure,
1414 ExprKind::Block(..) => ExprPrecedence::Block,
1415 ExprKind::Assign(..) => ExprPrecedence::Assign,
1416 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1417 ExprKind::Field(..) => ExprPrecedence::Field,
1418 ExprKind::Index(..) => ExprPrecedence::Index,
1419 ExprKind::Path(..) => ExprPrecedence::Path,
1420 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1421 ExprKind::Break(..) => ExprPrecedence::Break,
1422 ExprKind::Continue(..) => ExprPrecedence::Continue,
1423 ExprKind::Ret(..) => ExprPrecedence::Ret,
1424 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1425 ExprKind::Struct(..) => ExprPrecedence::Struct,
1426 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1427 ExprKind::Yield(..) => ExprPrecedence::Yield,
1428 ExprKind::Err => ExprPrecedence::Err,
1432 pub fn is_place_expr(&self) -> bool {
1434 ExprKind::Path(QPath::Resolved(_, ref path)) => {
1437 | Res::Def(DefKind::Static, _)
1443 ExprKind::Type(ref e, _) => {
1447 ExprKind::Unary(UnDeref, _) |
1448 ExprKind::Field(..) |
1449 ExprKind::Index(..) => {
1453 // Partially qualified paths in expressions can only legally
1454 // refer to associated items which are always rvalues.
1455 ExprKind::Path(QPath::TypeRelative(..)) |
1457 ExprKind::Call(..) |
1458 ExprKind::MethodCall(..) |
1459 ExprKind::Struct(..) |
1461 ExprKind::Match(..) |
1462 ExprKind::Closure(..) |
1463 ExprKind::Block(..) |
1464 ExprKind::Repeat(..) |
1465 ExprKind::Array(..) |
1466 ExprKind::Break(..) |
1467 ExprKind::Continue(..) |
1469 ExprKind::Loop(..) |
1470 ExprKind::Assign(..) |
1471 ExprKind::InlineAsm(..) |
1472 ExprKind::AssignOp(..) |
1474 ExprKind::Unary(..) |
1476 ExprKind::AddrOf(..) |
1477 ExprKind::Binary(..) |
1478 ExprKind::Yield(..) |
1479 ExprKind::Cast(..) |
1480 ExprKind::DropTemps(..) |
1488 impl fmt::Debug for Expr {
1489 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1490 write!(f, "expr({}: {})", self.hir_id,
1491 print::to_string(print::NO_ANN, |s| s.print_expr(self)))
1495 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1497 /// A `box x` expression.
1499 /// An array (e.g., `[a, b, c, d]`).
1500 Array(HirVec<Expr>),
1501 /// A function call.
1503 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1504 /// and the second field is the list of arguments.
1505 /// This also represents calling the constructor of
1506 /// tuple-like ADTs such as tuple structs and enum variants.
1507 Call(P<Expr>, HirVec<Expr>),
1508 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1510 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1511 /// (within the angle brackets).
1512 /// The first element of the vector of `Expr`s is the expression that evaluates
1513 /// to the object on which the method is being called on (the receiver),
1514 /// and the remaining elements are the rest of the arguments.
1515 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1516 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1517 MethodCall(P<PathSegment>, Span, HirVec<Expr>),
1518 /// A tuple (e.g., `(a, b, c ,d)`).
1520 /// A binary operation (e.g., `a + b`, `a * b`).
1521 Binary(BinOp, P<Expr>, P<Expr>),
1522 /// A unary operation (e.g., `!x`, `*x`).
1523 Unary(UnOp, P<Expr>),
1524 /// A literal (e.g., `1`, `"foo"`).
1526 /// A cast (e.g., `foo as f64`).
1527 Cast(P<Expr>, P<Ty>),
1528 /// A type reference (e.g., `Foo`).
1529 Type(P<Expr>, P<Ty>),
1530 /// Wraps the expression in a terminating scope.
1531 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1533 /// This construct only exists to tweak the drop order in HIR lowering.
1534 /// An example of that is the desugaring of `for` loops.
1536 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1538 /// I.e., `'label: loop { <block> }`.
1539 Loop(P<Block>, Option<Label>, LoopSource),
1540 /// A `match` block, with a source that indicates whether or not it is
1541 /// the result of a desugaring, and if so, which kind.
1542 Match(P<Expr>, HirVec<Arm>, MatchSource),
1543 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1545 /// The `Span` is the argument block `|...|`.
1547 /// This may also be a generator literal or an `async block` as indicated by the
1548 /// `Option<GeneratorMovability>`.
1549 Closure(CaptureClause, P<FnDecl>, BodyId, Span, Option<GeneratorMovability>),
1550 /// A block (e.g., `'label: { ... }`).
1551 Block(P<Block>, Option<Label>),
1553 /// An assignment (e.g., `a = foo()`).
1554 Assign(P<Expr>, P<Expr>),
1555 /// An assignment with an operator.
1558 AssignOp(BinOp, P<Expr>, P<Expr>),
1559 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1560 Field(P<Expr>, Ident),
1561 /// An indexing operation (`foo[2]`).
1562 Index(P<Expr>, P<Expr>),
1564 /// Path to a definition, possibly containing lifetime or type parameters.
1567 /// A referencing operation (i.e., `&a` or `&mut a`).
1568 AddrOf(Mutability, P<Expr>),
1569 /// A `break`, with an optional label to break.
1570 Break(Destination, Option<P<Expr>>),
1571 /// A `continue`, with an optional label.
1572 Continue(Destination),
1573 /// A `return`, with an optional value to be returned.
1574 Ret(Option<P<Expr>>),
1576 /// Inline assembly (from `asm!`), with its outputs and inputs.
1577 InlineAsm(P<InlineAsm>, HirVec<Expr>, HirVec<Expr>),
1579 /// A struct or struct-like variant literal expression.
1581 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1582 /// where `base` is the `Option<Expr>`.
1583 Struct(P<QPath>, HirVec<Field>, Option<P<Expr>>),
1585 /// An array literal constructed from one repeated element.
1587 /// E.g., `[1; 5]`. The first expression is the element
1588 /// to be repeated; the second is the number of times to repeat it.
1589 Repeat(P<Expr>, AnonConst),
1591 /// A suspension point for generators (i.e., `yield <expr>`).
1592 Yield(P<Expr>, YieldSource),
1594 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1598 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1599 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1601 /// Path to a definition, optionally "fully-qualified" with a `Self`
1602 /// type, if the path points to an associated item in a trait.
1604 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1605 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1606 /// even though they both have the same two-segment `Clone::clone` `Path`.
1607 Resolved(Option<P<Ty>>, P<Path>),
1609 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1610 /// Will be resolved by type-checking to an associated item.
1612 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1613 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1614 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1615 TypeRelative(P<Ty>, P<PathSegment>)
1618 /// Hints at the original code for a let statement.
1619 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1620 pub enum LocalSource {
1621 /// A `match _ { .. }`.
1623 /// A desugared `for _ in _ { .. }` loop.
1625 /// When lowering async functions, we create locals within the `async move` so that
1626 /// all arguments are dropped after the future is polled.
1628 /// ```ignore (pseudo-Rust)
1629 /// async fn foo(<pattern> @ x: Type) {
1631 /// let <pattern> = x;
1636 /// A desugared `<expr>.await`.
1640 /// Hints at the original code for a `match _ { .. }`.
1641 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
1642 pub enum MatchSource {
1643 /// A `match _ { .. }`.
1645 /// An `if _ { .. }` (optionally with `else { .. }`).
1647 contains_else_clause: bool,
1649 /// An `if let _ = _ { .. }` (optionally with `else { .. }`).
1651 contains_else_clause: bool,
1653 /// A `while _ { .. }` (which was desugared to a `loop { match _ { .. } }`).
1655 /// A `while let _ = _ { .. }` (which was desugared to a
1656 /// `loop { match _ { .. } }`).
1658 /// A desugared `for _ in _ { .. }` loop.
1660 /// A desugared `?` operator.
1662 /// A desugared `<expr>.await`.
1666 /// The loop type that yielded an `ExprKind::Loop`.
1667 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1668 pub enum LoopSource {
1669 /// A `loop { .. }` loop.
1671 /// A `while _ { .. }` loop.
1673 /// A `while let _ = _ { .. }` loop.
1675 /// A `for _ in _ { .. }` loop.
1680 pub fn name(self) -> &'static str {
1682 LoopSource::Loop => "loop",
1683 LoopSource::While => "while",
1684 LoopSource::WhileLet => "while let",
1685 LoopSource::ForLoop => "for",
1690 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1691 pub enum LoopIdError {
1693 UnlabeledCfInWhileCondition,
1697 impl fmt::Display for LoopIdError {
1698 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1699 f.write_str(match self {
1700 LoopIdError::OutsideLoopScope => "not inside loop scope",
1701 LoopIdError::UnlabeledCfInWhileCondition =>
1702 "unlabeled control flow (break or continue) in while condition",
1703 LoopIdError::UnresolvedLabel => "label not found",
1708 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1709 pub struct Destination {
1710 // This is `Some(_)` iff there is an explicit user-specified `label
1711 pub label: Option<Label>,
1713 // These errors are caught and then reported during the diagnostics pass in
1714 // librustc_passes/loops.rs
1715 pub target_id: Result<HirId, LoopIdError>,
1718 /// Whether a generator contains self-references, causing it to be `!Unpin`.
1719 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, HashStable,
1720 RustcEncodable, RustcDecodable, Hash, Debug)]
1721 pub enum GeneratorMovability {
1722 /// May contain self-references, `!Unpin`.
1724 /// Must not contain self-references, `Unpin`.
1728 /// The yield kind that caused an `ExprKind::Yield`.
1729 #[derive(Copy, Clone, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable, HashStable)]
1730 pub enum YieldSource {
1731 /// An `<expr>.await`.
1733 /// A plain `yield`.
1737 impl fmt::Display for YieldSource {
1738 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1739 f.write_str(match self {
1740 YieldSource::Await => "`await`",
1741 YieldSource::Yield => "`yield`",
1746 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1747 pub enum CaptureClause {
1752 // N.B., if you change this, you'll probably want to change the corresponding
1753 // type structure in middle/ty.rs as well.
1754 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1757 pub mutbl: Mutability,
1760 /// Represents a method's signature in a trait declaration or implementation.
1761 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1762 pub struct MethodSig {
1763 pub header: FnHeader,
1764 pub decl: P<FnDecl>,
1767 // The bodies for items are stored "out of line", in a separate
1768 // hashmap in the `Crate`. Here we just record the node-id of the item
1769 // so it can fetched later.
1770 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1771 pub struct TraitItemId {
1775 /// Represents an item declaration within a trait declaration,
1776 /// possibly including a default implementation. A trait item is
1777 /// either required (meaning it doesn't have an implementation, just a
1778 /// signature) or provided (meaning it has a default implementation).
1779 #[derive(RustcEncodable, RustcDecodable, Debug)]
1780 pub struct TraitItem {
1783 pub attrs: HirVec<Attribute>,
1784 pub generics: Generics,
1785 pub node: TraitItemKind,
1789 /// Represents a trait method's body (or just argument names).
1790 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1791 pub enum TraitMethod {
1792 /// No default body in the trait, just a signature.
1793 Required(HirVec<Ident>),
1795 /// Both signature and body are provided in the trait.
1799 /// Represents a trait method or associated constant or type
1800 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1801 pub enum TraitItemKind {
1802 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
1803 Const(P<Ty>, Option<BodyId>),
1804 /// A method with an optional body.
1805 Method(MethodSig, TraitMethod),
1806 /// An associated type with (possibly empty) bounds and optional concrete
1808 Type(GenericBounds, Option<P<Ty>>),
1811 // The bodies for items are stored "out of line", in a separate
1812 // hashmap in the `Crate`. Here we just record the node-id of the item
1813 // so it can fetched later.
1814 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1815 pub struct ImplItemId {
1819 /// Represents anything within an `impl` block.
1820 #[derive(RustcEncodable, RustcDecodable, Debug)]
1821 pub struct ImplItem {
1824 pub vis: Visibility,
1825 pub defaultness: Defaultness,
1826 pub attrs: HirVec<Attribute>,
1827 pub generics: Generics,
1828 pub node: ImplItemKind,
1832 /// Represents various kinds of content within an `impl`.
1833 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1834 pub enum ImplItemKind {
1835 /// An associated constant of the given type, set to the constant result
1836 /// of the expression.
1837 Const(P<Ty>, BodyId),
1838 /// A method implementation with the given signature and body.
1839 Method(MethodSig, BodyId),
1840 /// An associated type.
1842 /// An associated `type = impl Trait`.
1843 OpaqueTy(GenericBounds),
1846 /// Bind a type to an associated type (i.e., `A = Foo`).
1848 /// Bindings like `A: Debug` are represented as a special type `A =
1849 /// $::Debug` that is understood by the astconv code.
1851 /// FIXME(alexreg) -- why have a separate type for the binding case,
1852 /// wouldn't it be better to make the `ty` field an enum like:
1855 /// enum TypeBindingKind {
1860 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1861 pub struct TypeBinding {
1863 #[stable_hasher(project(name))]
1865 pub kind: TypeBindingKind,
1869 // Represents the two kinds of type bindings.
1870 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1871 pub enum TypeBindingKind {
1872 /// E.g., `Foo<Bar: Send>`.
1874 bounds: HirVec<GenericBound>,
1876 /// E.g., `Foo<Bar = ()>`.
1883 pub fn ty(&self) -> &Ty {
1885 TypeBindingKind::Equality { ref ty } => ty,
1886 _ => bug!("expected equality type binding for parenthesized generic args"),
1891 #[derive(RustcEncodable, RustcDecodable)]
1898 impl fmt::Debug for Ty {
1899 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1900 write!(f, "type({})",
1901 print::to_string(print::NO_ANN, |s| s.print_type(self)))
1905 /// Not represented directly in the AST; referred to by name through a `ty_path`.
1906 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
1916 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1917 pub struct BareFnTy {
1918 pub unsafety: Unsafety,
1920 pub generic_params: HirVec<GenericParam>,
1921 pub decl: P<FnDecl>,
1922 pub arg_names: HirVec<Ident>,
1925 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1926 pub struct OpaqueTy {
1927 pub generics: Generics,
1928 pub bounds: GenericBounds,
1929 pub impl_trait_fn: Option<DefId>,
1930 pub origin: OpaqueTyOrigin,
1933 /// From whence the opaque type came.
1934 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1935 pub enum OpaqueTyOrigin {
1936 /// `type Foo = impl Trait;`
1944 /// The various kinds of types recognized by the compiler.
1945 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1947 /// A variable length slice (i.e., `[T]`).
1949 /// A fixed length array (i.e., `[T; n]`).
1950 Array(P<Ty>, AnonConst),
1951 /// A raw pointer (i.e., `*const T` or `*mut T`).
1953 /// A reference (i.e., `&'a T` or `&'a mut T`).
1954 Rptr(Lifetime, MutTy),
1955 /// A bare function (e.g., `fn(usize) -> bool`).
1956 BareFn(P<BareFnTy>),
1957 /// The never type (`!`).
1959 /// A tuple (`(A, B, C, D, ...)`).
1961 /// A path to a type definition (`module::module::...::Type`), or an
1962 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
1964 /// Type parameters may be stored in each `PathSegment`.
1966 /// A type definition itself. This is currently only used for the `type Foo = impl Trait`
1967 /// item that `impl Trait` in return position desugars to.
1969 /// The generic argument list contains the lifetimes (and in the future possibly parameters)
1970 /// that are actually bound on the `impl Trait`.
1971 Def(ItemId, HirVec<GenericArg>),
1972 /// A trait object type `Bound1 + Bound2 + Bound3`
1973 /// where `Bound` is a trait or a lifetime.
1974 TraitObject(HirVec<PolyTraitRef>, Lifetime),
1977 /// `TyKind::Infer` means the type should be inferred instead of it having been
1978 /// specified. This can appear anywhere in a type.
1980 /// Placeholder for a type that has failed to be defined.
1982 /// Placeholder for C-variadic arguments. We "spoof" the `VaListImpl` created
1983 /// from the variadic arguments. This type is only valid up to typeck.
1987 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1988 pub struct InlineAsmOutput {
1989 pub constraint: Symbol,
1991 pub is_indirect: bool,
1995 // NOTE(eddyb) This is used within MIR as well, so unlike the rest of the HIR,
1996 // it needs to be `Clone` and use plain `Vec<T>` instead of `HirVec<T>`.
1997 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1998 pub struct InlineAsm {
2000 pub asm_str_style: StrStyle,
2001 pub outputs: Vec<InlineAsmOutput>,
2002 pub inputs: Vec<Symbol>,
2003 pub clobbers: Vec<Symbol>,
2005 pub alignstack: bool,
2006 pub dialect: AsmDialect,
2007 #[stable_hasher(ignore)] // This is used for error reporting
2008 pub ctxt: SyntaxContext,
2011 /// Represents an argument in a function header.
2012 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2014 pub attrs: HirVec<Attribute>,
2020 /// Represents the header (not the body) of a function declaration.
2021 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2023 /// The types of the function's arguments.
2025 /// Additional argument data is stored in the function's [body](Body::arguments).
2026 pub inputs: HirVec<Ty>,
2027 pub output: FunctionRetTy,
2028 pub c_variadic: bool,
2029 /// Does the function have an implicit self?
2030 pub implicit_self: ImplicitSelfKind,
2033 /// Represents what type of implicit self a function has, if any.
2034 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2035 pub enum ImplicitSelfKind {
2036 /// Represents a `fn x(self);`.
2038 /// Represents a `fn x(mut self);`.
2040 /// Represents a `fn x(&self);`.
2042 /// Represents a `fn x(&mut self);`.
2044 /// Represents when a function does not have a self argument or
2045 /// when a function has a `self: X` argument.
2049 impl ImplicitSelfKind {
2050 /// Does this represent an implicit self?
2051 pub fn has_implicit_self(&self) -> bool {
2053 ImplicitSelfKind::None => false,
2059 /// Is the trait definition an auto trait?
2060 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2066 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, HashStable,
2067 Ord, RustcEncodable, RustcDecodable, Debug)]
2073 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, HashStable,
2074 RustcEncodable, RustcDecodable, Hash, Debug)]
2080 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2081 pub enum Constness {
2086 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2087 pub enum Defaultness {
2088 Default { has_value: bool },
2093 pub fn has_value(&self) -> bool {
2095 Defaultness::Default { has_value, .. } => has_value,
2096 Defaultness::Final => true,
2100 pub fn is_final(&self) -> bool {
2101 *self == Defaultness::Final
2104 pub fn is_default(&self) -> bool {
2106 Defaultness::Default { .. } => true,
2112 impl fmt::Display for Unsafety {
2113 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2114 f.write_str(match self {
2115 Unsafety::Normal => "normal",
2116 Unsafety::Unsafe => "unsafe",
2121 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2122 pub enum ImplPolarity {
2123 /// `impl Trait for Type`
2125 /// `impl !Trait for Type`
2129 impl fmt::Debug for ImplPolarity {
2130 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2131 f.write_str(match self {
2132 ImplPolarity::Positive => "positive",
2133 ImplPolarity::Negative => "negative",
2139 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2140 pub enum FunctionRetTy {
2141 /// Return type is not specified.
2143 /// Functions default to `()` and
2144 /// closures default to inference. Span points to where return
2145 /// type would be inserted.
2146 DefaultReturn(Span),
2147 /// Everything else.
2151 impl fmt::Display for FunctionRetTy {
2152 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2154 Return(ref ty) => print::to_string(print::NO_ANN, |s| s.print_type(ty)).fmt(f),
2155 DefaultReturn(_) => "()".fmt(f),
2160 impl FunctionRetTy {
2161 pub fn span(&self) -> Span {
2163 DefaultReturn(span) => span,
2164 Return(ref ty) => ty.span,
2169 #[derive(RustcEncodable, RustcDecodable, Debug)]
2171 /// A span from the first token past `{` to the last token until `}`.
2172 /// For `mod foo;`, the inner span ranges from the first token
2173 /// to the last token in the external file.
2175 pub item_ids: HirVec<ItemId>,
2178 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2179 pub struct ForeignMod {
2181 pub items: HirVec<ForeignItem>,
2184 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2185 pub struct GlobalAsm {
2187 #[stable_hasher(ignore)] // This is used for error reporting
2188 pub ctxt: SyntaxContext,
2191 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2192 pub struct EnumDef {
2193 pub variants: HirVec<Variant>,
2196 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2197 pub struct Variant {
2198 /// Name of the variant.
2199 #[stable_hasher(project(name))]
2201 /// Attributes of the variant.
2202 pub attrs: HirVec<Attribute>,
2203 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2205 /// Fields and constructor id of the variant.
2206 pub data: VariantData,
2207 /// Explicit discriminant (e.g., `Foo = 1`).
2208 pub disr_expr: Option<AnonConst>,
2213 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2215 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2216 /// Also produced for each element of a list `use`, e.g.
2217 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2220 /// Glob import, e.g., `use foo::*`.
2223 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2224 /// an additional `use foo::{}` for performing checks such as
2225 /// unstable feature gating. May be removed in the future.
2229 /// References to traits in impls.
2231 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2232 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2233 /// trait being referred to but just a unique `HirId` that serves as a key
2234 /// within the resolution map.
2235 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2236 pub struct TraitRef {
2238 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2239 #[stable_hasher(ignore)]
2240 pub hir_ref_id: HirId,
2244 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2245 pub fn trait_def_id(&self) -> DefId {
2246 match self.path.res {
2247 Res::Def(DefKind::Trait, did) => did,
2248 Res::Def(DefKind::TraitAlias, did) => did,
2252 _ => unreachable!(),
2257 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2258 pub struct PolyTraitRef {
2259 /// The `'a` in `<'a> Foo<&'a T>`.
2260 pub bound_generic_params: HirVec<GenericParam>,
2262 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2263 pub trait_ref: TraitRef,
2268 pub type Visibility = Spanned<VisibilityKind>;
2270 #[derive(RustcEncodable, RustcDecodable, Debug)]
2271 pub enum VisibilityKind {
2274 Restricted { path: P<Path>, hir_id: HirId },
2278 impl VisibilityKind {
2279 pub fn is_pub(&self) -> bool {
2281 VisibilityKind::Public => true,
2286 pub fn is_pub_restricted(&self) -> bool {
2288 VisibilityKind::Public |
2289 VisibilityKind::Inherited => false,
2290 VisibilityKind::Crate(..) |
2291 VisibilityKind::Restricted { .. } => true,
2295 pub fn descr(&self) -> &'static str {
2297 VisibilityKind::Public => "public",
2298 VisibilityKind::Inherited => "private",
2299 VisibilityKind::Crate(..) => "crate-visible",
2300 VisibilityKind::Restricted { .. } => "restricted",
2305 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2306 pub struct StructField {
2308 #[stable_hasher(project(name))]
2310 pub vis: Visibility,
2313 pub attrs: HirVec<Attribute>,
2317 // Still necessary in couple of places
2318 pub fn is_positional(&self) -> bool {
2319 let first = self.ident.as_str().as_bytes()[0];
2320 first >= b'0' && first <= b'9'
2324 /// Fields and constructor IDs of enum variants and structs.
2325 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2326 pub enum VariantData {
2327 /// A struct variant.
2329 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2330 Struct(HirVec<StructField>, /* recovered */ bool),
2331 /// A tuple variant.
2333 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2334 Tuple(HirVec<StructField>, HirId),
2337 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2342 /// Return the fields of this variant.
2343 pub fn fields(&self) -> &[StructField] {
2345 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2350 /// Return the `HirId` of this variant's constructor, if it has one.
2351 pub fn ctor_hir_id(&self) -> Option<HirId> {
2353 VariantData::Struct(_, _) => None,
2354 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2359 // The bodies for items are stored "out of line", in a separate
2360 // hashmap in the `Crate`. Here we just record the node-id of the item
2361 // so it can fetched later.
2362 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2369 /// The name might be a dummy name in case of anonymous items
2370 #[derive(RustcEncodable, RustcDecodable, Debug)]
2374 pub attrs: HirVec<Attribute>,
2376 pub vis: Visibility,
2380 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2381 pub struct FnHeader {
2382 pub unsafety: Unsafety,
2383 pub constness: Constness,
2384 pub asyncness: IsAsync,
2389 pub fn is_const(&self) -> bool {
2390 match &self.constness {
2391 Constness::Const => true,
2397 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2399 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2401 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2402 ExternCrate(Option<Name>),
2404 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2408 /// `use foo::bar::baz;` (with `as baz` implicitly on the right)
2409 Use(P<Path>, UseKind),
2412 Static(P<Ty>, Mutability, BodyId),
2414 Const(P<Ty>, BodyId),
2415 /// A function declaration
2416 Fn(P<FnDecl>, FnHeader, Generics, BodyId),
2419 /// An external module
2420 ForeignMod(ForeignMod),
2421 /// Module-level inline assembly (from global_asm!)
2422 GlobalAsm(P<GlobalAsm>),
2423 /// A type alias, e.g., `type Foo = Bar<u8>`
2424 TyAlias(P<Ty>, Generics),
2425 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`
2427 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`
2428 Enum(EnumDef, Generics),
2429 /// A struct definition, e.g., `struct Foo<A> {x: A}`
2430 Struct(VariantData, Generics),
2431 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`
2432 Union(VariantData, Generics),
2433 /// A trait definition
2434 Trait(IsAuto, Unsafety, Generics, GenericBounds, HirVec<TraitItemRef>),
2436 TraitAlias(Generics, GenericBounds),
2438 /// An implementation, eg `impl<A> Trait for Foo { .. }`
2443 Option<TraitRef>, // (optional) trait this impl implements
2445 HirVec<ImplItemRef>),
2449 pub fn descriptive_variant(&self) -> &str {
2451 ItemKind::ExternCrate(..) => "extern crate",
2452 ItemKind::Use(..) => "use",
2453 ItemKind::Static(..) => "static item",
2454 ItemKind::Const(..) => "constant item",
2455 ItemKind::Fn(..) => "function",
2456 ItemKind::Mod(..) => "module",
2457 ItemKind::ForeignMod(..) => "foreign module",
2458 ItemKind::GlobalAsm(..) => "global asm",
2459 ItemKind::TyAlias(..) => "type alias",
2460 ItemKind::OpaqueTy(..) => "opaque type",
2461 ItemKind::Enum(..) => "enum",
2462 ItemKind::Struct(..) => "struct",
2463 ItemKind::Union(..) => "union",
2464 ItemKind::Trait(..) => "trait",
2465 ItemKind::TraitAlias(..) => "trait alias",
2466 ItemKind::Impl(..) => "impl",
2470 pub fn adt_kind(&self) -> Option<AdtKind> {
2472 ItemKind::Struct(..) => Some(AdtKind::Struct),
2473 ItemKind::Union(..) => Some(AdtKind::Union),
2474 ItemKind::Enum(..) => Some(AdtKind::Enum),
2479 pub fn generics(&self) -> Option<&Generics> {
2481 ItemKind::Fn(_, _, ref generics, _) |
2482 ItemKind::TyAlias(_, ref generics) |
2483 ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. }) |
2484 ItemKind::Enum(_, ref generics) |
2485 ItemKind::Struct(_, ref generics) |
2486 ItemKind::Union(_, ref generics) |
2487 ItemKind::Trait(_, _, ref generics, _, _) |
2488 ItemKind::Impl(_, _, _, ref generics, _, _, _)=> generics,
2494 /// A reference from an trait to one of its associated items. This
2495 /// contains the item's id, naturally, but also the item's name and
2496 /// some other high-level details (like whether it is an associated
2497 /// type or method, and whether it is public). This allows other
2498 /// passes to find the impl they want without loading the ID (which
2499 /// means fewer edges in the incremental compilation graph).
2500 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2501 pub struct TraitItemRef {
2502 pub id: TraitItemId,
2503 #[stable_hasher(project(name))]
2505 pub kind: AssocItemKind,
2507 pub defaultness: Defaultness,
2510 /// A reference from an impl to one of its associated items. This
2511 /// contains the item's ID, naturally, but also the item's name and
2512 /// some other high-level details (like whether it is an associated
2513 /// type or method, and whether it is public). This allows other
2514 /// passes to find the impl they want without loading the ID (which
2515 /// means fewer edges in the incremental compilation graph).
2516 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2517 pub struct ImplItemRef {
2519 #[stable_hasher(project(name))]
2521 pub kind: AssocItemKind,
2523 pub vis: Visibility,
2524 pub defaultness: Defaultness,
2527 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2528 pub enum AssocItemKind {
2530 Method { has_self: bool },
2535 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2536 pub struct ForeignItem {
2537 #[stable_hasher(project(name))]
2539 pub attrs: HirVec<Attribute>,
2540 pub node: ForeignItemKind,
2543 pub vis: Visibility,
2546 /// An item within an `extern` block.
2547 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2548 pub enum ForeignItemKind {
2549 /// A foreign function.
2550 Fn(P<FnDecl>, HirVec<Ident>, Generics),
2551 /// A foreign static item (`static ext: u8`).
2552 Static(P<Ty>, Mutability),
2557 impl ForeignItemKind {
2558 pub fn descriptive_variant(&self) -> &str {
2560 ForeignItemKind::Fn(..) => "foreign function",
2561 ForeignItemKind::Static(..) => "foreign static item",
2562 ForeignItemKind::Type => "foreign type",
2567 /// A variable captured by a closure.
2568 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable, HashStable)]
2570 // First span where it is accessed (there can be multiple).
2574 pub type CaptureModeMap = NodeMap<CaptureClause>;
2576 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2577 // has length > 0 if the trait is found through an chain of imports, starting with the
2578 // import/use statement in the scope where the trait is used.
2579 #[derive(Clone, Debug)]
2580 pub struct TraitCandidate {
2582 pub import_ids: SmallVec<[NodeId; 1]>,
2585 // Trait method resolution
2586 pub type TraitMap = NodeMap<Vec<TraitCandidate>>;
2588 // Map from the NodeId of a glob import to a list of items which are actually
2590 pub type GlobMap = NodeMap<FxHashSet<Name>>;
2592 pub fn provide(providers: &mut Providers<'_>) {
2593 check_attr::provide(providers);
2594 map::provide(providers);
2595 upvars::provide(providers);
2598 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
2599 pub struct CodegenFnAttrs {
2600 pub flags: CodegenFnAttrFlags,
2601 /// Parsed representation of the `#[inline]` attribute
2602 pub inline: InlineAttr,
2603 /// Parsed representation of the `#[optimize]` attribute
2604 pub optimize: OptimizeAttr,
2605 /// The `#[export_name = "..."]` attribute, indicating a custom symbol a
2606 /// function should be exported under
2607 pub export_name: Option<Symbol>,
2608 /// The `#[link_name = "..."]` attribute, indicating a custom symbol an
2609 /// imported function should be imported as. Note that `export_name`
2610 /// probably isn't set when this is set, this is for foreign items while
2611 /// `#[export_name]` is for Rust-defined functions.
2612 pub link_name: Option<Symbol>,
2613 /// The `#[target_feature(enable = "...")]` attribute and the enabled
2614 /// features (only enabled features are supported right now).
2615 pub target_features: Vec<Symbol>,
2616 /// The `#[linkage = "..."]` attribute and the value we found.
2617 pub linkage: Option<Linkage>,
2618 /// The `#[link_section = "..."]` attribute, or what executable section this
2619 /// should be placed in.
2620 pub link_section: Option<Symbol>,
2624 #[derive(RustcEncodable, RustcDecodable, HashStable)]
2625 pub struct CodegenFnAttrFlags: u32 {
2626 /// `#[cold]`: a hint to LLVM that this function, when called, is never on
2628 const COLD = 1 << 0;
2629 /// `#[rustc_allocator]`: a hint to LLVM that the pointer returned from this
2630 /// function is never null.
2631 const ALLOCATOR = 1 << 1;
2632 /// `#[unwind]`: an indicator that this function may unwind despite what
2633 /// its ABI signature may otherwise imply.
2634 const UNWIND = 1 << 2;
2635 /// `#[rust_allocator_nounwind]`, an indicator that an imported FFI
2636 /// function will never unwind. Probably obsolete by recent changes with
2637 /// #[unwind], but hasn't been removed/migrated yet
2638 const RUSTC_ALLOCATOR_NOUNWIND = 1 << 3;
2639 /// `#[naked]`: an indicator to LLVM that no function prologue/epilogue
2640 /// should be generated.
2641 const NAKED = 1 << 4;
2642 /// `#[no_mangle]`: an indicator that the function's name should be the same
2644 const NO_MANGLE = 1 << 5;
2645 /// `#[rustc_std_internal_symbol]`: an indicator that this symbol is a
2646 /// "weird symbol" for the standard library in that it has slightly
2647 /// different linkage, visibility, and reachability rules.
2648 const RUSTC_STD_INTERNAL_SYMBOL = 1 << 6;
2649 /// `#[no_debug]`: an indicator that no debugging information should be
2650 /// generated for this function by LLVM.
2651 const NO_DEBUG = 1 << 7;
2652 /// `#[thread_local]`: indicates a static is actually a thread local
2654 const THREAD_LOCAL = 1 << 8;
2655 /// `#[used]`: indicates that LLVM can't eliminate this function (but the
2657 const USED = 1 << 9;
2658 /// #[ffi_returns_twice], indicates that an extern function can return
2660 const FFI_RETURNS_TWICE = 1 << 10;
2664 impl CodegenFnAttrs {
2665 pub fn new() -> CodegenFnAttrs {
2667 flags: CodegenFnAttrFlags::empty(),
2668 inline: InlineAttr::None,
2669 optimize: OptimizeAttr::None,
2672 target_features: vec![],
2678 /// Returns `true` if `#[inline]` or `#[inline(always)]` is present.
2679 pub fn requests_inline(&self) -> bool {
2681 InlineAttr::Hint | InlineAttr::Always => true,
2682 InlineAttr::None | InlineAttr::Never => false,
2686 /// Returns `true` if it looks like this symbol needs to be exported, for example:
2688 /// * `#[no_mangle]` is present
2689 /// * `#[export_name(...)]` is present
2690 /// * `#[linkage]` is present
2691 pub fn contains_extern_indicator(&self) -> bool {
2692 self.flags.contains(CodegenFnAttrFlags::NO_MANGLE) ||
2693 self.export_name.is_some() ||
2694 match self.linkage {
2695 // These are private, so make sure we don't try to consider
2698 Some(Linkage::Internal) |
2699 Some(Linkage::Private) => false,
2705 #[derive(Copy, Clone, Debug)]
2706 pub enum Node<'hir> {
2709 ForeignItem(&'hir ForeignItem),
2710 TraitItem(&'hir TraitItem),
2711 ImplItem(&'hir ImplItem),
2712 Variant(&'hir Variant),
2713 Field(&'hir StructField),
2714 AnonConst(&'hir AnonConst),
2717 PathSegment(&'hir PathSegment),
2719 TraitRef(&'hir TraitRef),
2725 MacroDef(&'hir MacroDef),
2727 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
2728 /// with synthesized constructors.
2729 Ctor(&'hir VariantData),
2731 Lifetime(&'hir Lifetime),
2732 GenericParam(&'hir GenericParam),
2733 Visibility(&'hir Visibility),