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 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 serialize::UseSpecializedEncodable for HirId {
96 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
107 impl 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_empty_ctxt(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_empty_ctxt(kw::UnderscoreLifetime),
241 LifetimeName::Static => Ident::with_empty_ctxt(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>,
731 // N.B., we use a BTreeMap here so that `visit_all_items` iterates
732 // over the ids in increasing order. In principle it should not
733 // matter what order we visit things in, but in *practice* it
734 // does, because it can affect the order in which errors are
735 // detected, which in turn can make compile-fail tests yield
736 // slightly different results.
737 pub items: BTreeMap<HirId, Item>,
739 pub trait_items: BTreeMap<TraitItemId, TraitItem>,
740 pub impl_items: BTreeMap<ImplItemId, ImplItem>,
741 pub bodies: BTreeMap<BodyId, Body>,
742 pub trait_impls: BTreeMap<DefId, Vec<HirId>>,
744 /// A list of the body ids written out in the order in which they
745 /// appear in the crate. If you're going to process all the bodies
746 /// in the crate, you should iterate over this list rather than the keys
748 pub body_ids: Vec<BodyId>,
750 /// A list of modules written out in the order in which they
751 /// appear in the crate. This includes the main crate module.
752 pub modules: BTreeMap<NodeId, ModuleItems>,
756 pub fn item(&self, id: HirId) -> &Item {
760 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem {
761 &self.trait_items[&id]
764 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem {
765 &self.impl_items[&id]
768 /// Visits all items in the crate in some deterministic (but
769 /// unspecified) order. If you just need to process every item,
770 /// but don't care about nesting, this method is the best choice.
772 /// If you do care about nesting -- usually because your algorithm
773 /// follows lexical scoping rules -- then you want a different
774 /// approach. You should override `visit_nested_item` in your
775 /// visitor and then call `intravisit::walk_crate` instead.
776 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
777 where V: itemlikevisit::ItemLikeVisitor<'hir>
779 for (_, item) in &self.items {
780 visitor.visit_item(item);
783 for (_, trait_item) in &self.trait_items {
784 visitor.visit_trait_item(trait_item);
787 for (_, impl_item) in &self.impl_items {
788 visitor.visit_impl_item(impl_item);
792 /// A parallel version of `visit_all_item_likes`.
793 pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
794 where V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send
797 par_for_each_in(&self.items, |(_, item)| {
798 visitor.visit_item(item);
801 par_for_each_in(&self.trait_items, |(_, trait_item)| {
802 visitor.visit_trait_item(trait_item);
805 par_for_each_in(&self.impl_items, |(_, impl_item)| {
806 visitor.visit_impl_item(impl_item);
811 pub fn body(&self, id: BodyId) -> &Body {
816 /// A macro definition, in this crate or imported from another.
818 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
819 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
820 pub struct MacroDef {
823 pub attrs: HirVec<Attribute>,
826 pub body: TokenStream,
830 /// A block of statements `{ .. }`, which may have a label (in this case the
831 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
832 /// the `rules` being anything but `DefaultBlock`.
833 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
835 /// Statements in a block.
836 pub stmts: HirVec<Stmt>,
837 /// An expression at the end of the block
838 /// without a semicolon, if any.
839 pub expr: Option<P<Expr>>,
840 #[stable_hasher(ignore)]
842 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
843 pub rules: BlockCheckMode,
845 /// If true, then there may exist `break 'a` values that aim to
846 /// break out of this block early.
847 /// Used by `'label: {}` blocks and by `catch` statements.
848 pub targeted_by_break: bool,
851 #[derive(RustcEncodable, RustcDecodable, HashStable)]
853 #[stable_hasher(ignore)]
859 impl fmt::Debug for Pat {
860 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
861 write!(f, "pat({}: {})", self.hir_id,
862 print::to_string(print::NO_ANN, |s| s.print_pat(self)))
867 // FIXME(#19596) this is a workaround, but there should be a better way
868 fn walk_<G>(&self, it: &mut G) -> bool
869 where G: FnMut(&Pat) -> bool
876 PatKind::Binding(.., Some(ref p)) => p.walk_(it),
877 PatKind::Struct(_, ref fields, _) => {
878 fields.iter().all(|field| field.node.pat.walk_(it))
880 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
881 s.iter().all(|p| p.walk_(it))
883 PatKind::Box(ref s) | PatKind::Ref(ref s, _) => {
886 PatKind::Slice(ref before, ref slice, ref after) => {
890 .all(|p| p.walk_(it))
895 PatKind::Binding(..) |
896 PatKind::Path(_) => {
902 pub fn walk<F>(&self, mut it: F) -> bool
903 where F: FnMut(&Pat) -> bool
909 /// A single field in a struct pattern.
911 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
912 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
913 /// except `is_shorthand` is true.
914 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
915 pub struct FieldPat {
916 #[stable_hasher(ignore)]
918 /// The identifier for the field.
919 #[stable_hasher(project(name))]
921 /// The pattern the field is destructured to.
923 pub is_shorthand: bool,
926 /// Explicit binding annotations given in the HIR for a binding. Note
927 /// that this is not the final binding *mode* that we infer after type
929 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
930 pub enum BindingAnnotation {
931 /// No binding annotation given: this means that the final binding mode
932 /// will depend on whether we have skipped through a `&` reference
933 /// when matching. For example, the `x` in `Some(x)` will have binding
934 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
935 /// ultimately be inferred to be by-reference.
937 /// Note that implicit reference skipping is not implemented yet (#42640).
940 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
943 /// Annotated as `ref`, like `ref x`
946 /// Annotated as `ref mut x`.
950 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
956 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
958 /// Represents a wildcard pattern (i.e., `_`).
961 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
962 /// The `HirId` is the canonical ID for the variable being bound,
963 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
964 /// which is the pattern ID of the first `x`.
965 Binding(BindingAnnotation, HirId, Ident, Option<P<Pat>>),
967 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
968 /// The `bool` is `true` in the presence of a `..`.
969 Struct(QPath, HirVec<Spanned<FieldPat>>, bool),
971 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
972 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
973 /// `0 <= position <= subpats.len()`
974 TupleStruct(QPath, HirVec<P<Pat>>, Option<usize>),
976 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
979 /// A tuple pattern (e.g., `(a, b)`).
980 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
981 /// `0 <= position <= subpats.len()`
982 Tuple(HirVec<P<Pat>>, Option<usize>),
987 /// A reference pattern (e.g., `&mut (a, b)`).
988 Ref(P<Pat>, Mutability),
993 /// A range pattern (e.g., `1..=2` or `1..2`).
994 Range(P<Expr>, P<Expr>, RangeEnd),
996 /// `[a, b, ..i, y, z]` is represented as:
997 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`.
998 Slice(HirVec<P<Pat>>, Option<P<Pat>>, HirVec<P<Pat>>),
1001 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, HashStable,
1002 RustcEncodable, RustcDecodable, Hash, Debug)]
1003 pub enum Mutability {
1009 /// Returns `MutMutable` only if both arguments are mutable.
1010 pub fn and(self, other: Self) -> Self {
1012 MutMutable => other,
1013 MutImmutable => MutImmutable,
1018 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Hash, HashStable)]
1019 pub enum BinOpKind {
1020 /// The `+` operator (addition).
1022 /// The `-` operator (subtraction).
1024 /// The `*` operator (multiplication).
1026 /// The `/` operator (division).
1028 /// The `%` operator (modulus).
1030 /// The `&&` operator (logical and).
1032 /// The `||` operator (logical or).
1034 /// The `^` operator (bitwise xor).
1036 /// The `&` operator (bitwise and).
1038 /// The `|` operator (bitwise or).
1040 /// The `<<` operator (shift left).
1042 /// The `>>` operator (shift right).
1044 /// The `==` operator (equality).
1046 /// The `<` operator (less than).
1048 /// The `<=` operator (less than or equal to).
1050 /// The `!=` operator (not equal to).
1052 /// The `>=` operator (greater than or equal to).
1054 /// The `>` operator (greater than).
1059 pub fn as_str(self) -> &'static str {
1061 BinOpKind::Add => "+",
1062 BinOpKind::Sub => "-",
1063 BinOpKind::Mul => "*",
1064 BinOpKind::Div => "/",
1065 BinOpKind::Rem => "%",
1066 BinOpKind::And => "&&",
1067 BinOpKind::Or => "||",
1068 BinOpKind::BitXor => "^",
1069 BinOpKind::BitAnd => "&",
1070 BinOpKind::BitOr => "|",
1071 BinOpKind::Shl => "<<",
1072 BinOpKind::Shr => ">>",
1073 BinOpKind::Eq => "==",
1074 BinOpKind::Lt => "<",
1075 BinOpKind::Le => "<=",
1076 BinOpKind::Ne => "!=",
1077 BinOpKind::Ge => ">=",
1078 BinOpKind::Gt => ">",
1082 pub fn is_lazy(self) -> bool {
1084 BinOpKind::And | BinOpKind::Or => true,
1089 pub fn is_shift(self) -> bool {
1091 BinOpKind::Shl | BinOpKind::Shr => true,
1096 pub fn is_comparison(self) -> bool {
1103 BinOpKind::Ge => true,
1115 BinOpKind::Shr => false,
1119 /// Returns `true` if the binary operator takes its arguments by value.
1120 pub fn is_by_value(self) -> bool {
1121 !self.is_comparison()
1125 impl Into<ast::BinOpKind> for BinOpKind {
1126 fn into(self) -> ast::BinOpKind {
1128 BinOpKind::Add => ast::BinOpKind::Add,
1129 BinOpKind::Sub => ast::BinOpKind::Sub,
1130 BinOpKind::Mul => ast::BinOpKind::Mul,
1131 BinOpKind::Div => ast::BinOpKind::Div,
1132 BinOpKind::Rem => ast::BinOpKind::Rem,
1133 BinOpKind::And => ast::BinOpKind::And,
1134 BinOpKind::Or => ast::BinOpKind::Or,
1135 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1136 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1137 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1138 BinOpKind::Shl => ast::BinOpKind::Shl,
1139 BinOpKind::Shr => ast::BinOpKind::Shr,
1140 BinOpKind::Eq => ast::BinOpKind::Eq,
1141 BinOpKind::Lt => ast::BinOpKind::Lt,
1142 BinOpKind::Le => ast::BinOpKind::Le,
1143 BinOpKind::Ne => ast::BinOpKind::Ne,
1144 BinOpKind::Ge => ast::BinOpKind::Ge,
1145 BinOpKind::Gt => ast::BinOpKind::Gt,
1150 pub type BinOp = Spanned<BinOpKind>;
1152 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Hash, HashStable)]
1154 /// The `*` operator (deferencing).
1156 /// The `!` operator (logical negation).
1158 /// The `-` operator (negation).
1163 pub fn as_str(self) -> &'static str {
1171 /// Returns `true` if the unary operator takes its argument by value.
1172 pub fn is_by_value(self) -> bool {
1174 UnNeg | UnNot => true,
1181 #[derive(RustcEncodable, RustcDecodable)]
1188 impl fmt::Debug for Stmt {
1189 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1190 write!(f, "stmt({}: {})", self.hir_id,
1191 print::to_string(print::NO_ANN, |s| s.print_stmt(self)))
1195 /// The contents of a statement.
1196 #[derive(RustcEncodable, RustcDecodable, HashStable)]
1198 /// A local (`let`) binding.
1201 /// An item binding.
1204 /// An expression without a trailing semi-colon (must have unit type).
1207 /// An expression with a trailing semi-colon (may have any type).
1212 pub fn attrs(&self) -> &[Attribute] {
1214 StmtKind::Local(ref l) => &l.attrs,
1215 StmtKind::Item(_) => &[],
1216 StmtKind::Expr(ref e) |
1217 StmtKind::Semi(ref e) => &e.attrs,
1222 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1223 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1226 /// Type annotation, if any (otherwise the type will be inferred).
1227 pub ty: Option<P<Ty>>,
1228 /// Initializer expression to set the value, if any.
1229 pub init: Option<P<Expr>>,
1232 pub attrs: ThinVec<Attribute>,
1233 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1234 /// desugaring. Otherwise will be `Normal`.
1235 pub source: LocalSource,
1238 /// Represents a single arm of a `match` expression, e.g.
1239 /// `<pats> (if <guard>) => <body>`.
1240 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1242 #[stable_hasher(ignore)]
1245 pub attrs: HirVec<Attribute>,
1246 /// Multiple patterns can be combined with `|`
1247 pub pats: HirVec<P<Pat>>,
1248 /// Optional guard clause.
1249 pub guard: Option<Guard>,
1250 /// The expression the arm evaluates to if this arm matches.
1254 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1259 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1261 #[stable_hasher(ignore)]
1266 pub is_shorthand: bool,
1269 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1270 pub enum BlockCheckMode {
1272 UnsafeBlock(UnsafeSource),
1273 PushUnsafeBlock(UnsafeSource),
1274 PopUnsafeBlock(UnsafeSource),
1277 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1278 pub enum UnsafeSource {
1283 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1288 /// The body of a function, closure, or constant value. In the case of
1289 /// a function, the body contains not only the function body itself
1290 /// (which is an expression), but also the argument patterns, since
1291 /// those are something that the caller doesn't really care about.
1296 /// fn foo((x, y): (u32, u32)) -> u32 {
1301 /// Here, the `Body` associated with `foo()` would contain:
1303 /// - an `arguments` array containing the `(x, y)` pattern
1304 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1305 /// - `generator_kind` would be `None`
1307 /// All bodies have an **owner**, which can be accessed via the HIR
1308 /// map using `body_owner_def_id()`.
1309 #[derive(RustcEncodable, RustcDecodable, Debug)]
1311 pub arguments: HirVec<Arg>,
1313 pub generator_kind: Option<GeneratorKind>,
1317 pub fn id(&self) -> BodyId {
1319 hir_id: self.value.hir_id,
1324 /// The type of source expression that caused this generator to be created.
1325 // Not `IsAsync` because we want to eventually add support for `AsyncGen`
1326 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, HashStable,
1327 RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1328 pub enum GeneratorKind {
1329 /// An `async` block or function.
1331 /// A generator literal created via a `yield` inside a closure.
1335 impl fmt::Display for GeneratorKind {
1336 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1337 f.write_str(match self {
1338 GeneratorKind::Async => "`async` object",
1339 GeneratorKind::Gen => "generator",
1344 #[derive(Copy, Clone, Debug)]
1345 pub enum BodyOwnerKind {
1346 /// Functions and methods.
1352 /// Constants and associated constants.
1355 /// Initializer of a `static` item.
1359 impl BodyOwnerKind {
1360 pub fn is_fn_or_closure(self) -> bool {
1362 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1363 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1369 pub type Lit = Spanned<LitKind>;
1371 /// A constant (expression) that's not an item or associated item,
1372 /// but needs its own `DefId` for type-checking, const-eval, etc.
1373 /// These are usually found nested inside types (e.g., array lengths)
1374 /// or expressions (e.g., repeat counts), and also used to define
1375 /// explicit discriminant values for enum variants.
1376 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1377 pub struct AnonConst {
1383 #[derive(RustcEncodable, RustcDecodable)]
1387 pub attrs: ThinVec<Attribute>,
1391 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1392 #[cfg(target_arch = "x86_64")]
1393 static_assert_size!(Expr, 72);
1396 pub fn precedence(&self) -> ExprPrecedence {
1398 ExprKind::Box(_) => ExprPrecedence::Box,
1399 ExprKind::Array(_) => ExprPrecedence::Array,
1400 ExprKind::Call(..) => ExprPrecedence::Call,
1401 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1402 ExprKind::Tup(_) => ExprPrecedence::Tup,
1403 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1404 ExprKind::Unary(..) => ExprPrecedence::Unary,
1405 ExprKind::Lit(_) => ExprPrecedence::Lit,
1406 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1407 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1408 ExprKind::While(..) => ExprPrecedence::While,
1409 ExprKind::Loop(..) => ExprPrecedence::Loop,
1410 ExprKind::Match(..) => ExprPrecedence::Match,
1411 ExprKind::Closure(..) => ExprPrecedence::Closure,
1412 ExprKind::Block(..) => ExprPrecedence::Block,
1413 ExprKind::Assign(..) => ExprPrecedence::Assign,
1414 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1415 ExprKind::Field(..) => ExprPrecedence::Field,
1416 ExprKind::Index(..) => ExprPrecedence::Index,
1417 ExprKind::Path(..) => ExprPrecedence::Path,
1418 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1419 ExprKind::Break(..) => ExprPrecedence::Break,
1420 ExprKind::Continue(..) => ExprPrecedence::Continue,
1421 ExprKind::Ret(..) => ExprPrecedence::Ret,
1422 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1423 ExprKind::Struct(..) => ExprPrecedence::Struct,
1424 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1425 ExprKind::Yield(..) => ExprPrecedence::Yield,
1426 ExprKind::Err => ExprPrecedence::Err,
1430 pub fn is_place_expr(&self) -> bool {
1432 ExprKind::Path(QPath::Resolved(_, ref path)) => {
1435 | Res::Def(DefKind::Static, _)
1441 ExprKind::Type(ref e, _) => {
1445 ExprKind::Unary(UnDeref, _) |
1446 ExprKind::Field(..) |
1447 ExprKind::Index(..) => {
1451 // Partially qualified paths in expressions can only legally
1452 // refer to associated items which are always rvalues.
1453 ExprKind::Path(QPath::TypeRelative(..)) |
1455 ExprKind::Call(..) |
1456 ExprKind::MethodCall(..) |
1457 ExprKind::Struct(..) |
1459 ExprKind::Match(..) |
1460 ExprKind::Closure(..) |
1461 ExprKind::Block(..) |
1462 ExprKind::Repeat(..) |
1463 ExprKind::Array(..) |
1464 ExprKind::Break(..) |
1465 ExprKind::Continue(..) |
1467 ExprKind::While(..) |
1468 ExprKind::Loop(..) |
1469 ExprKind::Assign(..) |
1470 ExprKind::InlineAsm(..) |
1471 ExprKind::AssignOp(..) |
1473 ExprKind::Unary(..) |
1475 ExprKind::AddrOf(..) |
1476 ExprKind::Binary(..) |
1477 ExprKind::Yield(..) |
1478 ExprKind::Cast(..) |
1479 ExprKind::DropTemps(..) |
1487 impl fmt::Debug for Expr {
1488 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1489 write!(f, "expr({}: {})", self.hir_id,
1490 print::to_string(print::NO_ANN, |s| s.print_expr(self)))
1494 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1496 /// A `box x` expression.
1498 /// An array (e.g., `[a, b, c, d]`).
1499 Array(HirVec<Expr>),
1500 /// A function call.
1502 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1503 /// and the second field is the list of arguments.
1504 /// This also represents calling the constructor of
1505 /// tuple-like ADTs such as tuple structs and enum variants.
1506 Call(P<Expr>, HirVec<Expr>),
1507 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1509 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1510 /// (within the angle brackets).
1511 /// The first element of the vector of `Expr`s is the expression that evaluates
1512 /// to the object on which the method is being called on (the receiver),
1513 /// and the remaining elements are the rest of the arguments.
1514 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1515 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1516 MethodCall(P<PathSegment>, Span, HirVec<Expr>),
1517 /// A tuple (e.g., `(a, b, c ,d)`).
1519 /// A binary operation (e.g., `a + b`, `a * b`).
1520 Binary(BinOp, P<Expr>, P<Expr>),
1521 /// A unary operation (e.g., `!x`, `*x`).
1522 Unary(UnOp, P<Expr>),
1523 /// A literal (e.g., `1`, `"foo"`).
1525 /// A cast (e.g., `foo as f64`).
1526 Cast(P<Expr>, P<Ty>),
1527 /// A type reference (e.g., `Foo`).
1528 Type(P<Expr>, P<Ty>),
1529 /// Wraps the expression in a terminating scope.
1530 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1532 /// This construct only exists to tweak the drop order in HIR lowering.
1533 /// An example of that is the desugaring of `for` loops.
1535 /// A while loop, with an optional label
1537 /// I.e., `'label: while expr { <block> }`.
1538 While(P<Expr>, P<Block>, Option<Label>),
1539 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1541 /// I.e., `'label: loop { <block> }`.
1542 Loop(P<Block>, Option<Label>, LoopSource),
1543 /// A `match` block, with a source that indicates whether or not it is
1544 /// the result of a desugaring, and if so, which kind.
1545 Match(P<Expr>, HirVec<Arm>, MatchSource),
1546 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1548 /// The final span is the span of the argument block `|...|`.
1550 /// This may also be a generator literal or an `async block` as indicated by the
1551 /// `Option<GeneratorMovability>`.
1552 Closure(CaptureClause, P<FnDecl>, BodyId, Span, Option<GeneratorMovability>),
1553 /// A block (e.g., `'label: { ... }`).
1554 Block(P<Block>, Option<Label>),
1556 /// An assignment (e.g., `a = foo()`).
1557 Assign(P<Expr>, P<Expr>),
1558 /// An assignment with an operator.
1561 AssignOp(BinOp, P<Expr>, P<Expr>),
1562 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1563 Field(P<Expr>, Ident),
1564 /// An indexing operation (`foo[2]`).
1565 Index(P<Expr>, P<Expr>),
1567 /// Path to a definition, possibly containing lifetime or type parameters.
1570 /// A referencing operation (i.e., `&a` or `&mut a`).
1571 AddrOf(Mutability, P<Expr>),
1572 /// A `break`, with an optional label to break.
1573 Break(Destination, Option<P<Expr>>),
1574 /// A `continue`, with an optional label.
1575 Continue(Destination),
1576 /// A `return`, with an optional value to be returned.
1577 Ret(Option<P<Expr>>),
1579 /// Inline assembly (from `asm!`), with its outputs and inputs.
1580 InlineAsm(P<InlineAsm>, HirVec<Expr>, HirVec<Expr>),
1582 /// A struct or struct-like variant literal expression.
1584 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1585 /// where `base` is the `Option<Expr>`.
1586 Struct(P<QPath>, HirVec<Field>, Option<P<Expr>>),
1588 /// An array literal constructed from one repeated element.
1590 /// E.g., `[1; 5]`. The first expression is the element
1591 /// to be repeated; the second is the number of times to repeat it.
1592 Repeat(P<Expr>, AnonConst),
1594 /// A suspension point for generators (i.e., `yield <expr>`).
1595 Yield(P<Expr>, YieldSource),
1597 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1601 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1602 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1604 /// Path to a definition, optionally "fully-qualified" with a `Self`
1605 /// type, if the path points to an associated item in a trait.
1607 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1608 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1609 /// even though they both have the same two-segment `Clone::clone` `Path`.
1610 Resolved(Option<P<Ty>>, P<Path>),
1612 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1613 /// Will be resolved by type-checking to an associated item.
1615 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1616 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1617 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1618 TypeRelative(P<Ty>, P<PathSegment>)
1621 /// Hints at the original code for a let statement.
1622 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1623 pub enum LocalSource {
1624 /// A `match _ { .. }`.
1626 /// A desugared `for _ in _ { .. }` loop.
1628 /// When lowering async functions, we create locals within the `async move` so that
1629 /// all arguments are dropped after the future is polled.
1631 /// ```ignore (pseudo-Rust)
1632 /// async fn foo(<pattern> @ x: Type) {
1634 /// let <pattern> = x;
1639 /// A desugared `<expr>.await`.
1643 /// Hints at the original code for a `match _ { .. }`.
1644 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
1645 pub enum MatchSource {
1646 /// A `match _ { .. }`.
1648 /// An `if _ { .. }` (optionally with `else { .. }`).
1650 contains_else_clause: bool,
1652 /// An `if let _ = _ { .. }` (optionally with `else { .. }`).
1654 contains_else_clause: bool,
1656 /// A `while let _ = _ { .. }` (which was desugared to a
1657 /// `loop { match _ { .. } }`).
1659 /// A desugared `for _ in _ { .. }` loop.
1661 /// A desugared `?` operator.
1663 /// A desugared `<expr>.await`.
1667 /// The loop type that yielded an `ExprKind::Loop`.
1668 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1669 pub enum LoopSource {
1670 /// A `loop { .. }` loop.
1672 /// A `while let _ = _ { .. }` loop.
1674 /// A `for _ in _ { .. }` loop.
1678 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1679 pub enum LoopIdError {
1681 UnlabeledCfInWhileCondition,
1685 impl fmt::Display for LoopIdError {
1686 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1687 f.write_str(match self {
1688 LoopIdError::OutsideLoopScope => "not inside loop scope",
1689 LoopIdError::UnlabeledCfInWhileCondition =>
1690 "unlabeled control flow (break or continue) in while condition",
1691 LoopIdError::UnresolvedLabel => "label not found",
1696 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1697 pub struct Destination {
1698 // This is `Some(_)` iff there is an explicit user-specified `label
1699 pub label: Option<Label>,
1701 // These errors are caught and then reported during the diagnostics pass in
1702 // librustc_passes/loops.rs
1703 pub target_id: Result<HirId, LoopIdError>,
1706 /// Whether a generator contains self-references, causing it to be `!Unpin`.
1707 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, HashStable,
1708 RustcEncodable, RustcDecodable, Hash, Debug)]
1709 pub enum GeneratorMovability {
1710 /// May contain self-references, `!Unpin`.
1712 /// Must not contain self-references, `Unpin`.
1716 /// The yield kind that caused an `ExprKind::Yield`.
1717 #[derive(Copy, Clone, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable, HashStable)]
1718 pub enum YieldSource {
1719 /// An `<expr>.await`.
1721 /// A plain `yield`.
1725 impl fmt::Display for YieldSource {
1726 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1727 f.write_str(match self {
1728 YieldSource::Await => "`await`",
1729 YieldSource::Yield => "`yield`",
1734 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1735 pub enum CaptureClause {
1740 // N.B., if you change this, you'll probably want to change the corresponding
1741 // type structure in middle/ty.rs as well.
1742 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1745 pub mutbl: Mutability,
1748 /// Represents a method's signature in a trait declaration or implementation.
1749 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1750 pub struct MethodSig {
1751 pub header: FnHeader,
1752 pub decl: P<FnDecl>,
1755 // The bodies for items are stored "out of line", in a separate
1756 // hashmap in the `Crate`. Here we just record the node-id of the item
1757 // so it can fetched later.
1758 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1759 pub struct TraitItemId {
1763 /// Represents an item declaration within a trait declaration,
1764 /// possibly including a default implementation. A trait item is
1765 /// either required (meaning it doesn't have an implementation, just a
1766 /// signature) or provided (meaning it has a default implementation).
1767 #[derive(RustcEncodable, RustcDecodable, Debug)]
1768 pub struct TraitItem {
1771 pub attrs: HirVec<Attribute>,
1772 pub generics: Generics,
1773 pub node: TraitItemKind,
1777 /// Represents a trait method's body (or just argument names).
1778 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1779 pub enum TraitMethod {
1780 /// No default body in the trait, just a signature.
1781 Required(HirVec<Ident>),
1783 /// Both signature and body are provided in the trait.
1787 /// Represents a trait method or associated constant or type
1788 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1789 pub enum TraitItemKind {
1790 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
1791 Const(P<Ty>, Option<BodyId>),
1792 /// A method with an optional body.
1793 Method(MethodSig, TraitMethod),
1794 /// An associated type with (possibly empty) bounds and optional concrete
1796 Type(GenericBounds, Option<P<Ty>>),
1799 // The bodies for items are stored "out of line", in a separate
1800 // hashmap in the `Crate`. Here we just record the node-id of the item
1801 // so it can fetched later.
1802 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1803 pub struct ImplItemId {
1807 /// Represents anything within an `impl` block
1808 #[derive(RustcEncodable, RustcDecodable, Debug)]
1809 pub struct ImplItem {
1812 pub vis: Visibility,
1813 pub defaultness: Defaultness,
1814 pub attrs: HirVec<Attribute>,
1815 pub generics: Generics,
1816 pub node: ImplItemKind,
1820 /// Represents various kinds of content within an `impl`.
1821 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1822 pub enum ImplItemKind {
1823 /// An associated constant of the given type, set to the constant result
1824 /// of the expression
1825 Const(P<Ty>, BodyId),
1826 /// A method implementation with the given signature and body
1827 Method(MethodSig, BodyId),
1828 /// An associated type
1830 /// An associated existential type
1831 Existential(GenericBounds),
1834 /// Bind a type to an associated type (i.e., `A = Foo`).
1836 /// Bindings like `A: Debug` are represented as a special type `A =
1837 /// $::Debug` that is understood by the astconv code.
1839 /// FIXME(alexreg) -- why have a separate type for the binding case,
1840 /// wouldn't it be better to make the `ty` field an enum like:
1843 /// enum TypeBindingKind {
1848 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1849 pub struct TypeBinding {
1851 #[stable_hasher(project(name))]
1853 pub kind: TypeBindingKind,
1857 // Represents the two kinds of type bindings.
1858 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1859 pub enum TypeBindingKind {
1860 /// E.g., `Foo<Bar: Send>`.
1862 bounds: HirVec<GenericBound>,
1864 /// E.g., `Foo<Bar = ()>`.
1871 pub fn ty(&self) -> &Ty {
1873 TypeBindingKind::Equality { ref ty } => ty,
1874 _ => bug!("expected equality type binding for parenthesized generic args"),
1879 #[derive(RustcEncodable, RustcDecodable)]
1886 impl fmt::Debug for Ty {
1887 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1888 write!(f, "type({})",
1889 print::to_string(print::NO_ANN, |s| s.print_type(self)))
1893 /// Not represented directly in the AST; referred to by name through a `ty_path`.
1894 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
1904 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1905 pub struct BareFnTy {
1906 pub unsafety: Unsafety,
1908 pub generic_params: HirVec<GenericParam>,
1909 pub decl: P<FnDecl>,
1910 pub arg_names: HirVec<Ident>,
1913 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1914 pub struct ExistTy {
1915 pub generics: Generics,
1916 pub bounds: GenericBounds,
1917 pub impl_trait_fn: Option<DefId>,
1918 pub origin: ExistTyOrigin,
1921 /// Where the existential type came from
1922 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1923 pub enum ExistTyOrigin {
1924 /// `existential type Foo: Trait;`
1932 /// The various kinds of types recognized by the compiler.
1933 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1935 /// A variable length slice (i.e., `[T]`).
1937 /// A fixed length array (i.e., `[T; n]`).
1938 Array(P<Ty>, AnonConst),
1939 /// A raw pointer (i.e., `*const T` or `*mut T`).
1941 /// A reference (i.e., `&'a T` or `&'a mut T`).
1942 Rptr(Lifetime, MutTy),
1943 /// A bare function (e.g., `fn(usize) -> bool`).
1944 BareFn(P<BareFnTy>),
1945 /// The never type (`!`).
1947 /// A tuple (`(A, B, C, D, ...)`).
1949 /// A path to a type definition (`module::module::...::Type`), or an
1950 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
1952 /// Type parameters may be stored in each `PathSegment`.
1954 /// A type definition itself. This is currently only used for the `existential type`
1955 /// item that `impl Trait` in return position desugars to.
1957 /// The generic argument list contains the lifetimes (and in the future possibly parameters)
1958 /// that are actually bound on the `impl Trait`.
1959 Def(ItemId, HirVec<GenericArg>),
1960 /// A trait object type `Bound1 + Bound2 + Bound3`
1961 /// where `Bound` is a trait or a lifetime.
1962 TraitObject(HirVec<PolyTraitRef>, Lifetime),
1965 /// `TyKind::Infer` means the type should be inferred instead of it having been
1966 /// specified. This can appear anywhere in a type.
1968 /// Placeholder for a type that has failed to be defined.
1970 /// Placeholder for C-variadic arguments. We "spoof" the `VaListImpl` created
1971 /// from the variadic arguments. This type is only valid up to typeck.
1975 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1976 pub struct InlineAsmOutput {
1977 pub constraint: Symbol,
1979 pub is_indirect: bool,
1983 // NOTE(eddyb) This is used within MIR as well, so unlike the rest of the HIR,
1984 // it needs to be `Clone` and use plain `Vec<T>` instead of `HirVec<T>`.
1985 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1986 pub struct InlineAsm {
1988 pub asm_str_style: StrStyle,
1989 pub outputs: Vec<InlineAsmOutput>,
1990 pub inputs: Vec<Symbol>,
1991 pub clobbers: Vec<Symbol>,
1993 pub alignstack: bool,
1994 pub dialect: AsmDialect,
1995 #[stable_hasher(ignore)] // This is used for error reporting
1996 pub ctxt: SyntaxContext,
1999 /// Represents an argument in a function header.
2000 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2006 /// Represents the header (not the body) of a function declaration.
2007 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2009 /// The types of the function's arguments.
2011 /// Additional argument data is stored in the function's [body](Body::arguments).
2012 pub inputs: HirVec<Ty>,
2013 pub output: FunctionRetTy,
2014 pub c_variadic: bool,
2015 /// Does the function have an implicit self?
2016 pub implicit_self: ImplicitSelfKind,
2019 /// Represents what type of implicit self a function has, if any.
2020 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2021 pub enum ImplicitSelfKind {
2022 /// Represents a `fn x(self);`.
2024 /// Represents a `fn x(mut self);`.
2026 /// Represents a `fn x(&self);`.
2028 /// Represents a `fn x(&mut self);`.
2030 /// Represents when a function does not have a self argument or
2031 /// when a function has a `self: X` argument.
2035 impl ImplicitSelfKind {
2036 /// Does this represent an implicit self?
2037 pub fn has_implicit_self(&self) -> bool {
2039 ImplicitSelfKind::None => false,
2045 /// Is the trait definition an auto trait?
2046 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2052 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, HashStable,
2053 Ord, RustcEncodable, RustcDecodable, Debug)]
2059 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, HashStable,
2060 RustcEncodable, RustcDecodable, Hash, Debug)]
2066 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2067 pub enum Constness {
2072 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2073 pub enum Defaultness {
2074 Default { has_value: bool },
2079 pub fn has_value(&self) -> bool {
2081 Defaultness::Default { has_value, .. } => has_value,
2082 Defaultness::Final => true,
2086 pub fn is_final(&self) -> bool {
2087 *self == Defaultness::Final
2090 pub fn is_default(&self) -> bool {
2092 Defaultness::Default { .. } => true,
2098 impl fmt::Display for Unsafety {
2099 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2100 f.write_str(match self {
2101 Unsafety::Normal => "normal",
2102 Unsafety::Unsafe => "unsafe",
2107 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2108 pub enum ImplPolarity {
2109 /// `impl Trait for Type`
2111 /// `impl !Trait for Type`
2115 impl fmt::Debug for ImplPolarity {
2116 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2117 f.write_str(match self {
2118 ImplPolarity::Positive => "positive",
2119 ImplPolarity::Negative => "negative",
2125 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2126 pub enum FunctionRetTy {
2127 /// Return type is not specified.
2129 /// Functions default to `()` and
2130 /// closures default to inference. Span points to where return
2131 /// type would be inserted.
2132 DefaultReturn(Span),
2133 /// Everything else.
2137 impl fmt::Display for FunctionRetTy {
2138 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2140 Return(ref ty) => print::to_string(print::NO_ANN, |s| s.print_type(ty)).fmt(f),
2141 DefaultReturn(_) => "()".fmt(f),
2146 impl FunctionRetTy {
2147 pub fn span(&self) -> Span {
2149 DefaultReturn(span) => span,
2150 Return(ref ty) => ty.span,
2155 #[derive(RustcEncodable, RustcDecodable, Debug)]
2157 /// A span from the first token past `{` to the last token until `}`.
2158 /// For `mod foo;`, the inner span ranges from the first token
2159 /// to the last token in the external file.
2161 pub item_ids: HirVec<ItemId>,
2164 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2165 pub struct ForeignMod {
2167 pub items: HirVec<ForeignItem>,
2170 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2171 pub struct GlobalAsm {
2173 #[stable_hasher(ignore)] // This is used for error reporting
2174 pub ctxt: SyntaxContext,
2177 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2178 pub struct EnumDef {
2179 pub variants: HirVec<Variant>,
2182 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2183 pub struct VariantKind {
2184 /// Name of the variant.
2185 #[stable_hasher(project(name))]
2187 /// Attributes of the variant.
2188 pub attrs: HirVec<Attribute>,
2189 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2191 /// Fields and constructor id of the variant.
2192 pub data: VariantData,
2193 /// Explicit discriminant (e.g., `Foo = 1`).
2194 pub disr_expr: Option<AnonConst>,
2197 pub type Variant = Spanned<VariantKind>;
2199 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2201 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2202 /// Also produced for each element of a list `use`, e.g.
2203 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2206 /// Glob import, e.g., `use foo::*`.
2209 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2210 /// an additional `use foo::{}` for performing checks such as
2211 /// unstable feature gating. May be removed in the future.
2215 /// References to traits in impls.
2217 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2218 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2219 /// trait being referred to but just a unique `HirId` that serves as a key
2220 /// within the resolution map.
2221 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2222 pub struct TraitRef {
2224 // Don't hash the ref_id. It is tracked via the thing it is used to access
2225 #[stable_hasher(ignore)]
2226 pub hir_ref_id: HirId,
2230 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2231 pub fn trait_def_id(&self) -> DefId {
2232 match self.path.res {
2233 Res::Def(DefKind::Trait, did) => did,
2234 Res::Def(DefKind::TraitAlias, did) => did,
2238 _ => unreachable!(),
2243 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2244 pub struct PolyTraitRef {
2245 /// The `'a` in `<'a> Foo<&'a T>`.
2246 pub bound_generic_params: HirVec<GenericParam>,
2248 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2249 pub trait_ref: TraitRef,
2254 pub type Visibility = Spanned<VisibilityKind>;
2256 #[derive(RustcEncodable, RustcDecodable, Debug)]
2257 pub enum VisibilityKind {
2260 Restricted { path: P<Path>, hir_id: HirId },
2264 impl VisibilityKind {
2265 pub fn is_pub(&self) -> bool {
2267 VisibilityKind::Public => true,
2272 pub fn is_pub_restricted(&self) -> bool {
2274 VisibilityKind::Public |
2275 VisibilityKind::Inherited => false,
2276 VisibilityKind::Crate(..) |
2277 VisibilityKind::Restricted { .. } => true,
2281 pub fn descr(&self) -> &'static str {
2283 VisibilityKind::Public => "public",
2284 VisibilityKind::Inherited => "private",
2285 VisibilityKind::Crate(..) => "crate-visible",
2286 VisibilityKind::Restricted { .. } => "restricted",
2291 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2292 pub struct StructField {
2294 #[stable_hasher(project(name))]
2296 pub vis: Visibility,
2299 pub attrs: HirVec<Attribute>,
2303 // Still necessary in couple of places
2304 pub fn is_positional(&self) -> bool {
2305 let first = self.ident.as_str().as_bytes()[0];
2306 first >= b'0' && first <= b'9'
2310 /// Fields and constructor IDs of enum variants and structs.
2311 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2312 pub enum VariantData {
2313 /// A struct variant.
2315 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2316 Struct(HirVec<StructField>, /* recovered */ bool),
2317 /// A tuple variant.
2319 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2320 Tuple(HirVec<StructField>, HirId),
2323 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2328 /// Return the fields of this variant.
2329 pub fn fields(&self) -> &[StructField] {
2331 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2336 /// Return the `HirId` of this variant's constructor, if it has one.
2337 pub fn ctor_hir_id(&self) -> Option<HirId> {
2339 VariantData::Struct(_, _) => None,
2340 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2345 // The bodies for items are stored "out of line", in a separate
2346 // hashmap in the `Crate`. Here we just record the node-id of the item
2347 // so it can fetched later.
2348 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2355 /// The name might be a dummy name in case of anonymous items
2356 #[derive(RustcEncodable, RustcDecodable, Debug)]
2360 pub attrs: HirVec<Attribute>,
2362 pub vis: Visibility,
2366 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2367 pub struct FnHeader {
2368 pub unsafety: Unsafety,
2369 pub constness: Constness,
2370 pub asyncness: IsAsync,
2375 pub fn is_const(&self) -> bool {
2376 match &self.constness {
2377 Constness::Const => true,
2383 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2385 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2387 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2388 ExternCrate(Option<Name>),
2390 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2394 /// `use foo::bar::baz;` (with `as baz` implicitly on the right)
2395 Use(P<Path>, UseKind),
2398 Static(P<Ty>, Mutability, BodyId),
2400 Const(P<Ty>, BodyId),
2401 /// A function declaration
2402 Fn(P<FnDecl>, FnHeader, Generics, BodyId),
2405 /// An external module
2406 ForeignMod(ForeignMod),
2407 /// Module-level inline assembly (from global_asm!)
2408 GlobalAsm(P<GlobalAsm>),
2409 /// A type alias, e.g., `type Foo = Bar<u8>`
2410 Ty(P<Ty>, Generics),
2411 /// An existential type definition, e.g., `existential type Foo: Bar;`
2412 Existential(ExistTy),
2413 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`
2414 Enum(EnumDef, Generics),
2415 /// A struct definition, e.g., `struct Foo<A> {x: A}`
2416 Struct(VariantData, Generics),
2417 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`
2418 Union(VariantData, Generics),
2419 /// Represents a Trait Declaration
2420 Trait(IsAuto, Unsafety, Generics, GenericBounds, HirVec<TraitItemRef>),
2421 /// Represents a Trait Alias Declaration
2422 TraitAlias(Generics, GenericBounds),
2424 /// An implementation, eg `impl<A> Trait for Foo { .. }`
2429 Option<TraitRef>, // (optional) trait this impl implements
2431 HirVec<ImplItemRef>),
2435 pub fn descriptive_variant(&self) -> &str {
2437 ItemKind::ExternCrate(..) => "extern crate",
2438 ItemKind::Use(..) => "use",
2439 ItemKind::Static(..) => "static item",
2440 ItemKind::Const(..) => "constant item",
2441 ItemKind::Fn(..) => "function",
2442 ItemKind::Mod(..) => "module",
2443 ItemKind::ForeignMod(..) => "foreign module",
2444 ItemKind::GlobalAsm(..) => "global asm",
2445 ItemKind::Ty(..) => "type alias",
2446 ItemKind::Existential(..) => "existential type",
2447 ItemKind::Enum(..) => "enum",
2448 ItemKind::Struct(..) => "struct",
2449 ItemKind::Union(..) => "union",
2450 ItemKind::Trait(..) => "trait",
2451 ItemKind::TraitAlias(..) => "trait alias",
2452 ItemKind::Impl(..) => "impl",
2456 pub fn adt_kind(&self) -> Option<AdtKind> {
2458 ItemKind::Struct(..) => Some(AdtKind::Struct),
2459 ItemKind::Union(..) => Some(AdtKind::Union),
2460 ItemKind::Enum(..) => Some(AdtKind::Enum),
2465 pub fn generics(&self) -> Option<&Generics> {
2467 ItemKind::Fn(_, _, ref generics, _) |
2468 ItemKind::Ty(_, ref generics) |
2469 ItemKind::Existential(ExistTy { ref generics, impl_trait_fn: None, .. }) |
2470 ItemKind::Enum(_, ref generics) |
2471 ItemKind::Struct(_, ref generics) |
2472 ItemKind::Union(_, ref generics) |
2473 ItemKind::Trait(_, _, ref generics, _, _) |
2474 ItemKind::Impl(_, _, _, ref generics, _, _, _)=> generics,
2480 /// A reference from an trait to one of its associated items. This
2481 /// contains the item's id, naturally, but also the item's name and
2482 /// some other high-level details (like whether it is an associated
2483 /// type or method, and whether it is public). This allows other
2484 /// passes to find the impl they want without loading the ID (which
2485 /// means fewer edges in the incremental compilation graph).
2486 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2487 pub struct TraitItemRef {
2488 pub id: TraitItemId,
2489 #[stable_hasher(project(name))]
2491 pub kind: AssocItemKind,
2493 pub defaultness: Defaultness,
2496 /// A reference from an impl to one of its associated items. This
2497 /// contains the item's ID, naturally, but also the item's name and
2498 /// some other high-level details (like whether it is an associated
2499 /// type or method, and whether it is public). This allows other
2500 /// passes to find the impl they want without loading the ID (which
2501 /// means fewer edges in the incremental compilation graph).
2502 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2503 pub struct ImplItemRef {
2505 #[stable_hasher(project(name))]
2507 pub kind: AssocItemKind,
2509 pub vis: Visibility,
2510 pub defaultness: Defaultness,
2513 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2514 pub enum AssocItemKind {
2516 Method { has_self: bool },
2521 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2522 pub struct ForeignItem {
2523 #[stable_hasher(project(name))]
2525 pub attrs: HirVec<Attribute>,
2526 pub node: ForeignItemKind,
2529 pub vis: Visibility,
2532 /// An item within an `extern` block.
2533 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2534 pub enum ForeignItemKind {
2535 /// A foreign function.
2536 Fn(P<FnDecl>, HirVec<Ident>, Generics),
2537 /// A foreign static item (`static ext: u8`).
2538 Static(P<Ty>, Mutability),
2543 impl ForeignItemKind {
2544 pub fn descriptive_variant(&self) -> &str {
2546 ForeignItemKind::Fn(..) => "foreign function",
2547 ForeignItemKind::Static(..) => "foreign static item",
2548 ForeignItemKind::Type => "foreign type",
2553 /// A variable captured by a closure.
2554 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable, HashStable)]
2556 // First span where it is accessed (there can be multiple).
2560 pub type CaptureModeMap = NodeMap<CaptureClause>;
2562 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2563 // has length > 0 if the trait is found through an chain of imports, starting with the
2564 // import/use statement in the scope where the trait is used.
2565 #[derive(Clone, Debug)]
2566 pub struct TraitCandidate {
2568 pub import_ids: SmallVec<[NodeId; 1]>,
2571 // Trait method resolution
2572 pub type TraitMap = NodeMap<Vec<TraitCandidate>>;
2574 // Map from the NodeId of a glob import to a list of items which are actually
2576 pub type GlobMap = NodeMap<FxHashSet<Name>>;
2578 pub fn provide(providers: &mut Providers<'_>) {
2579 check_attr::provide(providers);
2580 map::provide(providers);
2581 upvars::provide(providers);
2584 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
2585 pub struct CodegenFnAttrs {
2586 pub flags: CodegenFnAttrFlags,
2587 /// Parsed representation of the `#[inline]` attribute
2588 pub inline: InlineAttr,
2589 /// Parsed representation of the `#[optimize]` attribute
2590 pub optimize: OptimizeAttr,
2591 /// The `#[export_name = "..."]` attribute, indicating a custom symbol a
2592 /// function should be exported under
2593 pub export_name: Option<Symbol>,
2594 /// The `#[link_name = "..."]` attribute, indicating a custom symbol an
2595 /// imported function should be imported as. Note that `export_name`
2596 /// probably isn't set when this is set, this is for foreign items while
2597 /// `#[export_name]` is for Rust-defined functions.
2598 pub link_name: Option<Symbol>,
2599 /// The `#[target_feature(enable = "...")]` attribute and the enabled
2600 /// features (only enabled features are supported right now).
2601 pub target_features: Vec<Symbol>,
2602 /// The `#[linkage = "..."]` attribute and the value we found.
2603 pub linkage: Option<Linkage>,
2604 /// The `#[link_section = "..."]` attribute, or what executable section this
2605 /// should be placed in.
2606 pub link_section: Option<Symbol>,
2610 #[derive(RustcEncodable, RustcDecodable, HashStable)]
2611 pub struct CodegenFnAttrFlags: u32 {
2612 /// `#[cold]`: a hint to LLVM that this function, when called, is never on
2614 const COLD = 1 << 0;
2615 /// `#[rustc_allocator]`: a hint to LLVM that the pointer returned from this
2616 /// function is never null.
2617 const ALLOCATOR = 1 << 1;
2618 /// `#[unwind]`: an indicator that this function may unwind despite what
2619 /// its ABI signature may otherwise imply.
2620 const UNWIND = 1 << 2;
2621 /// `#[rust_allocator_nounwind]`, an indicator that an imported FFI
2622 /// function will never unwind. Probably obsolete by recent changes with
2623 /// #[unwind], but hasn't been removed/migrated yet
2624 const RUSTC_ALLOCATOR_NOUNWIND = 1 << 3;
2625 /// `#[naked]`: an indicator to LLVM that no function prologue/epilogue
2626 /// should be generated.
2627 const NAKED = 1 << 4;
2628 /// `#[no_mangle]`: an indicator that the function's name should be the same
2630 const NO_MANGLE = 1 << 5;
2631 /// `#[rustc_std_internal_symbol]`: an indicator that this symbol is a
2632 /// "weird symbol" for the standard library in that it has slightly
2633 /// different linkage, visibility, and reachability rules.
2634 const RUSTC_STD_INTERNAL_SYMBOL = 1 << 6;
2635 /// `#[no_debug]`: an indicator that no debugging information should be
2636 /// generated for this function by LLVM.
2637 const NO_DEBUG = 1 << 7;
2638 /// `#[thread_local]`: indicates a static is actually a thread local
2640 const THREAD_LOCAL = 1 << 8;
2641 /// `#[used]`: indicates that LLVM can't eliminate this function (but the
2643 const USED = 1 << 9;
2644 /// #[ffi_returns_twice], indicates that an extern function can return
2646 const FFI_RETURNS_TWICE = 1 << 10;
2650 impl CodegenFnAttrs {
2651 pub fn new() -> CodegenFnAttrs {
2653 flags: CodegenFnAttrFlags::empty(),
2654 inline: InlineAttr::None,
2655 optimize: OptimizeAttr::None,
2658 target_features: vec![],
2664 /// Returns `true` if `#[inline]` or `#[inline(always)]` is present.
2665 pub fn requests_inline(&self) -> bool {
2667 InlineAttr::Hint | InlineAttr::Always => true,
2668 InlineAttr::None | InlineAttr::Never => false,
2672 /// Returns `true` if it looks like this symbol needs to be exported, for example:
2674 /// * `#[no_mangle]` is present
2675 /// * `#[export_name(...)]` is present
2676 /// * `#[linkage]` is present
2677 pub fn contains_extern_indicator(&self) -> bool {
2678 self.flags.contains(CodegenFnAttrFlags::NO_MANGLE) ||
2679 self.export_name.is_some() ||
2680 match self.linkage {
2681 // These are private, so make sure we don't try to consider
2684 Some(Linkage::Internal) |
2685 Some(Linkage::Private) => false,
2691 #[derive(Copy, Clone, Debug)]
2692 pub enum Node<'hir> {
2694 ForeignItem(&'hir ForeignItem),
2695 TraitItem(&'hir TraitItem),
2696 ImplItem(&'hir ImplItem),
2697 Variant(&'hir Variant),
2698 Field(&'hir StructField),
2699 AnonConst(&'hir AnonConst),
2702 PathSegment(&'hir PathSegment),
2704 TraitRef(&'hir TraitRef),
2710 MacroDef(&'hir MacroDef),
2712 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
2713 /// with synthesized constructors.
2714 Ctor(&'hir VariantData),
2716 Lifetime(&'hir Lifetime),
2717 GenericParam(&'hir GenericParam),
2718 Visibility(&'hir Visibility),