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::util::nodemap::{NodeMap, FxHashSet};
16 use crate::mir::mono::Linkage;
18 use errors::FatalError;
19 use syntax_pos::{Span, DUMMY_SP, symbol::InternedString, MultiSpan};
20 use syntax::source_map::Spanned;
21 use rustc_target::spec::abi::Abi;
22 use syntax::ast::{self, CrateSugar, Ident, Name, NodeId, AsmDialect};
23 use syntax::ast::{Attribute, Label, LitKind, StrStyle, FloatTy, IntTy, UintTy};
24 use syntax::attr::{InlineAttr, OptimizeAttr};
25 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;
68 /// Uniquely identifies a node in the HIR of the current crate. It is
69 /// composed of the `owner`, which is the `DefIndex` of the directly enclosing
70 /// `hir::Item`, `hir::TraitItem`, or `hir::ImplItem` (i.e., the closest "item-like"),
71 /// and the `local_id` which is unique within the given owner.
73 /// This two-level structure makes for more stable values: One can move an item
74 /// around within the source code, or add or remove stuff before it, without
75 /// the `local_id` part of the `HirId` changing, which is a very useful property in
76 /// incremental compilation where we have to persist things through changes to
78 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)]
81 pub local_id: ItemLocalId,
85 pub fn owner_def_id(self) -> DefId {
86 DefId::local(self.owner)
89 pub fn owner_local_def_id(self) -> LocalDefId {
90 LocalDefId::from_def_id(DefId::local(self.owner))
94 impl serialize::UseSpecializedEncodable for HirId {
95 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
106 impl serialize::UseSpecializedDecodable for HirId {
107 fn default_decode<D: Decoder>(d: &mut D) -> Result<HirId, D::Error> {
108 let owner = DefIndex::decode(d)?;
109 let local_id = ItemLocalId::decode(d)?;
118 impl fmt::Display for HirId {
119 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120 write!(f, "{:?}", self)
124 // Hack to ensure that we don't try to access the private parts of `ItemLocalId` in this module
125 mod item_local_id_inner {
126 use rustc_data_structures::indexed_vec::Idx;
127 use rustc_macros::HashStable;
129 /// An `ItemLocalId` uniquely identifies something within a given "item-like";
130 /// that is, within a `hir::Item`, `hir::TraitItem`, or `hir::ImplItem`. There is no
131 /// guarantee that the numerical value of a given `ItemLocalId` corresponds to
132 /// the node's position within the owning item in any way, but there is a
133 /// guarantee that the `LocalItemId`s within an owner occupy a dense range of
134 /// integers starting at zero, so a mapping that maps all or most nodes within
135 /// an "item-like" to something else can be implemented by a `Vec` instead of a
136 /// tree or hash map.
137 pub struct ItemLocalId {
143 pub use self::item_local_id_inner::ItemLocalId;
145 /// The `HirId` corresponding to `CRATE_NODE_ID` and `CRATE_DEF_INDEX`.
146 pub const CRATE_HIR_ID: HirId = HirId {
147 owner: CRATE_DEF_INDEX,
148 local_id: ItemLocalId::from_u32_const(0)
151 pub const DUMMY_HIR_ID: HirId = HirId {
152 owner: CRATE_DEF_INDEX,
153 local_id: DUMMY_ITEM_LOCAL_ID,
156 pub const DUMMY_ITEM_LOCAL_ID: ItemLocalId = ItemLocalId::MAX;
158 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, HashStable)]
159 pub struct Lifetime {
163 /// Either "`'a`", referring to a named lifetime definition,
164 /// or "``" (i.e., `kw::Invalid`), for elision placeholders.
166 /// HIR lowering inserts these placeholders in type paths that
167 /// refer to type definitions needing lifetime parameters,
168 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
169 pub name: LifetimeName,
172 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy, HashStable)]
174 /// Some user-given name like `T` or `'x`.
177 /// Synthetic name generated when user elided a lifetime in an impl header.
179 /// E.g., the lifetimes in cases like these:
181 /// impl Foo for &u32
182 /// impl Foo<'_> for u32
184 /// in that case, we rewrite to
186 /// impl<'f> Foo for &'f u32
187 /// impl<'f> Foo<'f> for u32
189 /// where `'f` is something like `Fresh(0)`. The indices are
190 /// unique per impl, but not necessarily continuous.
193 /// Indicates an illegal name was given and an error has been
194 /// repored (so we should squelch other derived errors). Occurs
195 /// when, e.g., `'_` is used in the wrong place.
200 pub fn ident(&self) -> Ident {
202 ParamName::Plain(ident) => ident,
203 ParamName::Fresh(_) |
204 ParamName::Error => Ident::with_empty_ctxt(kw::UnderscoreLifetime),
208 pub fn modern(&self) -> ParamName {
210 ParamName::Plain(ident) => ParamName::Plain(ident.modern()),
211 param_name => param_name,
216 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy, HashStable)]
217 pub enum LifetimeName {
218 /// User-given names or fresh (synthetic) names.
221 /// User wrote nothing (e.g., the lifetime in `&u32`).
224 /// Indicates an error during lowering (usually `'_` in wrong place)
225 /// that was already reported.
228 /// User wrote specifies `'_`.
231 /// User wrote `'static`.
236 pub fn ident(&self) -> Ident {
238 LifetimeName::Implicit | LifetimeName::Error => Ident::invalid(),
239 LifetimeName::Underscore => Ident::with_empty_ctxt(kw::UnderscoreLifetime),
240 LifetimeName::Static => Ident::with_empty_ctxt(kw::StaticLifetime),
241 LifetimeName::Param(param_name) => param_name.ident(),
245 pub fn is_elided(&self) -> bool {
247 LifetimeName::Implicit | LifetimeName::Underscore => true,
249 // It might seem surprising that `Fresh(_)` counts as
250 // *not* elided -- but this is because, as far as the code
251 // in the compiler is concerned -- `Fresh(_)` variants act
252 // equivalently to "some fresh name". They correspond to
253 // early-bound regions on an impl, in other words.
254 LifetimeName::Error | LifetimeName::Param(_) | LifetimeName::Static => false,
258 fn is_static(&self) -> bool {
259 self == &LifetimeName::Static
262 pub fn modern(&self) -> LifetimeName {
264 LifetimeName::Param(param_name) => LifetimeName::Param(param_name.modern()),
265 lifetime_name => lifetime_name,
270 impl fmt::Display for Lifetime {
271 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
272 self.name.ident().fmt(f)
276 impl fmt::Debug for Lifetime {
277 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
281 print::to_string(print::NO_ANN, |s| s.print_lifetime(self)))
286 pub fn is_elided(&self) -> bool {
287 self.name.is_elided()
290 pub fn is_static(&self) -> bool {
291 self.name.is_static()
295 /// A `Path` is essentially Rust's notion of a name; for instance,
296 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
297 /// along with a bunch of supporting information.
298 #[derive(RustcEncodable, RustcDecodable, HashStable)]
301 /// The resolution for the path.
303 /// The segments in the path: the things separated by `::`.
304 pub segments: HirVec<PathSegment>,
308 pub fn is_global(&self) -> bool {
309 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
313 impl fmt::Debug for Path {
314 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
315 write!(f, "path({})", self)
319 impl fmt::Display for Path {
320 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
321 write!(f, "{}", print::to_string(print::NO_ANN, |s| s.print_path(self, false)))
325 /// A segment of a path: an identifier, an optional lifetime, and a set of
327 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
328 pub struct PathSegment {
329 /// The identifier portion of this path segment.
330 #[stable_hasher(project(name))]
332 // `id` and `res` are optional. We currently only use these in save-analysis,
333 // any path segments without these will not have save-analysis info and
334 // therefore will not have 'jump to def' in IDEs, but otherwise will not be
335 // affected. (In general, we don't bother to get the defs for synthesized
336 // segments, only for segments which have come from the AST).
337 pub hir_id: Option<HirId>,
338 pub res: Option<Res>,
340 /// Type/lifetime parameters attached to this path. They come in
341 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
342 /// this is more than just simple syntactic sugar; the use of
343 /// parens affects the region binding rules, so we preserve the
345 pub args: Option<P<GenericArgs>>,
347 /// Whether to infer remaining type parameters, if any.
348 /// This only applies to expression and pattern paths, and
349 /// out of those only the segments with no type parameters
350 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
351 pub infer_args: bool,
355 /// Converts an identifier to the corresponding segment.
356 pub fn from_ident(ident: Ident) -> PathSegment {
368 hir_id: Option<HirId>,
378 args: if args.is_empty() {
386 pub fn generic_args(&self) -> &GenericArgs {
387 if let Some(ref args) = self.args {
390 const DUMMY: &GenericArgs = &GenericArgs::none();
396 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
397 pub struct ConstArg {
398 pub value: AnonConst,
402 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
403 pub enum GenericArg {
410 pub fn span(&self) -> Span {
412 GenericArg::Lifetime(l) => l.span,
413 GenericArg::Type(t) => t.span,
414 GenericArg::Const(c) => c.span,
418 pub fn id(&self) -> HirId {
420 GenericArg::Lifetime(l) => l.hir_id,
421 GenericArg::Type(t) => t.hir_id,
422 GenericArg::Const(c) => c.value.hir_id,
426 pub fn is_const(&self) -> bool {
428 GenericArg::Const(_) => true,
434 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
435 pub struct GenericArgs {
436 /// The generic arguments for this path segment.
437 pub args: HirVec<GenericArg>,
438 /// Bindings (equality constraints) on associated types, if present.
439 /// E.g., `Foo<A = Bar>`.
440 pub bindings: HirVec<TypeBinding>,
441 /// Were arguments written in parenthesized form `Fn(T) -> U`?
442 /// This is required mostly for pretty-printing and diagnostics,
443 /// but also for changing lifetime elision rules to be "function-like".
444 pub parenthesized: bool,
448 pub const fn none() -> Self {
451 bindings: HirVec::new(),
452 parenthesized: false,
456 pub fn is_empty(&self) -> bool {
457 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
460 pub fn inputs(&self) -> &[Ty] {
461 if self.parenthesized {
462 for arg in &self.args {
464 GenericArg::Lifetime(_) => {}
465 GenericArg::Type(ref ty) => {
466 if let TyKind::Tup(ref tys) = ty.node {
471 GenericArg::Const(_) => {}
475 bug!("GenericArgs::inputs: not a `Fn(T) -> U`");
478 pub fn own_counts(&self) -> GenericParamCount {
479 // We could cache this as a property of `GenericParamCount`, but
480 // the aim is to refactor this away entirely eventually and the
481 // presence of this method will be a constant reminder.
482 let mut own_counts: GenericParamCount = Default::default();
484 for arg in &self.args {
486 GenericArg::Lifetime(_) => own_counts.lifetimes += 1,
487 GenericArg::Type(_) => own_counts.types += 1,
488 GenericArg::Const(_) => own_counts.consts += 1,
496 /// A modifier on a bound, currently this is only used for `?Sized`, where the
497 /// modifier is `Maybe`. Negative bounds should also be handled here.
498 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
499 pub enum TraitBoundModifier {
504 /// The AST represents all type param bounds as types.
505 /// `typeck::collect::compute_bounds` matches these against
506 /// the "special" built-in traits (see `middle::lang_items`) and
507 /// detects `Copy`, `Send` and `Sync`.
508 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
509 pub enum GenericBound {
510 Trait(PolyTraitRef, TraitBoundModifier),
515 pub fn span(&self) -> Span {
517 &GenericBound::Trait(ref t, ..) => t.span,
518 &GenericBound::Outlives(ref l) => l.span,
523 pub type GenericBounds = HirVec<GenericBound>;
525 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable)]
526 pub enum LifetimeParamKind {
527 // Indicates that the lifetime definition was explicitly declared (e.g., in
528 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
531 // Indicates that the lifetime definition was synthetically added
532 // as a result of an in-band lifetime usage (e.g., in
533 // `fn foo(x: &'a u8) -> &'a u8 { x }`).
536 // Indication that the lifetime was elided (e.g., in both cases in
537 // `fn foo(x: &u8) -> &'_ u8 { x }`).
540 // Indication that the lifetime name was somehow in error.
544 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
545 pub enum GenericParamKind {
546 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
548 kind: LifetimeParamKind,
551 default: Option<P<Ty>>,
552 synthetic: Option<SyntheticTyParamKind>,
559 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
560 pub struct GenericParam {
563 pub attrs: HirVec<Attribute>,
564 pub bounds: GenericBounds,
566 pub pure_wrt_drop: bool,
567 pub kind: GenericParamKind,
571 pub struct GenericParamCount {
572 pub lifetimes: usize,
577 /// Represents lifetimes and type parameters attached to a declaration
578 /// of a function, enum, trait, etc.
579 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
580 pub struct Generics {
581 pub params: HirVec<GenericParam>,
582 pub where_clause: WhereClause,
587 pub const fn empty() -> Generics {
589 params: HirVec::new(),
590 where_clause: WhereClause {
591 predicates: HirVec::new(),
598 pub fn own_counts(&self) -> GenericParamCount {
599 // We could cache this as a property of `GenericParamCount`, but
600 // the aim is to refactor this away entirely eventually and the
601 // presence of this method will be a constant reminder.
602 let mut own_counts: GenericParamCount = Default::default();
604 for param in &self.params {
606 GenericParamKind::Lifetime { .. } => own_counts.lifetimes += 1,
607 GenericParamKind::Type { .. } => own_counts.types += 1,
608 GenericParamKind::Const { .. } => own_counts.consts += 1,
615 pub fn get_named(&self, name: InternedString) -> Option<&GenericParam> {
616 for param in &self.params {
617 if name == param.name.ident().as_interned_str() {
624 pub fn spans(&self) -> MultiSpan {
625 if self.params.is_empty() {
628 self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
633 /// Synthetic type parameters are converted to another form during lowering; this allows
634 /// us to track the original form they had, and is useful for error messages.
635 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
636 pub enum SyntheticTyParamKind {
640 /// A where-clause in a definition.
641 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
642 pub struct WhereClause {
643 pub predicates: HirVec<WherePredicate>,
644 // Only valid if predicates isn't empty.
649 pub fn span(&self) -> Option<Span> {
650 if self.predicates.is_empty() {
658 /// A single predicate in a where-clause.
659 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
660 pub enum WherePredicate {
661 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
662 BoundPredicate(WhereBoundPredicate),
663 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
664 RegionPredicate(WhereRegionPredicate),
665 /// An equality predicate (unsupported).
666 EqPredicate(WhereEqPredicate),
669 impl WherePredicate {
670 pub fn span(&self) -> Span {
672 &WherePredicate::BoundPredicate(ref p) => p.span,
673 &WherePredicate::RegionPredicate(ref p) => p.span,
674 &WherePredicate::EqPredicate(ref p) => p.span,
679 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
680 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
681 pub struct WhereBoundPredicate {
683 /// Any generics from a `for` binding.
684 pub bound_generic_params: HirVec<GenericParam>,
685 /// The type being bounded.
686 pub bounded_ty: P<Ty>,
687 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
688 pub bounds: GenericBounds,
691 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
692 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
693 pub struct WhereRegionPredicate {
695 pub lifetime: Lifetime,
696 pub bounds: GenericBounds,
699 /// An equality predicate (e.g., `T = int`); currently unsupported.
700 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
701 pub struct WhereEqPredicate {
708 #[derive(RustcEncodable, RustcDecodable, Debug)]
709 pub struct ModuleItems {
710 // Use BTreeSets here so items are in the same order as in the
711 // list of all items in Crate
712 pub items: BTreeSet<HirId>,
713 pub trait_items: BTreeSet<TraitItemId>,
714 pub impl_items: BTreeSet<ImplItemId>,
717 /// The top-level data structure that stores the entire contents of
718 /// the crate currently being compiled.
720 /// For more details, see the [rustc guide].
722 /// [rustc guide]: https://rust-lang.github.io/rustc-guide/hir.html
723 #[derive(RustcEncodable, RustcDecodable, Debug)]
726 pub attrs: HirVec<Attribute>,
728 pub exported_macros: HirVec<MacroDef>,
730 // N.B., we use a BTreeMap here so that `visit_all_items` iterates
731 // over the ids in increasing order. In principle it should not
732 // matter what order we visit things in, but in *practice* it
733 // does, because it can affect the order in which errors are
734 // detected, which in turn can make compile-fail tests yield
735 // slightly different results.
736 pub items: BTreeMap<HirId, Item>,
738 pub trait_items: BTreeMap<TraitItemId, TraitItem>,
739 pub impl_items: BTreeMap<ImplItemId, ImplItem>,
740 pub bodies: BTreeMap<BodyId, Body>,
741 pub trait_impls: BTreeMap<DefId, Vec<HirId>>,
743 /// A list of the body ids written out in the order in which they
744 /// appear in the crate. If you're going to process all the bodies
745 /// in the crate, you should iterate over this list rather than the keys
747 pub body_ids: Vec<BodyId>,
749 /// A list of modules written out in the order in which they
750 /// appear in the crate. This includes the main crate module.
751 pub modules: BTreeMap<NodeId, ModuleItems>,
755 pub fn item(&self, id: HirId) -> &Item {
759 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem {
760 &self.trait_items[&id]
763 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem {
764 &self.impl_items[&id]
767 /// Visits all items in the crate in some deterministic (but
768 /// unspecified) order. If you just need to process every item,
769 /// but don't care about nesting, this method is the best choice.
771 /// If you do care about nesting -- usually because your algorithm
772 /// follows lexical scoping rules -- then you want a different
773 /// approach. You should override `visit_nested_item` in your
774 /// visitor and then call `intravisit::walk_crate` instead.
775 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
776 where V: itemlikevisit::ItemLikeVisitor<'hir>
778 for (_, item) in &self.items {
779 visitor.visit_item(item);
782 for (_, trait_item) in &self.trait_items {
783 visitor.visit_trait_item(trait_item);
786 for (_, impl_item) in &self.impl_items {
787 visitor.visit_impl_item(impl_item);
791 /// A parallel version of `visit_all_item_likes`.
792 pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
793 where V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send
796 par_for_each_in(&self.items, |(_, item)| {
797 visitor.visit_item(item);
800 par_for_each_in(&self.trait_items, |(_, trait_item)| {
801 visitor.visit_trait_item(trait_item);
804 par_for_each_in(&self.impl_items, |(_, impl_item)| {
805 visitor.visit_impl_item(impl_item);
810 pub fn body(&self, id: BodyId) -> &Body {
815 /// A macro definition, in this crate or imported from another.
817 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
818 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
819 pub struct MacroDef {
822 pub attrs: HirVec<Attribute>,
825 pub body: TokenStream,
829 /// A block of statements `{ .. }`, which may have a label (in this case the
830 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
831 /// the `rules` being anything but `DefaultBlock`.
832 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
834 /// Statements in a block.
835 pub stmts: HirVec<Stmt>,
836 /// An expression at the end of the block
837 /// without a semicolon, if any.
838 pub expr: Option<P<Expr>>,
839 #[stable_hasher(ignore)]
841 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
842 pub rules: BlockCheckMode,
844 /// If true, then there may exist `break 'a` values that aim to
845 /// break out of this block early.
846 /// Used by `'label: {}` blocks and by `catch` statements.
847 pub targeted_by_break: bool,
850 #[derive(RustcEncodable, RustcDecodable, HashStable)]
852 #[stable_hasher(ignore)]
858 impl fmt::Debug for Pat {
859 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
860 write!(f, "pat({}: {})", self.hir_id,
861 print::to_string(print::NO_ANN, |s| s.print_pat(self)))
866 // FIXME(#19596) this is a workaround, but there should be a better way
867 fn walk_<G>(&self, it: &mut G) -> bool
868 where G: FnMut(&Pat) -> bool
875 PatKind::Binding(.., Some(ref p)) => p.walk_(it),
876 PatKind::Struct(_, ref fields, _) => {
877 fields.iter().all(|field| field.node.pat.walk_(it))
879 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
880 s.iter().all(|p| p.walk_(it))
882 PatKind::Box(ref s) | PatKind::Ref(ref s, _) => {
885 PatKind::Slice(ref before, ref slice, ref after) => {
889 .all(|p| p.walk_(it))
894 PatKind::Binding(..) |
895 PatKind::Path(_) => {
901 pub fn walk<F>(&self, mut it: F) -> bool
902 where F: FnMut(&Pat) -> bool
908 /// A single field in a struct pattern.
910 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
911 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
912 /// except `is_shorthand` is true.
913 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
914 pub struct FieldPat {
915 #[stable_hasher(ignore)]
917 /// The identifier for the field.
918 #[stable_hasher(project(name))]
920 /// The pattern the field is destructured to.
922 pub is_shorthand: bool,
925 /// Explicit binding annotations given in the HIR for a binding. Note
926 /// that this is not the final binding *mode* that we infer after type
928 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
929 pub enum BindingAnnotation {
930 /// No binding annotation given: this means that the final binding mode
931 /// will depend on whether we have skipped through a `&` reference
932 /// when matching. For example, the `x` in `Some(x)` will have binding
933 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
934 /// ultimately be inferred to be by-reference.
936 /// Note that implicit reference skipping is not implemented yet (#42640).
939 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
942 /// Annotated as `ref`, like `ref x`
945 /// Annotated as `ref mut x`.
949 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
955 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
957 /// Represents a wildcard pattern (i.e., `_`).
960 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
961 /// The `HirId` is the canonical ID for the variable being bound,
962 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
963 /// which is the pattern ID of the first `x`.
964 Binding(BindingAnnotation, HirId, Ident, Option<P<Pat>>),
966 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
967 /// The `bool` is `true` in the presence of a `..`.
968 Struct(QPath, HirVec<Spanned<FieldPat>>, bool),
970 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
971 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
972 /// `0 <= position <= subpats.len()`
973 TupleStruct(QPath, HirVec<P<Pat>>, Option<usize>),
975 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
978 /// A tuple pattern (e.g., `(a, b)`).
979 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
980 /// `0 <= position <= subpats.len()`
981 Tuple(HirVec<P<Pat>>, Option<usize>),
986 /// A reference pattern (e.g., `&mut (a, b)`).
987 Ref(P<Pat>, Mutability),
992 /// A range pattern (e.g., `1..=2` or `1..2`).
993 Range(P<Expr>, P<Expr>, RangeEnd),
995 /// `[a, b, ..i, y, z]` is represented as:
996 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`.
997 Slice(HirVec<P<Pat>>, Option<P<Pat>>, HirVec<P<Pat>>),
1000 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, HashStable,
1001 RustcEncodable, RustcDecodable, Hash, Debug)]
1002 pub enum Mutability {
1008 /// Returns `MutMutable` only if both arguments are mutable.
1009 pub fn and(self, other: Self) -> Self {
1011 MutMutable => other,
1012 MutImmutable => MutImmutable,
1017 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Hash, HashStable)]
1018 pub enum BinOpKind {
1019 /// The `+` operator (addition).
1021 /// The `-` operator (subtraction).
1023 /// The `*` operator (multiplication).
1025 /// The `/` operator (division).
1027 /// The `%` operator (modulus).
1029 /// The `&&` operator (logical and).
1031 /// The `||` operator (logical or).
1033 /// The `^` operator (bitwise xor).
1035 /// The `&` operator (bitwise and).
1037 /// The `|` operator (bitwise or).
1039 /// The `<<` operator (shift left).
1041 /// The `>>` operator (shift right).
1043 /// The `==` operator (equality).
1045 /// The `<` operator (less than).
1047 /// The `<=` operator (less than or equal to).
1049 /// The `!=` operator (not equal to).
1051 /// The `>=` operator (greater than or equal to).
1053 /// The `>` operator (greater than).
1058 pub fn as_str(self) -> &'static str {
1060 BinOpKind::Add => "+",
1061 BinOpKind::Sub => "-",
1062 BinOpKind::Mul => "*",
1063 BinOpKind::Div => "/",
1064 BinOpKind::Rem => "%",
1065 BinOpKind::And => "&&",
1066 BinOpKind::Or => "||",
1067 BinOpKind::BitXor => "^",
1068 BinOpKind::BitAnd => "&",
1069 BinOpKind::BitOr => "|",
1070 BinOpKind::Shl => "<<",
1071 BinOpKind::Shr => ">>",
1072 BinOpKind::Eq => "==",
1073 BinOpKind::Lt => "<",
1074 BinOpKind::Le => "<=",
1075 BinOpKind::Ne => "!=",
1076 BinOpKind::Ge => ">=",
1077 BinOpKind::Gt => ">",
1081 pub fn is_lazy(self) -> bool {
1083 BinOpKind::And | BinOpKind::Or => true,
1088 pub fn is_shift(self) -> bool {
1090 BinOpKind::Shl | BinOpKind::Shr => true,
1095 pub fn is_comparison(self) -> bool {
1102 BinOpKind::Ge => true,
1114 BinOpKind::Shr => false,
1118 /// Returns `true` if the binary operator takes its arguments by value.
1119 pub fn is_by_value(self) -> bool {
1120 !self.is_comparison()
1124 impl Into<ast::BinOpKind> for BinOpKind {
1125 fn into(self) -> ast::BinOpKind {
1127 BinOpKind::Add => ast::BinOpKind::Add,
1128 BinOpKind::Sub => ast::BinOpKind::Sub,
1129 BinOpKind::Mul => ast::BinOpKind::Mul,
1130 BinOpKind::Div => ast::BinOpKind::Div,
1131 BinOpKind::Rem => ast::BinOpKind::Rem,
1132 BinOpKind::And => ast::BinOpKind::And,
1133 BinOpKind::Or => ast::BinOpKind::Or,
1134 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1135 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1136 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1137 BinOpKind::Shl => ast::BinOpKind::Shl,
1138 BinOpKind::Shr => ast::BinOpKind::Shr,
1139 BinOpKind::Eq => ast::BinOpKind::Eq,
1140 BinOpKind::Lt => ast::BinOpKind::Lt,
1141 BinOpKind::Le => ast::BinOpKind::Le,
1142 BinOpKind::Ne => ast::BinOpKind::Ne,
1143 BinOpKind::Ge => ast::BinOpKind::Ge,
1144 BinOpKind::Gt => ast::BinOpKind::Gt,
1149 pub type BinOp = Spanned<BinOpKind>;
1151 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Hash, HashStable)]
1153 /// The `*` operator (deferencing).
1155 /// The `!` operator (logical negation).
1157 /// The `-` operator (negation).
1162 pub fn as_str(self) -> &'static str {
1170 /// Returns `true` if the unary operator takes its argument by value.
1171 pub fn is_by_value(self) -> bool {
1173 UnNeg | UnNot => true,
1180 #[derive(RustcEncodable, RustcDecodable)]
1187 impl fmt::Debug for Stmt {
1188 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1189 write!(f, "stmt({}: {})", self.hir_id,
1190 print::to_string(print::NO_ANN, |s| s.print_stmt(self)))
1194 /// The contents of a statement.
1195 #[derive(RustcEncodable, RustcDecodable, HashStable)]
1197 /// A local (`let`) binding.
1200 /// An item binding.
1203 /// An expression without a trailing semi-colon (must have unit type).
1206 /// An expression with a trailing semi-colon (may have any type).
1211 pub fn attrs(&self) -> &[Attribute] {
1213 StmtKind::Local(ref l) => &l.attrs,
1214 StmtKind::Item(_) => &[],
1215 StmtKind::Expr(ref e) |
1216 StmtKind::Semi(ref e) => &e.attrs,
1221 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1222 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1225 /// Type annotation, if any (otherwise the type will be inferred).
1226 pub ty: Option<P<Ty>>,
1227 /// Initializer expression to set the value, if any.
1228 pub init: Option<P<Expr>>,
1231 pub attrs: ThinVec<Attribute>,
1232 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1233 /// desugaring. Otherwise will be `Normal`.
1234 pub source: LocalSource,
1237 /// Represents a single arm of a `match` expression, e.g.
1238 /// `<pats> (if <guard>) => <body>`.
1239 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1241 #[stable_hasher(ignore)]
1244 pub attrs: HirVec<Attribute>,
1245 /// Multiple patterns can be combined with `|`
1246 pub pats: HirVec<P<Pat>>,
1247 /// Optional guard clause.
1248 pub guard: Option<Guard>,
1249 /// The expression the arm evaluates to if this arm matches.
1253 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1258 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1260 #[stable_hasher(ignore)]
1265 pub is_shorthand: bool,
1268 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1269 pub enum BlockCheckMode {
1271 UnsafeBlock(UnsafeSource),
1272 PushUnsafeBlock(UnsafeSource),
1273 PopUnsafeBlock(UnsafeSource),
1276 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1277 pub enum UnsafeSource {
1282 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1287 /// The body of a function, closure, or constant value. In the case of
1288 /// a function, the body contains not only the function body itself
1289 /// (which is an expression), but also the argument patterns, since
1290 /// those are something that the caller doesn't really care about.
1295 /// fn foo((x, y): (u32, u32)) -> u32 {
1300 /// Here, the `Body` associated with `foo()` would contain:
1302 /// - an `arguments` array containing the `(x, y)` pattern
1303 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1304 /// - `generator_kind` would be `None`
1306 /// All bodies have an **owner**, which can be accessed via the HIR
1307 /// map using `body_owner_def_id()`.
1308 #[derive(RustcEncodable, RustcDecodable, Debug)]
1310 pub arguments: HirVec<Arg>,
1312 pub generator_kind: Option<GeneratorKind>,
1316 pub fn id(&self) -> BodyId {
1318 hir_id: self.value.hir_id,
1323 /// The type of source expression that caused this generator to be created.
1324 // Not `IsAsync` because we want to eventually add support for `AsyncGen`
1325 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, HashStable,
1326 RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1327 pub enum GeneratorKind {
1328 /// An `async` block or function.
1330 /// A generator literal created via a `yield` inside a closure.
1334 impl fmt::Display for GeneratorKind {
1335 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1336 f.write_str(match self {
1337 GeneratorKind::Async => "`async` object",
1338 GeneratorKind::Gen => "generator",
1343 #[derive(Copy, Clone, Debug)]
1344 pub enum BodyOwnerKind {
1345 /// Functions and methods.
1351 /// Constants and associated constants.
1354 /// Initializer of a `static` item.
1358 impl BodyOwnerKind {
1359 pub fn is_fn_or_closure(self) -> bool {
1361 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1362 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1368 pub type Lit = Spanned<LitKind>;
1370 /// A constant (expression) that's not an item or associated item,
1371 /// but needs its own `DefId` for type-checking, const-eval, etc.
1372 /// These are usually found nested inside types (e.g., array lengths)
1373 /// or expressions (e.g., repeat counts), and also used to define
1374 /// explicit discriminant values for enum variants.
1375 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1376 pub struct AnonConst {
1382 #[derive(RustcEncodable, RustcDecodable)]
1386 pub attrs: ThinVec<Attribute>,
1390 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1391 #[cfg(target_arch = "x86_64")]
1392 static_assert_size!(Expr, 72);
1395 pub fn precedence(&self) -> ExprPrecedence {
1397 ExprKind::Box(_) => ExprPrecedence::Box,
1398 ExprKind::Array(_) => ExprPrecedence::Array,
1399 ExprKind::Call(..) => ExprPrecedence::Call,
1400 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1401 ExprKind::Tup(_) => ExprPrecedence::Tup,
1402 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1403 ExprKind::Unary(..) => ExprPrecedence::Unary,
1404 ExprKind::Lit(_) => ExprPrecedence::Lit,
1405 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1406 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1407 ExprKind::While(..) => ExprPrecedence::While,
1408 ExprKind::Loop(..) => ExprPrecedence::Loop,
1409 ExprKind::Match(..) => ExprPrecedence::Match,
1410 ExprKind::Closure(..) => ExprPrecedence::Closure,
1411 ExprKind::Block(..) => ExprPrecedence::Block,
1412 ExprKind::Assign(..) => ExprPrecedence::Assign,
1413 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1414 ExprKind::Field(..) => ExprPrecedence::Field,
1415 ExprKind::Index(..) => ExprPrecedence::Index,
1416 ExprKind::Path(..) => ExprPrecedence::Path,
1417 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1418 ExprKind::Break(..) => ExprPrecedence::Break,
1419 ExprKind::Continue(..) => ExprPrecedence::Continue,
1420 ExprKind::Ret(..) => ExprPrecedence::Ret,
1421 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1422 ExprKind::Struct(..) => ExprPrecedence::Struct,
1423 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1424 ExprKind::Yield(..) => ExprPrecedence::Yield,
1425 ExprKind::Err => ExprPrecedence::Err,
1429 pub fn is_place_expr(&self) -> bool {
1431 ExprKind::Path(QPath::Resolved(_, ref path)) => {
1434 | Res::Def(DefKind::Static, _)
1440 ExprKind::Type(ref e, _) => {
1444 ExprKind::Unary(UnDeref, _) |
1445 ExprKind::Field(..) |
1446 ExprKind::Index(..) => {
1450 // Partially qualified paths in expressions can only legally
1451 // refer to associated items which are always rvalues.
1452 ExprKind::Path(QPath::TypeRelative(..)) |
1454 ExprKind::Call(..) |
1455 ExprKind::MethodCall(..) |
1456 ExprKind::Struct(..) |
1458 ExprKind::Match(..) |
1459 ExprKind::Closure(..) |
1460 ExprKind::Block(..) |
1461 ExprKind::Repeat(..) |
1462 ExprKind::Array(..) |
1463 ExprKind::Break(..) |
1464 ExprKind::Continue(..) |
1466 ExprKind::While(..) |
1467 ExprKind::Loop(..) |
1468 ExprKind::Assign(..) |
1469 ExprKind::InlineAsm(..) |
1470 ExprKind::AssignOp(..) |
1472 ExprKind::Unary(..) |
1474 ExprKind::AddrOf(..) |
1475 ExprKind::Binary(..) |
1476 ExprKind::Yield(..) |
1477 ExprKind::Cast(..) |
1478 ExprKind::DropTemps(..) |
1486 impl fmt::Debug for Expr {
1487 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1488 write!(f, "expr({}: {})", self.hir_id,
1489 print::to_string(print::NO_ANN, |s| s.print_expr(self)))
1493 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1495 /// A `box x` expression.
1497 /// An array (e.g., `[a, b, c, d]`).
1498 Array(HirVec<Expr>),
1499 /// A function call.
1501 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1502 /// and the second field is the list of arguments.
1503 /// This also represents calling the constructor of
1504 /// tuple-like ADTs such as tuple structs and enum variants.
1505 Call(P<Expr>, HirVec<Expr>),
1506 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1508 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1509 /// (within the angle brackets).
1510 /// The first element of the vector of `Expr`s is the expression that evaluates
1511 /// to the object on which the method is being called on (the receiver),
1512 /// and the remaining elements are the rest of the arguments.
1513 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1514 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1515 MethodCall(P<PathSegment>, Span, HirVec<Expr>),
1516 /// A tuple (e.g., `(a, b, c ,d)`).
1518 /// A binary operation (e.g., `a + b`, `a * b`).
1519 Binary(BinOp, P<Expr>, P<Expr>),
1520 /// A unary operation (e.g., `!x`, `*x`).
1521 Unary(UnOp, P<Expr>),
1522 /// A literal (e.g., `1`, `"foo"`).
1524 /// A cast (e.g., `foo as f64`).
1525 Cast(P<Expr>, P<Ty>),
1526 /// A type reference (e.g., `Foo`).
1527 Type(P<Expr>, P<Ty>),
1528 /// Wraps the expression in a terminating scope.
1529 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1531 /// This construct only exists to tweak the drop order in HIR lowering.
1532 /// An example of that is the desugaring of `for` loops.
1534 /// A while loop, with an optional label
1536 /// I.e., `'label: while expr { <block> }`.
1537 While(P<Expr>, P<Block>, Option<Label>),
1538 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1540 /// I.e., `'label: loop { <block> }`.
1541 Loop(P<Block>, Option<Label>, LoopSource),
1542 /// A `match` block, with a source that indicates whether or not it is
1543 /// the result of a desugaring, and if so, which kind.
1544 Match(P<Expr>, HirVec<Arm>, MatchSource),
1545 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1547 /// The final span is the span of the argument block `|...|`.
1549 /// This may also be a generator literal or an `async block` as indicated by the
1550 /// `Option<GeneratorMovability>`.
1551 Closure(CaptureClause, P<FnDecl>, BodyId, Span, Option<GeneratorMovability>),
1552 /// A block (e.g., `'label: { ... }`).
1553 Block(P<Block>, Option<Label>),
1555 /// An assignment (e.g., `a = foo()`).
1556 Assign(P<Expr>, P<Expr>),
1557 /// An assignment with an operator.
1560 AssignOp(BinOp, P<Expr>, P<Expr>),
1561 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1562 Field(P<Expr>, Ident),
1563 /// An indexing operation (`foo[2]`).
1564 Index(P<Expr>, P<Expr>),
1566 /// Path to a definition, possibly containing lifetime or type parameters.
1569 /// A referencing operation (i.e., `&a` or `&mut a`).
1570 AddrOf(Mutability, P<Expr>),
1571 /// A `break`, with an optional label to break.
1572 Break(Destination, Option<P<Expr>>),
1573 /// A `continue`, with an optional label.
1574 Continue(Destination),
1575 /// A `return`, with an optional value to be returned.
1576 Ret(Option<P<Expr>>),
1578 /// Inline assembly (from `asm!`), with its outputs and inputs.
1579 InlineAsm(P<InlineAsm>, HirVec<Expr>, HirVec<Expr>),
1581 /// A struct or struct-like variant literal expression.
1583 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1584 /// where `base` is the `Option<Expr>`.
1585 Struct(P<QPath>, HirVec<Field>, Option<P<Expr>>),
1587 /// An array literal constructed from one repeated element.
1589 /// E.g., `[1; 5]`. The first expression is the element
1590 /// to be repeated; the second is the number of times to repeat it.
1591 Repeat(P<Expr>, AnonConst),
1593 /// A suspension point for generators (i.e., `yield <expr>`).
1594 Yield(P<Expr>, YieldSource),
1596 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1600 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1601 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1603 /// Path to a definition, optionally "fully-qualified" with a `Self`
1604 /// type, if the path points to an associated item in a trait.
1606 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1607 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1608 /// even though they both have the same two-segment `Clone::clone` `Path`.
1609 Resolved(Option<P<Ty>>, P<Path>),
1611 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1612 /// Will be resolved by type-checking to an associated item.
1614 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1615 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1616 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1617 TypeRelative(P<Ty>, P<PathSegment>)
1620 /// Hints at the original code for a let statement.
1621 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1622 pub enum LocalSource {
1623 /// A `match _ { .. }`.
1625 /// A desugared `for _ in _ { .. }` loop.
1627 /// When lowering async functions, we create locals within the `async move` so that
1628 /// all arguments are dropped after the future is polled.
1630 /// ```ignore (pseudo-Rust)
1631 /// async fn foo(<pattern> @ x: Type) {
1633 /// let <pattern> = x;
1638 /// A desugared `<expr>.await`.
1642 /// Hints at the original code for a `match _ { .. }`.
1643 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
1644 pub enum MatchSource {
1645 /// A `match _ { .. }`.
1647 /// An `if _ { .. }` (optionally with `else { .. }`).
1649 contains_else_clause: bool,
1651 /// An `if let _ = _ { .. }` (optionally with `else { .. }`).
1653 contains_else_clause: bool,
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 let _ = _ { .. }` loop.
1673 /// A `for _ in _ { .. }` loop.
1677 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1678 pub enum LoopIdError {
1680 UnlabeledCfInWhileCondition,
1684 impl fmt::Display for LoopIdError {
1685 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1686 f.write_str(match self {
1687 LoopIdError::OutsideLoopScope => "not inside loop scope",
1688 LoopIdError::UnlabeledCfInWhileCondition =>
1689 "unlabeled control flow (break or continue) in while condition",
1690 LoopIdError::UnresolvedLabel => "label not found",
1695 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1696 pub struct Destination {
1697 // This is `Some(_)` iff there is an explicit user-specified `label
1698 pub label: Option<Label>,
1700 // These errors are caught and then reported during the diagnostics pass in
1701 // librustc_passes/loops.rs
1702 pub target_id: Result<HirId, LoopIdError>,
1705 /// Whether a generator contains self-references, causing it to be `!Unpin`.
1706 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, HashStable,
1707 RustcEncodable, RustcDecodable, Hash, Debug)]
1708 pub enum GeneratorMovability {
1709 /// May contain self-references, `!Unpin`.
1711 /// Must not contain self-references, `Unpin`.
1715 /// The yield kind that caused an `ExprKind::Yield`.
1716 #[derive(Copy, Clone, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable, HashStable)]
1717 pub enum YieldSource {
1718 /// An `<expr>.await`.
1720 /// A plain `yield`.
1724 impl fmt::Display for YieldSource {
1725 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1726 f.write_str(match self {
1727 YieldSource::Await => "`await`",
1728 YieldSource::Yield => "`yield`",
1733 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1734 pub enum CaptureClause {
1739 // N.B., if you change this, you'll probably want to change the corresponding
1740 // type structure in middle/ty.rs as well.
1741 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1744 pub mutbl: Mutability,
1747 /// Represents a method's signature in a trait declaration or implementation.
1748 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1749 pub struct MethodSig {
1750 pub header: FnHeader,
1751 pub decl: P<FnDecl>,
1754 // The bodies for items are stored "out of line", in a separate
1755 // hashmap in the `Crate`. Here we just record the node-id of the item
1756 // so it can fetched later.
1757 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1758 pub struct TraitItemId {
1762 /// Represents an item declaration within a trait declaration,
1763 /// possibly including a default implementation. A trait item is
1764 /// either required (meaning it doesn't have an implementation, just a
1765 /// signature) or provided (meaning it has a default implementation).
1766 #[derive(RustcEncodable, RustcDecodable, Debug)]
1767 pub struct TraitItem {
1770 pub attrs: HirVec<Attribute>,
1771 pub generics: Generics,
1772 pub node: TraitItemKind,
1776 /// Represents a trait method's body (or just argument names).
1777 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1778 pub enum TraitMethod {
1779 /// No default body in the trait, just a signature.
1780 Required(HirVec<Ident>),
1782 /// Both signature and body are provided in the trait.
1786 /// Represents a trait method or associated constant or type
1787 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1788 pub enum TraitItemKind {
1789 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
1790 Const(P<Ty>, Option<BodyId>),
1791 /// A method with an optional body.
1792 Method(MethodSig, TraitMethod),
1793 /// An associated type with (possibly empty) bounds and optional concrete
1795 Type(GenericBounds, Option<P<Ty>>),
1798 // The bodies for items are stored "out of line", in a separate
1799 // hashmap in the `Crate`. Here we just record the node-id of the item
1800 // so it can fetched later.
1801 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1802 pub struct ImplItemId {
1806 /// Represents anything within an `impl` block
1807 #[derive(RustcEncodable, RustcDecodable, Debug)]
1808 pub struct ImplItem {
1811 pub vis: Visibility,
1812 pub defaultness: Defaultness,
1813 pub attrs: HirVec<Attribute>,
1814 pub generics: Generics,
1815 pub node: ImplItemKind,
1819 /// Represents various kinds of content within an `impl`.
1820 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1821 pub enum ImplItemKind {
1822 /// An associated constant of the given type, set to the constant result
1823 /// of the expression
1824 Const(P<Ty>, BodyId),
1825 /// A method implementation with the given signature and body
1826 Method(MethodSig, BodyId),
1827 /// An associated type
1829 /// An associated existential type
1830 Existential(GenericBounds),
1833 /// Bind a type to an associated type (i.e., `A = Foo`).
1835 /// Bindings like `A: Debug` are represented as a special type `A =
1836 /// $::Debug` that is understood by the astconv code.
1838 /// FIXME(alexreg) -- why have a separate type for the binding case,
1839 /// wouldn't it be better to make the `ty` field an enum like:
1842 /// enum TypeBindingKind {
1847 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1848 pub struct TypeBinding {
1850 #[stable_hasher(project(name))]
1852 pub kind: TypeBindingKind,
1856 // Represents the two kinds of type bindings.
1857 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1858 pub enum TypeBindingKind {
1859 /// E.g., `Foo<Bar: Send>`.
1861 bounds: HirVec<GenericBound>,
1863 /// E.g., `Foo<Bar = ()>`.
1870 pub fn ty(&self) -> &Ty {
1872 TypeBindingKind::Equality { ref ty } => ty,
1873 _ => bug!("expected equality type binding for parenthesized generic args"),
1878 #[derive(RustcEncodable, RustcDecodable)]
1885 impl fmt::Debug for Ty {
1886 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1887 write!(f, "type({})",
1888 print::to_string(print::NO_ANN, |s| s.print_type(self)))
1892 /// Not represented directly in the AST; referred to by name through a `ty_path`.
1893 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
1903 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1904 pub struct BareFnTy {
1905 pub unsafety: Unsafety,
1907 pub generic_params: HirVec<GenericParam>,
1908 pub decl: P<FnDecl>,
1909 pub arg_names: HirVec<Ident>,
1912 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1913 pub struct ExistTy {
1914 pub generics: Generics,
1915 pub bounds: GenericBounds,
1916 pub impl_trait_fn: Option<DefId>,
1917 pub origin: ExistTyOrigin,
1920 /// Where the existential type came from
1921 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1922 pub enum ExistTyOrigin {
1923 /// `existential type Foo: Trait;`
1931 /// The various kinds of types recognized by the compiler.
1932 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1934 /// A variable length slice (i.e., `[T]`).
1936 /// A fixed length array (i.e., `[T; n]`).
1937 Array(P<Ty>, AnonConst),
1938 /// A raw pointer (i.e., `*const T` or `*mut T`).
1940 /// A reference (i.e., `&'a T` or `&'a mut T`).
1941 Rptr(Lifetime, MutTy),
1942 /// A bare function (e.g., `fn(usize) -> bool`).
1943 BareFn(P<BareFnTy>),
1944 /// The never type (`!`).
1946 /// A tuple (`(A, B, C, D, ...)`).
1948 /// A path to a type definition (`module::module::...::Type`), or an
1949 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
1951 /// Type parameters may be stored in each `PathSegment`.
1953 /// A type definition itself. This is currently only used for the `existential type`
1954 /// item that `impl Trait` in return position desugars to.
1956 /// The generic argument list contains the lifetimes (and in the future possibly parameters)
1957 /// that are actually bound on the `impl Trait`.
1958 Def(ItemId, HirVec<GenericArg>),
1959 /// A trait object type `Bound1 + Bound2 + Bound3`
1960 /// where `Bound` is a trait or a lifetime.
1961 TraitObject(HirVec<PolyTraitRef>, Lifetime),
1964 /// `TyKind::Infer` means the type should be inferred instead of it having been
1965 /// specified. This can appear anywhere in a type.
1967 /// Placeholder for a type that has failed to be defined.
1969 /// Placeholder for C-variadic arguments. We "spoof" the `VaListImpl` created
1970 /// from the variadic arguments. This type is only valid up to typeck.
1974 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1975 pub struct InlineAsmOutput {
1976 pub constraint: Symbol,
1978 pub is_indirect: bool,
1982 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1983 pub struct InlineAsm {
1985 pub asm_str_style: StrStyle,
1986 pub outputs: HirVec<InlineAsmOutput>,
1987 pub inputs: HirVec<Symbol>,
1988 pub clobbers: HirVec<Symbol>,
1990 pub alignstack: bool,
1991 pub dialect: AsmDialect,
1992 #[stable_hasher(ignore)] // This is used for error reporting
1993 pub ctxt: SyntaxContext,
1996 /// Represents an argument in a function header.
1997 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2003 /// Represents the header (not the body) of a function declaration.
2004 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2006 /// The types of the function's arguments.
2008 /// Additional argument data is stored in the function's [body](Body::arguments).
2009 pub inputs: HirVec<Ty>,
2010 pub output: FunctionRetTy,
2011 pub c_variadic: bool,
2012 /// Does the function have an implicit self?
2013 pub implicit_self: ImplicitSelfKind,
2016 /// Represents what type of implicit self a function has, if any.
2017 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2018 pub enum ImplicitSelfKind {
2019 /// Represents a `fn x(self);`.
2021 /// Represents a `fn x(mut self);`.
2023 /// Represents a `fn x(&self);`.
2025 /// Represents a `fn x(&mut self);`.
2027 /// Represents when a function does not have a self argument or
2028 /// when a function has a `self: X` argument.
2032 impl ImplicitSelfKind {
2033 /// Does this represent an implicit self?
2034 pub fn has_implicit_self(&self) -> bool {
2036 ImplicitSelfKind::None => false,
2042 /// Is the trait definition an auto trait?
2043 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2049 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, HashStable,
2050 Ord, RustcEncodable, RustcDecodable, Debug)]
2056 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, HashStable,
2057 RustcEncodable, RustcDecodable, Hash, Debug)]
2063 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2064 pub enum Constness {
2069 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2070 pub enum Defaultness {
2071 Default { has_value: bool },
2076 pub fn has_value(&self) -> bool {
2078 Defaultness::Default { has_value, .. } => has_value,
2079 Defaultness::Final => true,
2083 pub fn is_final(&self) -> bool {
2084 *self == Defaultness::Final
2087 pub fn is_default(&self) -> bool {
2089 Defaultness::Default { .. } => true,
2095 impl fmt::Display for Unsafety {
2096 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2097 f.write_str(match self {
2098 Unsafety::Normal => "normal",
2099 Unsafety::Unsafe => "unsafe",
2104 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2105 pub enum ImplPolarity {
2106 /// `impl Trait for Type`
2108 /// `impl !Trait for Type`
2112 impl fmt::Debug for ImplPolarity {
2113 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2114 f.write_str(match self {
2115 ImplPolarity::Positive => "positive",
2116 ImplPolarity::Negative => "negative",
2122 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2123 pub enum FunctionRetTy {
2124 /// Return type is not specified.
2126 /// Functions default to `()` and
2127 /// closures default to inference. Span points to where return
2128 /// type would be inserted.
2129 DefaultReturn(Span),
2130 /// Everything else.
2134 impl fmt::Display for FunctionRetTy {
2135 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2137 Return(ref ty) => print::to_string(print::NO_ANN, |s| s.print_type(ty)).fmt(f),
2138 DefaultReturn(_) => "()".fmt(f),
2143 impl FunctionRetTy {
2144 pub fn span(&self) -> Span {
2146 DefaultReturn(span) => span,
2147 Return(ref ty) => ty.span,
2152 #[derive(RustcEncodable, RustcDecodable, Debug)]
2154 /// A span from the first token past `{` to the last token until `}`.
2155 /// For `mod foo;`, the inner span ranges from the first token
2156 /// to the last token in the external file.
2158 pub item_ids: HirVec<ItemId>,
2161 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2162 pub struct ForeignMod {
2164 pub items: HirVec<ForeignItem>,
2167 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2168 pub struct GlobalAsm {
2170 #[stable_hasher(ignore)] // This is used for error reporting
2171 pub ctxt: SyntaxContext,
2174 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2175 pub struct EnumDef {
2176 pub variants: HirVec<Variant>,
2179 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2180 pub struct VariantKind {
2181 /// Name of the variant.
2182 #[stable_hasher(project(name))]
2184 /// Attributes of the variant.
2185 pub attrs: HirVec<Attribute>,
2186 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2188 /// Fields and constructor id of the variant.
2189 pub data: VariantData,
2190 /// Explicit discriminant (e.g., `Foo = 1`).
2191 pub disr_expr: Option<AnonConst>,
2194 pub type Variant = Spanned<VariantKind>;
2196 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2198 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2199 /// Also produced for each element of a list `use`, e.g.
2200 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2203 /// Glob import, e.g., `use foo::*`.
2206 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2207 /// an additional `use foo::{}` for performing checks such as
2208 /// unstable feature gating. May be removed in the future.
2212 /// References to traits in impls.
2214 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2215 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2216 /// trait being referred to but just a unique `HirId` that serves as a key
2217 /// within the resolution map.
2218 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2219 pub struct TraitRef {
2221 // Don't hash the ref_id. It is tracked via the thing it is used to access
2222 #[stable_hasher(ignore)]
2223 pub hir_ref_id: HirId,
2227 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2228 pub fn trait_def_id(&self) -> DefId {
2229 match self.path.res {
2230 Res::Def(DefKind::Trait, did) => did,
2231 Res::Def(DefKind::TraitAlias, did) => did,
2235 _ => unreachable!(),
2240 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2241 pub struct PolyTraitRef {
2242 /// The `'a` in `<'a> Foo<&'a T>`.
2243 pub bound_generic_params: HirVec<GenericParam>,
2245 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2246 pub trait_ref: TraitRef,
2251 pub type Visibility = Spanned<VisibilityKind>;
2253 #[derive(RustcEncodable, RustcDecodable, Debug)]
2254 pub enum VisibilityKind {
2257 Restricted { path: P<Path>, hir_id: HirId },
2261 impl VisibilityKind {
2262 pub fn is_pub(&self) -> bool {
2264 VisibilityKind::Public => true,
2269 pub fn is_pub_restricted(&self) -> bool {
2271 VisibilityKind::Public |
2272 VisibilityKind::Inherited => false,
2273 VisibilityKind::Crate(..) |
2274 VisibilityKind::Restricted { .. } => true,
2278 pub fn descr(&self) -> &'static str {
2280 VisibilityKind::Public => "public",
2281 VisibilityKind::Inherited => "private",
2282 VisibilityKind::Crate(..) => "crate-visible",
2283 VisibilityKind::Restricted { .. } => "restricted",
2288 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2289 pub struct StructField {
2291 #[stable_hasher(project(name))]
2293 pub vis: Visibility,
2296 pub attrs: HirVec<Attribute>,
2300 // Still necessary in couple of places
2301 pub fn is_positional(&self) -> bool {
2302 let first = self.ident.as_str().as_bytes()[0];
2303 first >= b'0' && first <= b'9'
2307 /// Fields and constructor IDs of enum variants and structs.
2308 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2309 pub enum VariantData {
2310 /// A struct variant.
2312 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2313 Struct(HirVec<StructField>, /* recovered */ bool),
2314 /// A tuple variant.
2316 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2317 Tuple(HirVec<StructField>, HirId),
2320 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2325 /// Return the fields of this variant.
2326 pub fn fields(&self) -> &[StructField] {
2328 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2333 /// Return the `HirId` of this variant's constructor, if it has one.
2334 pub fn ctor_hir_id(&self) -> Option<HirId> {
2336 VariantData::Struct(_, _) => None,
2337 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2342 // The bodies for items are stored "out of line", in a separate
2343 // hashmap in the `Crate`. Here we just record the node-id of the item
2344 // so it can fetched later.
2345 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2352 /// The name might be a dummy name in case of anonymous items
2353 #[derive(RustcEncodable, RustcDecodable, Debug)]
2357 pub attrs: HirVec<Attribute>,
2359 pub vis: Visibility,
2363 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2364 pub struct FnHeader {
2365 pub unsafety: Unsafety,
2366 pub constness: Constness,
2367 pub asyncness: IsAsync,
2372 pub fn is_const(&self) -> bool {
2373 match &self.constness {
2374 Constness::Const => true,
2380 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2382 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2384 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2385 ExternCrate(Option<Name>),
2387 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2391 /// `use foo::bar::baz;` (with `as baz` implicitly on the right)
2392 Use(P<Path>, UseKind),
2395 Static(P<Ty>, Mutability, BodyId),
2397 Const(P<Ty>, BodyId),
2398 /// A function declaration
2399 Fn(P<FnDecl>, FnHeader, Generics, BodyId),
2402 /// An external module
2403 ForeignMod(ForeignMod),
2404 /// Module-level inline assembly (from global_asm!)
2405 GlobalAsm(P<GlobalAsm>),
2406 /// A type alias, e.g., `type Foo = Bar<u8>`
2407 Ty(P<Ty>, Generics),
2408 /// An existential type definition, e.g., `existential type Foo: Bar;`
2409 Existential(ExistTy),
2410 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`
2411 Enum(EnumDef, Generics),
2412 /// A struct definition, e.g., `struct Foo<A> {x: A}`
2413 Struct(VariantData, Generics),
2414 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`
2415 Union(VariantData, Generics),
2416 /// Represents a Trait Declaration
2417 Trait(IsAuto, Unsafety, Generics, GenericBounds, HirVec<TraitItemRef>),
2418 /// Represents a Trait Alias Declaration
2419 TraitAlias(Generics, GenericBounds),
2421 /// An implementation, eg `impl<A> Trait for Foo { .. }`
2426 Option<TraitRef>, // (optional) trait this impl implements
2428 HirVec<ImplItemRef>),
2432 pub fn descriptive_variant(&self) -> &str {
2434 ItemKind::ExternCrate(..) => "extern crate",
2435 ItemKind::Use(..) => "use",
2436 ItemKind::Static(..) => "static item",
2437 ItemKind::Const(..) => "constant item",
2438 ItemKind::Fn(..) => "function",
2439 ItemKind::Mod(..) => "module",
2440 ItemKind::ForeignMod(..) => "foreign module",
2441 ItemKind::GlobalAsm(..) => "global asm",
2442 ItemKind::Ty(..) => "type alias",
2443 ItemKind::Existential(..) => "existential type",
2444 ItemKind::Enum(..) => "enum",
2445 ItemKind::Struct(..) => "struct",
2446 ItemKind::Union(..) => "union",
2447 ItemKind::Trait(..) => "trait",
2448 ItemKind::TraitAlias(..) => "trait alias",
2449 ItemKind::Impl(..) => "impl",
2453 pub fn adt_kind(&self) -> Option<AdtKind> {
2455 ItemKind::Struct(..) => Some(AdtKind::Struct),
2456 ItemKind::Union(..) => Some(AdtKind::Union),
2457 ItemKind::Enum(..) => Some(AdtKind::Enum),
2462 pub fn generics(&self) -> Option<&Generics> {
2464 ItemKind::Fn(_, _, ref generics, _) |
2465 ItemKind::Ty(_, ref generics) |
2466 ItemKind::Existential(ExistTy { ref generics, impl_trait_fn: None, .. }) |
2467 ItemKind::Enum(_, ref generics) |
2468 ItemKind::Struct(_, ref generics) |
2469 ItemKind::Union(_, ref generics) |
2470 ItemKind::Trait(_, _, ref generics, _, _) |
2471 ItemKind::Impl(_, _, _, ref generics, _, _, _)=> generics,
2477 /// A reference from an trait to one of its associated items. This
2478 /// contains the item's id, naturally, but also the item's name and
2479 /// some other high-level details (like whether it is an associated
2480 /// type or method, and whether it is public). This allows other
2481 /// passes to find the impl they want without loading the ID (which
2482 /// means fewer edges in the incremental compilation graph).
2483 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2484 pub struct TraitItemRef {
2485 pub id: TraitItemId,
2486 #[stable_hasher(project(name))]
2488 pub kind: AssocItemKind,
2490 pub defaultness: Defaultness,
2493 /// A reference from an impl to one of its associated items. This
2494 /// contains the item's ID, naturally, but also the item's name and
2495 /// some other high-level details (like whether it is an associated
2496 /// type or method, and whether it is public). This allows other
2497 /// passes to find the impl they want without loading the ID (which
2498 /// means fewer edges in the incremental compilation graph).
2499 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2500 pub struct ImplItemRef {
2502 #[stable_hasher(project(name))]
2504 pub kind: AssocItemKind,
2506 pub vis: Visibility,
2507 pub defaultness: Defaultness,
2510 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2511 pub enum AssocItemKind {
2513 Method { has_self: bool },
2518 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2519 pub struct ForeignItem {
2520 #[stable_hasher(project(name))]
2522 pub attrs: HirVec<Attribute>,
2523 pub node: ForeignItemKind,
2526 pub vis: Visibility,
2529 /// An item within an `extern` block.
2530 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2531 pub enum ForeignItemKind {
2532 /// A foreign function.
2533 Fn(P<FnDecl>, HirVec<Ident>, Generics),
2534 /// A foreign static item (`static ext: u8`).
2535 Static(P<Ty>, Mutability),
2540 impl ForeignItemKind {
2541 pub fn descriptive_variant(&self) -> &str {
2543 ForeignItemKind::Fn(..) => "foreign function",
2544 ForeignItemKind::Static(..) => "foreign static item",
2545 ForeignItemKind::Type => "foreign type",
2550 /// A variable captured by a closure.
2551 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable, HashStable)]
2553 // First span where it is accessed (there can be multiple).
2557 pub type CaptureModeMap = NodeMap<CaptureClause>;
2559 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2560 // has length > 0 if the trait is found through an chain of imports, starting with the
2561 // import/use statement in the scope where the trait is used.
2562 #[derive(Clone, Debug)]
2563 pub struct TraitCandidate {
2565 pub import_ids: SmallVec<[NodeId; 1]>,
2568 // Trait method resolution
2569 pub type TraitMap = NodeMap<Vec<TraitCandidate>>;
2571 // Map from the NodeId of a glob import to a list of items which are actually
2573 pub type GlobMap = NodeMap<FxHashSet<Name>>;
2575 pub fn provide(providers: &mut Providers<'_>) {
2576 check_attr::provide(providers);
2577 map::provide(providers);
2578 upvars::provide(providers);
2581 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
2582 pub struct CodegenFnAttrs {
2583 pub flags: CodegenFnAttrFlags,
2584 /// Parsed representation of the `#[inline]` attribute
2585 pub inline: InlineAttr,
2586 /// Parsed representation of the `#[optimize]` attribute
2587 pub optimize: OptimizeAttr,
2588 /// The `#[export_name = "..."]` attribute, indicating a custom symbol a
2589 /// function should be exported under
2590 pub export_name: Option<Symbol>,
2591 /// The `#[link_name = "..."]` attribute, indicating a custom symbol an
2592 /// imported function should be imported as. Note that `export_name`
2593 /// probably isn't set when this is set, this is for foreign items while
2594 /// `#[export_name]` is for Rust-defined functions.
2595 pub link_name: Option<Symbol>,
2596 /// The `#[target_feature(enable = "...")]` attribute and the enabled
2597 /// features (only enabled features are supported right now).
2598 pub target_features: Vec<Symbol>,
2599 /// The `#[linkage = "..."]` attribute and the value we found.
2600 pub linkage: Option<Linkage>,
2601 /// The `#[link_section = "..."]` attribute, or what executable section this
2602 /// should be placed in.
2603 pub link_section: Option<Symbol>,
2607 #[derive(RustcEncodable, RustcDecodable, HashStable)]
2608 pub struct CodegenFnAttrFlags: u32 {
2609 /// `#[cold]`: a hint to LLVM that this function, when called, is never on
2611 const COLD = 1 << 0;
2612 /// `#[rustc_allocator]`: a hint to LLVM that the pointer returned from this
2613 /// function is never null.
2614 const ALLOCATOR = 1 << 1;
2615 /// `#[unwind]`: an indicator that this function may unwind despite what
2616 /// its ABI signature may otherwise imply.
2617 const UNWIND = 1 << 2;
2618 /// `#[rust_allocator_nounwind]`, an indicator that an imported FFI
2619 /// function will never unwind. Probably obsolete by recent changes with
2620 /// #[unwind], but hasn't been removed/migrated yet
2621 const RUSTC_ALLOCATOR_NOUNWIND = 1 << 3;
2622 /// `#[naked]`: an indicator to LLVM that no function prologue/epilogue
2623 /// should be generated.
2624 const NAKED = 1 << 4;
2625 /// `#[no_mangle]`: an indicator that the function's name should be the same
2627 const NO_MANGLE = 1 << 5;
2628 /// `#[rustc_std_internal_symbol]`: an indicator that this symbol is a
2629 /// "weird symbol" for the standard library in that it has slightly
2630 /// different linkage, visibility, and reachability rules.
2631 const RUSTC_STD_INTERNAL_SYMBOL = 1 << 6;
2632 /// `#[no_debug]`: an indicator that no debugging information should be
2633 /// generated for this function by LLVM.
2634 const NO_DEBUG = 1 << 7;
2635 /// `#[thread_local]`: indicates a static is actually a thread local
2637 const THREAD_LOCAL = 1 << 8;
2638 /// `#[used]`: indicates that LLVM can't eliminate this function (but the
2640 const USED = 1 << 9;
2641 /// #[ffi_returns_twice], indicates that an extern function can return
2643 const FFI_RETURNS_TWICE = 1 << 10;
2647 impl CodegenFnAttrs {
2648 pub fn new() -> CodegenFnAttrs {
2650 flags: CodegenFnAttrFlags::empty(),
2651 inline: InlineAttr::None,
2652 optimize: OptimizeAttr::None,
2655 target_features: vec![],
2661 /// Returns `true` if `#[inline]` or `#[inline(always)]` is present.
2662 pub fn requests_inline(&self) -> bool {
2664 InlineAttr::Hint | InlineAttr::Always => true,
2665 InlineAttr::None | InlineAttr::Never => false,
2669 /// Returns `true` if it looks like this symbol needs to be exported, for example:
2671 /// * `#[no_mangle]` is present
2672 /// * `#[export_name(...)]` is present
2673 /// * `#[linkage]` is present
2674 pub fn contains_extern_indicator(&self) -> bool {
2675 self.flags.contains(CodegenFnAttrFlags::NO_MANGLE) ||
2676 self.export_name.is_some() ||
2677 match self.linkage {
2678 // These are private, so make sure we don't try to consider
2681 Some(Linkage::Internal) |
2682 Some(Linkage::Private) => false,
2688 #[derive(Copy, Clone, Debug)]
2689 pub enum Node<'hir> {
2691 ForeignItem(&'hir ForeignItem),
2692 TraitItem(&'hir TraitItem),
2693 ImplItem(&'hir ImplItem),
2694 Variant(&'hir Variant),
2695 Field(&'hir StructField),
2696 AnonConst(&'hir AnonConst),
2699 PathSegment(&'hir PathSegment),
2701 TraitRef(&'hir TraitRef),
2707 MacroDef(&'hir MacroDef),
2709 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
2710 /// with synthesized constructors.
2711 Ctor(&'hir VariantData),
2713 Lifetime(&'hir Lifetime),
2714 GenericParam(&'hir GenericParam),
2715 Visibility(&'hir Visibility),