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};
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, keywords};
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;
67 /// Uniquely identifies a node in the HIR of the current crate. It is
68 /// composed of the `owner`, which is the `DefIndex` of the directly enclosing
69 /// `hir::Item`, `hir::TraitItem`, or `hir::ImplItem` (i.e., the closest "item-like"),
70 /// and the `local_id` which is unique within the given owner.
72 /// This two-level structure makes for more stable values: One can move an item
73 /// around within the source code, or add or remove stuff before it, without
74 /// the `local_id` part of the `HirId` changing, which is a very useful property in
75 /// incremental compilation where we have to persist things through changes to
77 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)]
80 pub local_id: ItemLocalId,
84 pub fn owner_def_id(self) -> DefId {
85 DefId::local(self.owner)
88 pub fn owner_local_def_id(self) -> LocalDefId {
89 LocalDefId::from_def_id(DefId::local(self.owner))
93 impl serialize::UseSpecializedEncodable for HirId {
94 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
105 impl serialize::UseSpecializedDecodable for HirId {
106 fn default_decode<D: Decoder>(d: &mut D) -> Result<HirId, D::Error> {
107 let owner = DefIndex::decode(d)?;
108 let local_id = ItemLocalId::decode(d)?;
117 impl fmt::Display for HirId {
118 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
119 write!(f, "{:?}", self)
123 // hack to ensure that we don't try to access the private parts of `ItemLocalId` in this module
124 mod item_local_id_inner {
125 use rustc_data_structures::indexed_vec::Idx;
126 use rustc_macros::HashStable;
128 /// An `ItemLocalId` uniquely identifies something within a given "item-like",
129 /// that is, within a hir::Item, hir::TraitItem, or hir::ImplItem. There is no
130 /// guarantee that the numerical value of a given `ItemLocalId` corresponds to
131 /// the node's position within the owning item in any way, but there is a
132 /// guarantee that the `LocalItemId`s within an owner occupy a dense range of
133 /// integers starting at zero, so a mapping that maps all or most nodes within
134 /// an "item-like" to something else can be implemented by a `Vec` instead of a
135 /// tree or hash map.
136 pub struct ItemLocalId {
142 pub use self::item_local_id_inner::ItemLocalId;
144 /// The `HirId` corresponding to `CRATE_NODE_ID` and `CRATE_DEF_INDEX`.
145 pub const CRATE_HIR_ID: HirId = HirId {
146 owner: CRATE_DEF_INDEX,
147 local_id: ItemLocalId::from_u32_const(0)
150 pub const DUMMY_HIR_ID: HirId = HirId {
151 owner: CRATE_DEF_INDEX,
152 local_id: DUMMY_ITEM_LOCAL_ID,
155 pub const DUMMY_ITEM_LOCAL_ID: ItemLocalId = ItemLocalId::MAX;
157 #[derive(Clone, RustcEncodable, RustcDecodable, Copy, HashStable)]
158 pub struct Lifetime {
162 /// Either "`'a`", referring to a named lifetime definition,
163 /// or "``" (i.e., `keywords::Invalid`), for elision placeholders.
165 /// HIR lowering inserts these placeholders in type paths that
166 /// refer to type definitions needing lifetime parameters,
167 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
168 pub name: LifetimeName,
171 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy, HashStable)]
173 /// Some user-given name like `T` or `'x`.
176 /// Synthetic name generated when user elided a lifetime in an impl header.
178 /// E.g., the lifetimes in cases like these:
180 /// impl Foo for &u32
181 /// impl Foo<'_> for u32
183 /// in that case, we rewrite to
185 /// impl<'f> Foo for &'f u32
186 /// impl<'f> Foo<'f> for u32
188 /// where `'f` is something like `Fresh(0)`. The indices are
189 /// unique per impl, but not necessarily continuous.
192 /// Indicates an illegal name was given and an error has been
193 /// repored (so we should squelch other derived errors). Occurs
194 /// when, e.g., `'_` is used in the wrong place.
199 pub fn ident(&self) -> Ident {
201 ParamName::Plain(ident) => ident,
202 ParamName::Error | ParamName::Fresh(_) => keywords::UnderscoreLifetime.ident(),
206 pub fn modern(&self) -> ParamName {
208 ParamName::Plain(ident) => ParamName::Plain(ident.modern()),
209 param_name => param_name,
214 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy, HashStable)]
215 pub enum LifetimeName {
216 /// User-given names or fresh (synthetic) names.
219 /// User wrote nothing (e.g., the lifetime in `&u32`).
222 /// Indicates an error during lowering (usually `'_` in wrong place)
223 /// that was already reported.
226 /// User wrote specifies `'_`.
229 /// User wrote `'static`.
234 pub fn ident(&self) -> Ident {
236 LifetimeName::Implicit => keywords::Invalid.ident(),
237 LifetimeName::Error => keywords::Invalid.ident(),
238 LifetimeName::Underscore => keywords::UnderscoreLifetime.ident(),
239 LifetimeName::Static => keywords::StaticLifetime.ident(),
240 LifetimeName::Param(param_name) => param_name.ident(),
244 pub fn is_elided(&self) -> bool {
246 LifetimeName::Implicit | LifetimeName::Underscore => true,
248 // It might seem surprising that `Fresh(_)` counts as
249 // *not* elided -- but this is because, as far as the code
250 // in the compiler is concerned -- `Fresh(_)` variants act
251 // equivalently to "some fresh name". They correspond to
252 // early-bound regions on an impl, in other words.
253 LifetimeName::Error | LifetimeName::Param(_) | LifetimeName::Static => false,
257 fn is_static(&self) -> bool {
258 self == &LifetimeName::Static
261 pub fn modern(&self) -> LifetimeName {
263 LifetimeName::Param(param_name) => LifetimeName::Param(param_name.modern()),
264 lifetime_name => lifetime_name,
269 impl fmt::Display for Lifetime {
270 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
271 self.name.ident().fmt(f)
275 impl fmt::Debug for Lifetime {
276 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
280 print::to_string(print::NO_ANN, |s| s.print_lifetime(self)))
285 pub fn is_elided(&self) -> bool {
286 self.name.is_elided()
289 pub fn is_static(&self) -> bool {
290 self.name.is_static()
294 /// A `Path` is essentially Rust's notion of a name; for instance,
295 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
296 /// along with a bunch of supporting information.
297 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
300 /// The resolution for the path.
302 /// The segments in the path: the things separated by `::`.
303 pub segments: HirVec<PathSegment>,
307 pub fn is_global(&self) -> bool {
308 !self.segments.is_empty() && self.segments[0].ident.name == keywords::PathRoot.name()
312 impl fmt::Debug for Path {
313 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
314 write!(f, "path({})", self)
318 impl fmt::Display for Path {
319 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
320 write!(f, "{}", print::to_string(print::NO_ANN, |s| s.print_path(self, false)))
324 /// A segment of a path: an identifier, an optional lifetime, and a set of
326 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
327 pub struct PathSegment {
328 /// The identifier portion of this path segment.
329 #[stable_hasher(project(name))]
331 // `id` and `res` are optional. We currently only use these in save-analysis,
332 // any path segments without these will not have save-analysis info and
333 // therefore will not have 'jump to def' in IDEs, but otherwise will not be
334 // affected. (In general, we don't bother to get the defs for synthesized
335 // segments, only for segments which have come from the AST).
336 pub hir_id: Option<HirId>,
337 pub res: Option<Res>,
339 /// Type/lifetime parameters attached to this path. They come in
340 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
341 /// this is more than just simple syntactic sugar; the use of
342 /// parens affects the region binding rules, so we preserve the
344 pub args: Option<P<GenericArgs>>,
346 /// Whether to infer remaining type parameters, if any.
347 /// This only applies to expression and pattern paths, and
348 /// out of those only the segments with no type parameters
349 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
350 pub infer_types: bool,
354 /// Converts an identifier to the corresponding segment.
355 pub fn from_ident(ident: Ident) -> PathSegment {
367 hir_id: Option<HirId>,
377 args: if args.is_empty() {
385 // FIXME: hack required because you can't create a static
386 // `GenericArgs`, so you can't just return a `&GenericArgs`.
387 pub fn with_generic_args<F, R>(&self, f: F) -> R
388 where F: FnOnce(&GenericArgs) -> R
390 let dummy = GenericArgs::none();
391 f(if let Some(ref args) = self.args {
399 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
400 pub struct ConstArg {
401 pub value: AnonConst,
405 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
406 pub enum GenericArg {
413 pub fn span(&self) -> Span {
415 GenericArg::Lifetime(l) => l.span,
416 GenericArg::Type(t) => t.span,
417 GenericArg::Const(c) => c.span,
421 pub fn id(&self) -> HirId {
423 GenericArg::Lifetime(l) => l.hir_id,
424 GenericArg::Type(t) => t.hir_id,
425 GenericArg::Const(c) => c.value.hir_id,
430 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
431 pub struct GenericArgs {
432 /// The generic arguments for this path segment.
433 pub args: HirVec<GenericArg>,
434 /// Bindings (equality constraints) on associated types, if present.
435 /// E.g., `Foo<A = Bar>`.
436 pub bindings: HirVec<TypeBinding>,
437 /// Were arguments written in parenthesized form `Fn(T) -> U`?
438 /// This is required mostly for pretty-printing and diagnostics,
439 /// but also for changing lifetime elision rules to be "function-like".
440 pub parenthesized: bool,
444 pub fn none() -> Self {
447 bindings: HirVec::new(),
448 parenthesized: false,
452 pub fn is_empty(&self) -> bool {
453 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
456 pub fn inputs(&self) -> &[Ty] {
457 if self.parenthesized {
458 for arg in &self.args {
460 GenericArg::Lifetime(_) => {}
461 GenericArg::Type(ref ty) => {
462 if let TyKind::Tup(ref tys) = ty.node {
467 GenericArg::Const(_) => {}
471 bug!("GenericArgs::inputs: not a `Fn(T) -> U`");
474 pub fn own_counts(&self) -> GenericParamCount {
475 // We could cache this as a property of `GenericParamCount`, but
476 // the aim is to refactor this away entirely eventually and the
477 // presence of this method will be a constant reminder.
478 let mut own_counts: GenericParamCount = Default::default();
480 for arg in &self.args {
482 GenericArg::Lifetime(_) => own_counts.lifetimes += 1,
483 GenericArg::Type(_) => own_counts.types += 1,
484 GenericArg::Const(_) => own_counts.consts += 1,
492 /// A modifier on a bound, currently this is only used for `?Sized`, where the
493 /// modifier is `Maybe`. Negative bounds should also be handled here.
494 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
495 pub enum TraitBoundModifier {
500 /// The AST represents all type param bounds as types.
501 /// `typeck::collect::compute_bounds` matches these against
502 /// the "special" built-in traits (see `middle::lang_items`) and
503 /// detects `Copy`, `Send` and `Sync`.
504 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
505 pub enum GenericBound {
506 Trait(PolyTraitRef, TraitBoundModifier),
511 pub fn span(&self) -> Span {
513 &GenericBound::Trait(ref t, ..) => t.span,
514 &GenericBound::Outlives(ref l) => l.span,
519 pub type GenericBounds = HirVec<GenericBound>;
521 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable)]
522 pub enum LifetimeParamKind {
523 // Indicates that the lifetime definition was explicitly declared (e.g., in
524 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
527 // Indicates that the lifetime definition was synthetically added
528 // as a result of an in-band lifetime usage (e.g., in
529 // `fn foo(x: &'a u8) -> &'a u8 { x }`).
532 // Indication that the lifetime was elided (e.g., in both cases in
533 // `fn foo(x: &u8) -> &'_ u8 { x }`).
536 // Indication that the lifetime name was somehow in error.
540 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
541 pub enum GenericParamKind {
542 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
544 kind: LifetimeParamKind,
547 default: Option<P<Ty>>,
548 synthetic: Option<SyntheticTyParamKind>,
555 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
556 pub struct GenericParam {
559 pub attrs: HirVec<Attribute>,
560 pub bounds: GenericBounds,
562 pub pure_wrt_drop: bool,
564 pub kind: GenericParamKind,
568 pub struct GenericParamCount {
569 pub lifetimes: usize,
574 /// Represents lifetimes and type parameters attached to a declaration
575 /// of a function, enum, trait, etc.
576 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
577 pub struct Generics {
578 pub params: HirVec<GenericParam>,
579 pub where_clause: WhereClause,
584 pub fn empty() -> Generics {
586 params: HirVec::new(),
587 where_clause: WhereClause {
588 hir_id: DUMMY_HIR_ID,
589 predicates: HirVec::new(),
595 pub fn own_counts(&self) -> GenericParamCount {
596 // We could cache this as a property of `GenericParamCount`, but
597 // the aim is to refactor this away entirely eventually and the
598 // presence of this method will be a constant reminder.
599 let mut own_counts: GenericParamCount = Default::default();
601 for param in &self.params {
603 GenericParamKind::Lifetime { .. } => own_counts.lifetimes += 1,
604 GenericParamKind::Type { .. } => own_counts.types += 1,
605 GenericParamKind::Const { .. } => own_counts.consts += 1,
612 pub fn get_named(&self, name: InternedString) -> Option<&GenericParam> {
613 for param in &self.params {
614 if name == param.name.ident().as_interned_str() {
622 /// Synthetic type parameters are converted to another form during lowering; this allows
623 /// us to track the original form they had, and is useful for error messages.
624 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
625 pub enum SyntheticTyParamKind {
629 /// A where-clause in a definition.
630 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
631 pub struct WhereClause {
633 pub predicates: HirVec<WherePredicate>,
637 pub fn span(&self) -> Option<Span> {
638 self.predicates.iter().map(|predicate| predicate.span())
639 .fold(None, |acc, i| match (acc, i) {
640 (None, i) => Some(i),
648 /// A single predicate in a where-clause.
649 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
650 pub enum WherePredicate {
651 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
652 BoundPredicate(WhereBoundPredicate),
653 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
654 RegionPredicate(WhereRegionPredicate),
655 /// An equality predicate (unsupported).
656 EqPredicate(WhereEqPredicate),
659 impl WherePredicate {
660 pub fn span(&self) -> Span {
662 &WherePredicate::BoundPredicate(ref p) => p.span,
663 &WherePredicate::RegionPredicate(ref p) => p.span,
664 &WherePredicate::EqPredicate(ref p) => p.span,
669 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
670 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
671 pub struct WhereBoundPredicate {
673 /// Any generics from a `for` binding.
674 pub bound_generic_params: HirVec<GenericParam>,
675 /// The type being bounded.
676 pub bounded_ty: P<Ty>,
677 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
678 pub bounds: GenericBounds,
681 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
682 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
683 pub struct WhereRegionPredicate {
685 pub lifetime: Lifetime,
686 pub bounds: GenericBounds,
689 /// An equality predicate (e.g., `T = int`); currently unsupported.
690 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
691 pub struct WhereEqPredicate {
698 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
699 pub struct ModuleItems {
700 // Use BTreeSets here so items are in the same order as in the
701 // list of all items in Crate
702 pub items: BTreeSet<HirId>,
703 pub trait_items: BTreeSet<TraitItemId>,
704 pub impl_items: BTreeSet<ImplItemId>,
707 /// The top-level data structure that stores the entire contents of
708 /// the crate currently being compiled.
710 /// For more details, see the [rustc guide].
712 /// [rustc guide]: https://rust-lang.github.io/rustc-guide/hir.html
713 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
716 pub attrs: HirVec<Attribute>,
718 pub exported_macros: HirVec<MacroDef>,
720 // N.B., we use a BTreeMap here so that `visit_all_items` iterates
721 // over the ids in increasing order. In principle it should not
722 // matter what order we visit things in, but in *practice* it
723 // does, because it can affect the order in which errors are
724 // detected, which in turn can make compile-fail tests yield
725 // slightly different results.
726 pub items: BTreeMap<HirId, Item>,
728 pub trait_items: BTreeMap<TraitItemId, TraitItem>,
729 pub impl_items: BTreeMap<ImplItemId, ImplItem>,
730 pub bodies: BTreeMap<BodyId, Body>,
731 pub trait_impls: BTreeMap<DefId, Vec<HirId>>,
733 /// A list of the body ids written out in the order in which they
734 /// appear in the crate. If you're going to process all the bodies
735 /// in the crate, you should iterate over this list rather than the keys
737 pub body_ids: Vec<BodyId>,
739 /// A list of modules written out in the order in which they
740 /// appear in the crate. This includes the main crate module.
741 pub modules: BTreeMap<NodeId, ModuleItems>,
745 pub fn item(&self, id: HirId) -> &Item {
749 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem {
750 &self.trait_items[&id]
753 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem {
754 &self.impl_items[&id]
757 /// Visits all items in the crate in some deterministic (but
758 /// unspecified) order. If you just need to process every item,
759 /// but don't care about nesting, this method is the best choice.
761 /// If you do care about nesting -- usually because your algorithm
762 /// follows lexical scoping rules -- then you want a different
763 /// approach. You should override `visit_nested_item` in your
764 /// visitor and then call `intravisit::walk_crate` instead.
765 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
766 where V: itemlikevisit::ItemLikeVisitor<'hir>
768 for (_, item) in &self.items {
769 visitor.visit_item(item);
772 for (_, trait_item) in &self.trait_items {
773 visitor.visit_trait_item(trait_item);
776 for (_, impl_item) in &self.impl_items {
777 visitor.visit_impl_item(impl_item);
781 /// A parallel version of `visit_all_item_likes`.
782 pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
783 where V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send
786 par_for_each_in(&self.items, |(_, item)| {
787 visitor.visit_item(item);
790 par_for_each_in(&self.trait_items, |(_, trait_item)| {
791 visitor.visit_trait_item(trait_item);
794 par_for_each_in(&self.impl_items, |(_, impl_item)| {
795 visitor.visit_impl_item(impl_item);
800 pub fn body(&self, id: BodyId) -> &Body {
805 /// A macro definition, in this crate or imported from another.
807 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
808 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
809 pub struct MacroDef {
812 pub attrs: HirVec<Attribute>,
815 pub body: TokenStream,
819 /// A block of statements `{ .. }`, which may have a label (in this case the
820 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
821 /// the `rules` being anything but `DefaultBlock`.
822 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
824 /// Statements in a block.
825 pub stmts: HirVec<Stmt>,
826 /// An expression at the end of the block
827 /// without a semicolon, if any.
828 pub expr: Option<P<Expr>>,
829 #[stable_hasher(ignore)]
831 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
832 pub rules: BlockCheckMode,
834 /// If true, then there may exist `break 'a` values that aim to
835 /// break out of this block early.
836 /// Used by `'label: {}` blocks and by `catch` statements.
837 pub targeted_by_break: bool,
840 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
842 #[stable_hasher(ignore)]
848 impl fmt::Debug for Pat {
849 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
850 write!(f, "pat({}: {})", self.hir_id,
851 print::to_string(print::NO_ANN, |s| s.print_pat(self)))
856 // FIXME(#19596) this is a workaround, but there should be a better way
857 fn walk_<G>(&self, it: &mut G) -> bool
858 where G: FnMut(&Pat) -> bool
865 PatKind::Binding(.., Some(ref p)) => p.walk_(it),
866 PatKind::Struct(_, ref fields, _) => {
867 fields.iter().all(|field| field.node.pat.walk_(it))
869 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
870 s.iter().all(|p| p.walk_(it))
872 PatKind::Box(ref s) | PatKind::Ref(ref s, _) => {
875 PatKind::Slice(ref before, ref slice, ref after) => {
879 .all(|p| p.walk_(it))
884 PatKind::Binding(..) |
885 PatKind::Path(_) => {
891 pub fn walk<F>(&self, mut it: F) -> bool
892 where F: FnMut(&Pat) -> bool
898 /// A single field in a struct pattern.
900 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
901 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
902 /// except `is_shorthand` is true.
903 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
904 pub struct FieldPat {
905 #[stable_hasher(ignore)]
907 /// The identifier for the field.
908 #[stable_hasher(project(name))]
910 /// The pattern the field is destructured to.
912 pub is_shorthand: bool,
915 /// Explicit binding annotations given in the HIR for a binding. Note
916 /// that this is not the final binding *mode* that we infer after type
918 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable)]
919 pub enum BindingAnnotation {
920 /// No binding annotation given: this means that the final binding mode
921 /// will depend on whether we have skipped through a `&` reference
922 /// when matching. For example, the `x` in `Some(x)` will have binding
923 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
924 /// ultimately be inferred to be by-reference.
926 /// Note that implicit reference skipping is not implemented yet (#42640).
929 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
932 /// Annotated as `ref`, like `ref x`
935 /// Annotated as `ref mut x`.
939 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
945 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
947 /// Represents a wildcard pattern (i.e., `_`).
950 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
951 /// The `HirId` is the canonical ID for the variable being bound,
952 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
953 /// which is the pattern ID of the first `x`.
954 Binding(BindingAnnotation, HirId, Ident, Option<P<Pat>>),
956 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
957 /// The `bool` is `true` in the presence of a `..`.
958 Struct(QPath, HirVec<Spanned<FieldPat>>, bool),
960 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
961 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
962 /// `0 <= position <= subpats.len()`
963 TupleStruct(QPath, HirVec<P<Pat>>, Option<usize>),
965 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
968 /// A tuple pattern (e.g., `(a, b)`).
969 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
970 /// `0 <= position <= subpats.len()`
971 Tuple(HirVec<P<Pat>>, Option<usize>),
976 /// A reference pattern (e.g., `&mut (a, b)`).
977 Ref(P<Pat>, Mutability),
982 /// A range pattern (e.g., `1...2` or `1..2`).
983 Range(P<Expr>, P<Expr>, RangeEnd),
985 /// `[a, b, ..i, y, z]` is represented as:
986 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`.
987 Slice(HirVec<P<Pat>>, Option<P<Pat>>, HirVec<P<Pat>>),
990 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, HashStable,
991 RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
992 pub enum Mutability {
998 /// Returns `MutMutable` only if both arguments are mutable.
999 pub fn and(self, other: Self) -> Self {
1001 MutMutable => other,
1002 MutImmutable => MutImmutable,
1007 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, Hash, HashStable)]
1008 pub enum BinOpKind {
1009 /// The `+` operator (addition).
1011 /// The `-` operator (subtraction).
1013 /// The `*` operator (multiplication).
1015 /// The `/` operator (division).
1017 /// The `%` operator (modulus).
1019 /// The `&&` operator (logical and).
1021 /// The `||` operator (logical or).
1023 /// The `^` operator (bitwise xor).
1025 /// The `&` operator (bitwise and).
1027 /// The `|` operator (bitwise or).
1029 /// The `<<` operator (shift left).
1031 /// The `>>` operator (shift right).
1033 /// The `==` operator (equality).
1035 /// The `<` operator (less than).
1037 /// The `<=` operator (less than or equal to).
1039 /// The `!=` operator (not equal to).
1041 /// The `>=` operator (greater than or equal to).
1043 /// The `>` operator (greater than).
1048 pub fn as_str(self) -> &'static str {
1050 BinOpKind::Add => "+",
1051 BinOpKind::Sub => "-",
1052 BinOpKind::Mul => "*",
1053 BinOpKind::Div => "/",
1054 BinOpKind::Rem => "%",
1055 BinOpKind::And => "&&",
1056 BinOpKind::Or => "||",
1057 BinOpKind::BitXor => "^",
1058 BinOpKind::BitAnd => "&",
1059 BinOpKind::BitOr => "|",
1060 BinOpKind::Shl => "<<",
1061 BinOpKind::Shr => ">>",
1062 BinOpKind::Eq => "==",
1063 BinOpKind::Lt => "<",
1064 BinOpKind::Le => "<=",
1065 BinOpKind::Ne => "!=",
1066 BinOpKind::Ge => ">=",
1067 BinOpKind::Gt => ">",
1071 pub fn is_lazy(self) -> bool {
1073 BinOpKind::And | BinOpKind::Or => true,
1078 pub fn is_shift(self) -> bool {
1080 BinOpKind::Shl | BinOpKind::Shr => true,
1085 pub fn is_comparison(self) -> bool {
1092 BinOpKind::Ge => true,
1104 BinOpKind::Shr => false,
1108 /// Returns `true` if the binary operator takes its arguments by value.
1109 pub fn is_by_value(self) -> bool {
1110 !self.is_comparison()
1114 impl Into<ast::BinOpKind> for BinOpKind {
1115 fn into(self) -> ast::BinOpKind {
1117 BinOpKind::Add => ast::BinOpKind::Add,
1118 BinOpKind::Sub => ast::BinOpKind::Sub,
1119 BinOpKind::Mul => ast::BinOpKind::Mul,
1120 BinOpKind::Div => ast::BinOpKind::Div,
1121 BinOpKind::Rem => ast::BinOpKind::Rem,
1122 BinOpKind::And => ast::BinOpKind::And,
1123 BinOpKind::Or => ast::BinOpKind::Or,
1124 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1125 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1126 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1127 BinOpKind::Shl => ast::BinOpKind::Shl,
1128 BinOpKind::Shr => ast::BinOpKind::Shr,
1129 BinOpKind::Eq => ast::BinOpKind::Eq,
1130 BinOpKind::Lt => ast::BinOpKind::Lt,
1131 BinOpKind::Le => ast::BinOpKind::Le,
1132 BinOpKind::Ne => ast::BinOpKind::Ne,
1133 BinOpKind::Ge => ast::BinOpKind::Ge,
1134 BinOpKind::Gt => ast::BinOpKind::Gt,
1139 pub type BinOp = Spanned<BinOpKind>;
1141 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, Hash, HashStable)]
1143 /// The `*` operator (deferencing).
1145 /// The `!` operator (logical negation).
1147 /// The `-` operator (negation).
1152 pub fn as_str(self) -> &'static str {
1160 /// Returns `true` if the unary operator takes its argument by value.
1161 pub fn is_by_value(self) -> bool {
1163 UnNeg | UnNot => true,
1170 #[derive(Clone, RustcEncodable, RustcDecodable)]
1177 impl fmt::Debug for Stmt {
1178 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1179 write!(f, "stmt({}: {})", self.hir_id,
1180 print::to_string(print::NO_ANN, |s| s.print_stmt(self)))
1184 /// The contents of a statement.
1185 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
1187 /// A local (`let`) binding.
1190 /// An item binding.
1193 /// An expression without a trailing semi-colon (must have unit type).
1196 /// An expression with a trailing semi-colon (may have any type).
1201 pub fn attrs(&self) -> &[Attribute] {
1203 StmtKind::Local(ref l) => &l.attrs,
1204 StmtKind::Item(_) => &[],
1205 StmtKind::Expr(ref e) |
1206 StmtKind::Semi(ref e) => &e.attrs,
1211 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1212 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1215 /// Type annotation, if any (otherwise the type will be inferred).
1216 pub ty: Option<P<Ty>>,
1217 /// Initializer expression to set the value, if any.
1218 pub init: Option<P<Expr>>,
1221 pub attrs: ThinVec<Attribute>,
1222 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1223 /// desugaring. Otherwise will be `Normal`.
1224 pub source: LocalSource,
1227 /// Represents a single arm of a `match` expression, e.g.
1228 /// `<pats> (if <guard>) => <body>`.
1229 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1231 pub attrs: HirVec<Attribute>,
1232 /// Multiple patterns can be combined with `|`
1233 pub pats: HirVec<P<Pat>>,
1234 /// Optional guard clause.
1235 pub guard: Option<Guard>,
1236 /// The expression the arm evaluates to if this arm matches.
1240 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1245 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1247 #[stable_hasher(ignore)]
1252 pub is_shorthand: bool,
1255 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable)]
1256 pub enum BlockCheckMode {
1258 UnsafeBlock(UnsafeSource),
1259 PushUnsafeBlock(UnsafeSource),
1260 PopUnsafeBlock(UnsafeSource),
1263 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable)]
1264 pub enum UnsafeSource {
1269 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1274 /// The body of a function, closure, or constant value. In the case of
1275 /// a function, the body contains not only the function body itself
1276 /// (which is an expression), but also the argument patterns, since
1277 /// those are something that the caller doesn't really care about.
1282 /// fn foo((x, y): (u32, u32)) -> u32 {
1287 /// Here, the `Body` associated with `foo()` would contain:
1289 /// - an `arguments` array containing the `(x, y)` pattern
1290 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1291 /// - `is_generator` would be false
1293 /// All bodies have an **owner**, which can be accessed via the HIR
1294 /// map using `body_owner_def_id()`.
1295 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1297 pub arguments: HirVec<Arg>,
1299 pub is_generator: bool,
1303 pub fn id(&self) -> BodyId {
1305 hir_id: self.value.hir_id,
1310 #[derive(Copy, Clone, Debug)]
1311 pub enum BodyOwnerKind {
1312 /// Functions and methods.
1318 /// Constants and associated constants.
1321 /// Initializer of a `static` item.
1325 impl BodyOwnerKind {
1326 pub fn is_fn_or_closure(self) -> bool {
1328 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1329 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1335 pub type Lit = Spanned<LitKind>;
1337 /// A constant (expression) that's not an item or associated item,
1338 /// but needs its own `DefId` for type-checking, const-eval, etc.
1339 /// These are usually found nested inside types (e.g., array lengths)
1340 /// or expressions (e.g., repeat counts), and also used to define
1341 /// explicit discriminant values for enum variants.
1342 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1343 pub struct AnonConst {
1349 #[derive(Clone, RustcEncodable, RustcDecodable)]
1353 pub attrs: ThinVec<Attribute>,
1357 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1358 #[cfg(target_arch = "x86_64")]
1359 static_assert_size!(Expr, 72);
1362 pub fn precedence(&self) -> ExprPrecedence {
1364 ExprKind::Box(_) => ExprPrecedence::Box,
1365 ExprKind::Array(_) => ExprPrecedence::Array,
1366 ExprKind::Call(..) => ExprPrecedence::Call,
1367 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1368 ExprKind::Tup(_) => ExprPrecedence::Tup,
1369 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1370 ExprKind::Unary(..) => ExprPrecedence::Unary,
1371 ExprKind::Lit(_) => ExprPrecedence::Lit,
1372 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1373 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1374 ExprKind::While(..) => ExprPrecedence::While,
1375 ExprKind::Loop(..) => ExprPrecedence::Loop,
1376 ExprKind::Match(..) => ExprPrecedence::Match,
1377 ExprKind::Closure(..) => ExprPrecedence::Closure,
1378 ExprKind::Block(..) => ExprPrecedence::Block,
1379 ExprKind::Assign(..) => ExprPrecedence::Assign,
1380 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1381 ExprKind::Field(..) => ExprPrecedence::Field,
1382 ExprKind::Index(..) => ExprPrecedence::Index,
1383 ExprKind::Path(..) => ExprPrecedence::Path,
1384 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1385 ExprKind::Break(..) => ExprPrecedence::Break,
1386 ExprKind::Continue(..) => ExprPrecedence::Continue,
1387 ExprKind::Ret(..) => ExprPrecedence::Ret,
1388 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1389 ExprKind::Struct(..) => ExprPrecedence::Struct,
1390 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1391 ExprKind::Yield(..) => ExprPrecedence::Yield,
1392 ExprKind::Err => ExprPrecedence::Err,
1396 pub fn is_place_expr(&self) -> bool {
1398 ExprKind::Path(QPath::Resolved(_, ref path)) => {
1402 | Res::Def(DefKind::Static, _)
1408 ExprKind::Type(ref e, _) => {
1412 ExprKind::Unary(UnDeref, _) |
1413 ExprKind::Field(..) |
1414 ExprKind::Index(..) => {
1418 // Partially qualified paths in expressions can only legally
1419 // refer to associated items which are always rvalues.
1420 ExprKind::Path(QPath::TypeRelative(..)) |
1422 ExprKind::Call(..) |
1423 ExprKind::MethodCall(..) |
1424 ExprKind::Struct(..) |
1426 ExprKind::Match(..) |
1427 ExprKind::Closure(..) |
1428 ExprKind::Block(..) |
1429 ExprKind::Repeat(..) |
1430 ExprKind::Array(..) |
1431 ExprKind::Break(..) |
1432 ExprKind::Continue(..) |
1434 ExprKind::While(..) |
1435 ExprKind::Loop(..) |
1436 ExprKind::Assign(..) |
1437 ExprKind::InlineAsm(..) |
1438 ExprKind::AssignOp(..) |
1440 ExprKind::Unary(..) |
1442 ExprKind::AddrOf(..) |
1443 ExprKind::Binary(..) |
1444 ExprKind::Yield(..) |
1445 ExprKind::Cast(..) |
1446 ExprKind::DropTemps(..) |
1454 impl fmt::Debug for Expr {
1455 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1456 write!(f, "expr({}: {})", self.hir_id,
1457 print::to_string(print::NO_ANN, |s| s.print_expr(self)))
1461 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1463 /// A `box x` expression.
1465 /// An array (e.g., `[a, b, c, d]`).
1466 Array(HirVec<Expr>),
1467 /// A function call.
1469 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1470 /// and the second field is the list of arguments.
1471 /// This also represents calling the constructor of
1472 /// tuple-like ADTs such as tuple structs and enum variants.
1473 Call(P<Expr>, HirVec<Expr>),
1474 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1476 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1477 /// (within the angle brackets).
1478 /// The first element of the vector of `Expr`s is the expression that evaluates
1479 /// to the object on which the method is being called on (the receiver),
1480 /// and the remaining elements are the rest of the arguments.
1481 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1482 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1483 MethodCall(P<PathSegment>, Span, HirVec<Expr>),
1484 /// A tuple (e.g., `(a, b, c ,d)`).
1486 /// A binary operation (e.g., `a + b`, `a * b`).
1487 Binary(BinOp, P<Expr>, P<Expr>),
1488 /// A unary operation (e.g., `!x`, `*x`).
1489 Unary(UnOp, P<Expr>),
1490 /// A literal (e.g., `1`, `"foo"`).
1492 /// A cast (e.g., `foo as f64`).
1493 Cast(P<Expr>, P<Ty>),
1494 /// A type reference (e.g., `Foo`).
1495 Type(P<Expr>, P<Ty>),
1496 /// Wraps the expression in a terminating scope.
1497 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1499 /// This construct only exists to tweak the drop order in HIR lowering.
1500 /// An example of that is the desugaring of `for` loops.
1502 /// A while loop, with an optional label
1504 /// I.e., `'label: while expr { <block> }`.
1505 While(P<Expr>, P<Block>, Option<Label>),
1506 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1508 /// I.e., `'label: loop { <block> }`.
1509 Loop(P<Block>, Option<Label>, LoopSource),
1510 /// A `match` block, with a source that indicates whether or not it is
1511 /// the result of a desugaring, and if so, which kind.
1512 Match(P<Expr>, HirVec<Arm>, MatchSource),
1513 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1515 /// The final span is the span of the argument block `|...|`.
1517 /// This may also be a generator literal, indicated by the final boolean,
1518 /// in that case there is an `GeneratorClause`.
1519 Closure(CaptureClause, P<FnDecl>, BodyId, Span, Option<GeneratorMovability>),
1520 /// A block (e.g., `'label: { ... }`).
1521 Block(P<Block>, Option<Label>),
1523 /// An assignment (e.g., `a = foo()`).
1524 Assign(P<Expr>, P<Expr>),
1525 /// An assignment with an operator.
1528 AssignOp(BinOp, P<Expr>, P<Expr>),
1529 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1530 Field(P<Expr>, Ident),
1531 /// An indexing operation (`foo[2]`).
1532 Index(P<Expr>, P<Expr>),
1534 /// Path to a definition, possibly containing lifetime or type parameters.
1537 /// A referencing operation (i.e., `&a` or `&mut a`).
1538 AddrOf(Mutability, P<Expr>),
1539 /// A `break`, with an optional label to break.
1540 Break(Destination, Option<P<Expr>>),
1541 /// A `continue`, with an optional label.
1542 Continue(Destination),
1543 /// A `return`, with an optional value to be returned.
1544 Ret(Option<P<Expr>>),
1546 /// Inline assembly (from `asm!`), with its outputs and inputs.
1547 InlineAsm(P<InlineAsm>, HirVec<Expr>, HirVec<Expr>),
1549 /// A struct or struct-like variant literal expression.
1551 /// For example, `Foo {x: 1, y: 2}`, or
1552 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
1553 Struct(P<QPath>, HirVec<Field>, Option<P<Expr>>),
1555 /// An array literal constructed from one repeated element.
1557 /// For example, `[1; 5]`. The first expression is the element
1558 /// to be repeated; the second is the number of times to repeat it.
1559 Repeat(P<Expr>, AnonConst),
1561 /// A suspension point for generators (i.e., `yield <expr>`).
1564 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1568 /// Optionally `Self`-qualified value/type path or associated extension.
1569 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1571 /// Path to a definition, optionally "fully-qualified" with a `Self`
1572 /// type, if the path points to an associated item in a trait.
1574 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1575 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1576 /// even though they both have the same two-segment `Clone::clone` `Path`.
1577 Resolved(Option<P<Ty>>, P<Path>),
1579 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1580 /// Will be resolved by type-checking to an associated item.
1582 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1583 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1584 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1585 TypeRelative(P<Ty>, P<PathSegment>)
1588 /// Hints at the original code for a let statement.
1589 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, HashStable)]
1590 pub enum LocalSource {
1591 /// A `match _ { .. }`.
1593 /// A desugared `for _ in _ { .. }` loop.
1595 /// When lowering async functions, we create locals within the `async move` so that
1596 /// all arguments are dropped after the future is polled.
1598 /// ```ignore (pseudo-Rust)
1599 /// async fn foo(<pattern> @ x: Type) {
1601 /// let <pattern> = x;
1606 /// A desugared `<expr>.await`.
1610 /// Hints at the original code for a `match _ { .. }`.
1611 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy, HashStable)]
1612 pub enum MatchSource {
1613 /// A `match _ { .. }`.
1615 /// An `if _ { .. }` (optionally with `else { .. }`).
1617 contains_else_clause: bool,
1619 /// An `if let _ = _ { .. }` (optionally with `else { .. }`).
1621 contains_else_clause: bool,
1623 /// A `while let _ = _ { .. }` (which was desugared to a
1624 /// `loop { match _ { .. } }`).
1626 /// A desugared `for _ in _ { .. }` loop.
1628 /// A desugared `?` operator.
1630 /// A desugared `<expr>.await`.
1634 /// The loop type that yielded an `ExprKind::Loop`.
1635 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable)]
1636 pub enum LoopSource {
1637 /// A `loop { .. }` loop.
1639 /// A `while let _ = _ { .. }` loop.
1641 /// A `for _ in _ { .. }` loop.
1645 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, HashStable)]
1646 pub enum LoopIdError {
1648 UnlabeledCfInWhileCondition,
1652 impl fmt::Display for LoopIdError {
1653 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1654 fmt::Display::fmt(match *self {
1655 LoopIdError::OutsideLoopScope => "not inside loop scope",
1656 LoopIdError::UnlabeledCfInWhileCondition =>
1657 "unlabeled control flow (break or continue) in while condition",
1658 LoopIdError::UnresolvedLabel => "label not found",
1663 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, HashStable)]
1664 pub struct Destination {
1665 // This is `Some(_)` iff there is an explicit user-specified `label
1666 pub label: Option<Label>,
1668 // These errors are caught and then reported during the diagnostics pass in
1669 // librustc_passes/loops.rs
1670 pub target_id: Result<HirId, LoopIdError>,
1673 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, HashStable,
1674 RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1675 pub enum GeneratorMovability {
1680 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, HashStable)]
1681 pub enum CaptureClause {
1686 // N.B., if you change this, you'll probably want to change the corresponding
1687 // type structure in middle/ty.rs as well.
1688 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1691 pub mutbl: Mutability,
1694 /// Represents a method's signature in a trait declaration or implementation.
1695 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1696 pub struct MethodSig {
1697 pub header: FnHeader,
1698 pub decl: P<FnDecl>,
1701 // The bodies for items are stored "out of line", in a separate
1702 // hashmap in the `Crate`. Here we just record the node-id of the item
1703 // so it can fetched later.
1704 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1705 pub struct TraitItemId {
1709 /// Represents an item declaration within a trait declaration,
1710 /// possibly including a default implementation. A trait item is
1711 /// either required (meaning it doesn't have an implementation, just a
1712 /// signature) or provided (meaning it has a default implementation).
1713 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1714 pub struct TraitItem {
1717 pub attrs: HirVec<Attribute>,
1718 pub generics: Generics,
1719 pub node: TraitItemKind,
1723 /// A trait method's body (or just argument names).
1724 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1725 pub enum TraitMethod {
1726 /// No default body in the trait, just a signature.
1727 Required(HirVec<Ident>),
1729 /// Both signature and body are provided in the trait.
1733 /// Represents a trait method or associated constant or type
1734 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1735 pub enum TraitItemKind {
1736 /// An associated constant with an optional value (otherwise `impl`s
1737 /// must contain a value)
1738 Const(P<Ty>, Option<BodyId>),
1739 /// A method with an optional body
1740 Method(MethodSig, TraitMethod),
1741 /// An associated type with (possibly empty) bounds and optional concrete
1743 Type(GenericBounds, Option<P<Ty>>),
1746 // The bodies for items are stored "out of line", in a separate
1747 // hashmap in the `Crate`. Here we just record the node-id of the item
1748 // so it can fetched later.
1749 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1750 pub struct ImplItemId {
1754 /// Represents anything within an `impl` block
1755 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1756 pub struct ImplItem {
1759 pub vis: Visibility,
1760 pub defaultness: Defaultness,
1761 pub attrs: HirVec<Attribute>,
1762 pub generics: Generics,
1763 pub node: ImplItemKind,
1767 /// Represents different contents within `impl`s
1768 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1769 pub enum ImplItemKind {
1770 /// An associated constant of the given type, set to the constant result
1771 /// of the expression
1772 Const(P<Ty>, BodyId),
1773 /// A method implementation with the given signature and body
1774 Method(MethodSig, BodyId),
1775 /// An associated type
1777 /// An associated existential type
1778 Existential(GenericBounds),
1781 // Bind a type to an associated type: `A=Foo`.
1782 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1783 pub struct TypeBinding {
1785 #[stable_hasher(project(name))]
1791 #[derive(Clone, RustcEncodable, RustcDecodable)]
1798 impl fmt::Debug for Ty {
1799 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1800 write!(f, "type({})",
1801 print::to_string(print::NO_ANN, |s| s.print_type(self)))
1805 /// Not represented directly in the AST; referred to by name through a `ty_path`.
1806 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy, HashStable)]
1816 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1817 pub struct BareFnTy {
1818 pub unsafety: Unsafety,
1820 pub generic_params: HirVec<GenericParam>,
1821 pub decl: P<FnDecl>,
1822 pub arg_names: HirVec<Ident>,
1825 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1826 pub struct ExistTy {
1827 pub generics: Generics,
1828 pub bounds: GenericBounds,
1829 pub impl_trait_fn: Option<DefId>,
1830 pub origin: ExistTyOrigin,
1833 /// Where the existential type came from
1834 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1835 pub enum ExistTyOrigin {
1836 /// `existential type Foo: Trait;`
1844 /// The various kinds of types recognized by the compiler.
1845 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1847 /// A variable length slice (i.e., `[T]`).
1849 /// A fixed length array (i.e., `[T; n]`).
1850 Array(P<Ty>, AnonConst),
1851 /// A raw pointer (i.e., `*const T` or `*mut T`).
1853 /// A reference (i.e., `&'a T` or `&'a mut T`).
1854 Rptr(Lifetime, MutTy),
1855 /// A bare function (e.g., `fn(usize) -> bool`).
1856 BareFn(P<BareFnTy>),
1857 /// The never type (`!`).
1859 /// A tuple (`(A, B, C, D,...)`).
1861 /// A path to a type definition (`module::module::...::Type`), or an
1862 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
1864 /// Type parameters may be stored in each `PathSegment`.
1866 /// A type definition itself. This is currently only used for the `existential type`
1867 /// item that `impl Trait` in return position desugars to.
1869 /// The generic argument list contains the lifetimes (and in the future possibly parameters)
1870 /// that are actually bound on the `impl Trait`.
1871 Def(ItemId, HirVec<GenericArg>),
1872 /// A trait object type `Bound1 + Bound2 + Bound3`
1873 /// where `Bound` is a trait or a lifetime.
1874 TraitObject(HirVec<PolyTraitRef>, Lifetime),
1877 /// `TyKind::Infer` means the type should be inferred instead of it having been
1878 /// specified. This can appear anywhere in a type.
1880 /// Placeholder for a type that has failed to be defined.
1882 /// Placeholder for C-variadic arguments. We "spoof" the `VaList` created
1883 /// from the variadic arguments. This type is only valid up to typeck.
1887 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1888 pub struct InlineAsmOutput {
1889 pub constraint: Symbol,
1891 pub is_indirect: bool,
1895 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1896 pub struct InlineAsm {
1898 pub asm_str_style: StrStyle,
1899 pub outputs: HirVec<InlineAsmOutput>,
1900 pub inputs: HirVec<Symbol>,
1901 pub clobbers: HirVec<Symbol>,
1903 pub alignstack: bool,
1904 pub dialect: AsmDialect,
1905 #[stable_hasher(ignore)] // This is used for error reporting
1906 pub ctxt: SyntaxContext,
1909 /// Represents an argument in a function header.
1910 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1914 pub source: ArgSource,
1918 /// Returns the pattern representing the original binding for this argument.
1919 pub fn original_pat(&self) -> &P<Pat> {
1920 match &self.source {
1921 ArgSource::Normal => &self.pat,
1922 ArgSource::AsyncFn(pat) => &pat,
1927 /// Represents the source of an argument in a function header.
1928 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1929 pub enum ArgSource {
1930 /// Argument as specified by the user.
1932 /// Generated argument from `async fn` lowering, contains the original binding pattern.
1936 /// Represents the header (not the body) of a function declaration.
1937 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1939 /// The types of the function's arguments.
1941 /// Additional argument data is stored in the function's [body](Body::arguments).
1942 pub inputs: HirVec<Ty>,
1943 pub output: FunctionRetTy,
1944 pub c_variadic: bool,
1945 /// Does the function have an implicit self?
1946 pub implicit_self: ImplicitSelfKind,
1949 /// Represents what type of implicit self a function has, if any.
1950 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, HashStable)]
1951 pub enum ImplicitSelfKind {
1952 /// Represents a `fn x(self);`.
1954 /// Represents a `fn x(mut self);`.
1956 /// Represents a `fn x(&self);`.
1958 /// Represents a `fn x(&mut self);`.
1960 /// Represents when a function does not have a self argument or
1961 /// when a function has a `self: X` argument.
1965 impl ImplicitSelfKind {
1966 /// Does this represent an implicit self?
1967 pub fn has_implicit_self(&self) -> bool {
1969 ImplicitSelfKind::None => false,
1975 /// Is the trait definition an auto trait?
1976 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1982 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, HashStable,
1983 Ord, RustcEncodable, RustcDecodable, Debug)]
1989 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, HashStable,
1990 RustcEncodable, RustcDecodable, Hash, Debug)]
1996 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1997 pub enum Constness {
2002 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2003 pub enum Defaultness {
2004 Default { has_value: bool },
2009 pub fn has_value(&self) -> bool {
2011 Defaultness::Default { has_value, .. } => has_value,
2012 Defaultness::Final => true,
2016 pub fn is_final(&self) -> bool {
2017 *self == Defaultness::Final
2020 pub fn is_default(&self) -> bool {
2022 Defaultness::Default { .. } => true,
2028 impl fmt::Display for Unsafety {
2029 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2030 fmt::Display::fmt(match *self {
2031 Unsafety::Normal => "normal",
2032 Unsafety::Unsafe => "unsafe",
2038 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2039 pub enum ImplPolarity {
2040 /// `impl Trait for Type`
2042 /// `impl !Trait for Type`
2046 impl fmt::Debug for ImplPolarity {
2047 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2049 ImplPolarity::Positive => "positive".fmt(f),
2050 ImplPolarity::Negative => "negative".fmt(f),
2056 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2057 pub enum FunctionRetTy {
2058 /// Return type is not specified.
2060 /// Functions default to `()` and
2061 /// closures default to inference. Span points to where return
2062 /// type would be inserted.
2063 DefaultReturn(Span),
2064 /// Everything else.
2068 impl fmt::Display for FunctionRetTy {
2069 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2071 Return(ref ty) => print::to_string(print::NO_ANN, |s| s.print_type(ty)).fmt(f),
2072 DefaultReturn(_) => "()".fmt(f),
2077 impl FunctionRetTy {
2078 pub fn span(&self) -> Span {
2080 DefaultReturn(span) => span,
2081 Return(ref ty) => ty.span,
2086 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2088 /// A span from the first token past `{` to the last token until `}`.
2089 /// For `mod foo;`, the inner span ranges from the first token
2090 /// to the last token in the external file.
2092 pub item_ids: HirVec<ItemId>,
2095 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2096 pub struct ForeignMod {
2098 pub items: HirVec<ForeignItem>,
2101 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2102 pub struct GlobalAsm {
2104 #[stable_hasher(ignore)] // This is used for error reporting
2105 pub ctxt: SyntaxContext,
2108 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2109 pub struct EnumDef {
2110 pub variants: HirVec<Variant>,
2113 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2114 pub struct VariantKind {
2115 /// Name of the variant.
2116 #[stable_hasher(project(name))]
2118 /// Attributes of the variant.
2119 pub attrs: HirVec<Attribute>,
2120 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2122 /// Fields and constructor id of the variant.
2123 pub data: VariantData,
2124 /// Explicit discriminant (e.g., `Foo = 1`).
2125 pub disr_expr: Option<AnonConst>,
2128 pub type Variant = Spanned<VariantKind>;
2130 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2132 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2133 /// Also produced for each element of a list `use`, e.g.
2134 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2137 /// Glob import, e.g., `use foo::*`.
2140 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2141 /// an additional `use foo::{}` for performing checks such as
2142 /// unstable feature gating. May be removed in the future.
2146 /// TraitRef's appear in impls.
2148 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
2149 /// that the ref_id is for. Note that ref_id's value is not the NodeId of the
2150 /// trait being referred to but just a unique NodeId that serves as a key
2151 /// within the resolution map.
2152 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2153 pub struct TraitRef {
2155 // Don't hash the ref_id. It is tracked via the thing it is used to access
2156 #[stable_hasher(ignore)]
2157 pub hir_ref_id: HirId,
2161 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2162 pub fn trait_def_id(&self) -> DefId {
2163 match self.path.res {
2164 Res::Def(DefKind::Trait, did) => did,
2165 Res::Def(DefKind::TraitAlias, did) => did,
2169 _ => unreachable!(),
2174 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2175 pub struct PolyTraitRef {
2176 /// The `'a` in `<'a> Foo<&'a T>`.
2177 pub bound_generic_params: HirVec<GenericParam>,
2179 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2180 pub trait_ref: TraitRef,
2185 pub type Visibility = Spanned<VisibilityKind>;
2187 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2188 pub enum VisibilityKind {
2191 Restricted { path: P<Path>, hir_id: HirId },
2195 impl VisibilityKind {
2196 pub fn is_pub(&self) -> bool {
2198 VisibilityKind::Public => true,
2203 pub fn is_pub_restricted(&self) -> bool {
2205 VisibilityKind::Public |
2206 VisibilityKind::Inherited => false,
2207 VisibilityKind::Crate(..) |
2208 VisibilityKind::Restricted { .. } => true,
2212 pub fn descr(&self) -> &'static str {
2214 VisibilityKind::Public => "public",
2215 VisibilityKind::Inherited => "private",
2216 VisibilityKind::Crate(..) => "crate-visible",
2217 VisibilityKind::Restricted { .. } => "restricted",
2222 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2223 pub struct StructField {
2225 #[stable_hasher(project(name))]
2227 pub vis: Visibility,
2230 pub attrs: HirVec<Attribute>,
2234 // Still necessary in couple of places
2235 pub fn is_positional(&self) -> bool {
2236 let first = self.ident.as_str().as_bytes()[0];
2237 first >= b'0' && first <= b'9'
2241 /// Fields and constructor ids of enum variants and structs
2242 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2243 pub enum VariantData {
2246 /// e.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2247 Struct(HirVec<StructField>, /* recovered */ bool),
2250 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2251 Tuple(HirVec<StructField>, HirId),
2254 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2259 /// Return the fields of this variant.
2260 pub fn fields(&self) -> &[StructField] {
2262 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2267 /// Return the `HirId` of this variant's constructor, if it has one.
2268 pub fn ctor_hir_id(&self) -> Option<HirId> {
2270 VariantData::Struct(_, _) => None,
2271 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2276 // The bodies for items are stored "out of line", in a separate
2277 // hashmap in the `Crate`. Here we just record the node-id of the item
2278 // so it can fetched later.
2279 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2286 /// The name might be a dummy name in case of anonymous items
2287 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2291 pub attrs: HirVec<Attribute>,
2293 pub vis: Visibility,
2297 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, HashStable)]
2298 pub struct FnHeader {
2299 pub unsafety: Unsafety,
2300 pub constness: Constness,
2301 pub asyncness: IsAsync,
2306 pub fn is_const(&self) -> bool {
2307 match &self.constness {
2308 Constness::Const => true,
2314 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2316 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2318 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2319 ExternCrate(Option<Name>),
2321 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2325 /// `use foo::bar::baz;` (with `as baz` implicitly on the right)
2326 Use(P<Path>, UseKind),
2329 Static(P<Ty>, Mutability, BodyId),
2331 Const(P<Ty>, BodyId),
2332 /// A function declaration
2333 Fn(P<FnDecl>, FnHeader, Generics, BodyId),
2336 /// An external module
2337 ForeignMod(ForeignMod),
2338 /// Module-level inline assembly (from global_asm!)
2339 GlobalAsm(P<GlobalAsm>),
2340 /// A type alias, e.g., `type Foo = Bar<u8>`
2341 Ty(P<Ty>, Generics),
2342 /// An existential type definition, e.g., `existential type Foo: Bar;`
2343 Existential(ExistTy),
2344 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`
2345 Enum(EnumDef, Generics),
2346 /// A struct definition, e.g., `struct Foo<A> {x: A}`
2347 Struct(VariantData, Generics),
2348 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`
2349 Union(VariantData, Generics),
2350 /// Represents a Trait Declaration
2351 Trait(IsAuto, Unsafety, Generics, GenericBounds, HirVec<TraitItemRef>),
2352 /// Represents a Trait Alias Declaration
2353 TraitAlias(Generics, GenericBounds),
2355 /// An implementation, eg `impl<A> Trait for Foo { .. }`
2360 Option<TraitRef>, // (optional) trait this impl implements
2362 HirVec<ImplItemRef>),
2366 pub fn descriptive_variant(&self) -> &str {
2368 ItemKind::ExternCrate(..) => "extern crate",
2369 ItemKind::Use(..) => "use",
2370 ItemKind::Static(..) => "static item",
2371 ItemKind::Const(..) => "constant item",
2372 ItemKind::Fn(..) => "function",
2373 ItemKind::Mod(..) => "module",
2374 ItemKind::ForeignMod(..) => "foreign module",
2375 ItemKind::GlobalAsm(..) => "global asm",
2376 ItemKind::Ty(..) => "type alias",
2377 ItemKind::Existential(..) => "existential type",
2378 ItemKind::Enum(..) => "enum",
2379 ItemKind::Struct(..) => "struct",
2380 ItemKind::Union(..) => "union",
2381 ItemKind::Trait(..) => "trait",
2382 ItemKind::TraitAlias(..) => "trait alias",
2383 ItemKind::Impl(..) => "impl",
2387 pub fn adt_kind(&self) -> Option<AdtKind> {
2389 ItemKind::Struct(..) => Some(AdtKind::Struct),
2390 ItemKind::Union(..) => Some(AdtKind::Union),
2391 ItemKind::Enum(..) => Some(AdtKind::Enum),
2396 pub fn generics(&self) -> Option<&Generics> {
2398 ItemKind::Fn(_, _, ref generics, _) |
2399 ItemKind::Ty(_, ref generics) |
2400 ItemKind::Existential(ExistTy { ref generics, impl_trait_fn: None, .. }) |
2401 ItemKind::Enum(_, ref generics) |
2402 ItemKind::Struct(_, ref generics) |
2403 ItemKind::Union(_, ref generics) |
2404 ItemKind::Trait(_, _, ref generics, _, _) |
2405 ItemKind::Impl(_, _, _, ref generics, _, _, _)=> generics,
2411 /// A reference from an trait to one of its associated items. This
2412 /// contains the item's id, naturally, but also the item's name and
2413 /// some other high-level details (like whether it is an associated
2414 /// type or method, and whether it is public). This allows other
2415 /// passes to find the impl they want without loading the ID (which
2416 /// means fewer edges in the incremental compilation graph).
2417 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2418 pub struct TraitItemRef {
2419 pub id: TraitItemId,
2420 #[stable_hasher(project(name))]
2422 pub kind: AssociatedItemKind,
2424 pub defaultness: Defaultness,
2427 /// A reference from an impl to one of its associated items. This
2428 /// contains the item's ID, naturally, but also the item's name and
2429 /// some other high-level details (like whether it is an associated
2430 /// type or method, and whether it is public). This allows other
2431 /// passes to find the impl they want without loading the ID (which
2432 /// means fewer edges in the incremental compilation graph).
2433 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2434 pub struct ImplItemRef {
2436 #[stable_hasher(project(name))]
2438 pub kind: AssociatedItemKind,
2440 pub vis: Visibility,
2441 pub defaultness: Defaultness,
2444 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2445 pub enum AssociatedItemKind {
2447 Method { has_self: bool },
2452 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2453 pub struct ForeignItem {
2454 #[stable_hasher(project(name))]
2456 pub attrs: HirVec<Attribute>,
2457 pub node: ForeignItemKind,
2460 pub vis: Visibility,
2463 /// An item within an `extern` block.
2464 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2465 pub enum ForeignItemKind {
2466 /// A foreign function.
2467 Fn(P<FnDecl>, HirVec<Ident>, Generics),
2468 /// A foreign static item (`static ext: u8`).
2469 Static(P<Ty>, Mutability),
2474 impl ForeignItemKind {
2475 pub fn descriptive_variant(&self) -> &str {
2477 ForeignItemKind::Fn(..) => "foreign function",
2478 ForeignItemKind::Static(..) => "foreign static item",
2479 ForeignItemKind::Type => "foreign type",
2484 /// A variable captured by a closure.
2485 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable, HashStable)]
2486 pub struct Upvar<Id = HirId> {
2487 /// The variable being captured.
2490 // First span where it is accessed (there can be multiple).
2494 impl<Id: fmt::Debug + Copy> Upvar<Id> {
2495 pub fn map_id<R>(self, map: impl FnMut(Id) -> R) -> Upvar<R> {
2497 res: self.res.map_id(map),
2502 pub fn var_id(&self) -> Id {
2504 Res::Local(id) | Res::Upvar(id, ..) => id,
2505 _ => bug!("Upvar::var_id: bad res ({:?})", self.res)
2510 pub type UpvarMap = NodeMap<Vec<Upvar<ast::NodeId>>>;
2512 pub type CaptureModeMap = NodeMap<CaptureClause>;
2514 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2515 // has length > 0 if the trait is found through an chain of imports, starting with the
2516 // import/use statement in the scope where the trait is used.
2517 #[derive(Clone, Debug)]
2518 pub struct TraitCandidate {
2520 pub import_ids: SmallVec<[NodeId; 1]>,
2523 // Trait method resolution
2524 pub type TraitMap = NodeMap<Vec<TraitCandidate>>;
2526 // Map from the NodeId of a glob import to a list of items which are actually
2528 pub type GlobMap = NodeMap<FxHashSet<Name>>;
2531 pub fn provide(providers: &mut Providers<'_>) {
2532 check_attr::provide(providers);
2533 providers.def_kind = map::def_kind;
2536 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
2537 pub struct CodegenFnAttrs {
2538 pub flags: CodegenFnAttrFlags,
2539 /// Parsed representation of the `#[inline]` attribute
2540 pub inline: InlineAttr,
2541 /// Parsed representation of the `#[optimize]` attribute
2542 pub optimize: OptimizeAttr,
2543 /// The `#[export_name = "..."]` attribute, indicating a custom symbol a
2544 /// function should be exported under
2545 pub export_name: Option<Symbol>,
2546 /// The `#[link_name = "..."]` attribute, indicating a custom symbol an
2547 /// imported function should be imported as. Note that `export_name`
2548 /// probably isn't set when this is set, this is for foreign items while
2549 /// `#[export_name]` is for Rust-defined functions.
2550 pub link_name: Option<Symbol>,
2551 /// The `#[target_feature(enable = "...")]` attribute and the enabled
2552 /// features (only enabled features are supported right now).
2553 pub target_features: Vec<Symbol>,
2554 /// The `#[linkage = "..."]` attribute and the value we found.
2555 pub linkage: Option<Linkage>,
2556 /// The `#[link_section = "..."]` attribute, or what executable section this
2557 /// should be placed in.
2558 pub link_section: Option<Symbol>,
2562 #[derive(RustcEncodable, RustcDecodable, HashStable)]
2563 pub struct CodegenFnAttrFlags: u32 {
2564 /// `#[cold]`: a hint to LLVM that this function, when called, is never on
2566 const COLD = 1 << 0;
2567 /// `#[allocator]`: a hint to LLVM that the pointer returned from this
2568 /// function is never null.
2569 const ALLOCATOR = 1 << 1;
2570 /// `#[unwind]`: an indicator that this function may unwind despite what
2571 /// its ABI signature may otherwise imply.
2572 const UNWIND = 1 << 2;
2573 /// `#[rust_allocator_nounwind]`, an indicator that an imported FFI
2574 /// function will never unwind. Probably obsolete by recent changes with
2575 /// #[unwind], but hasn't been removed/migrated yet
2576 const RUSTC_ALLOCATOR_NOUNWIND = 1 << 3;
2577 /// `#[naked]`: an indicator to LLVM that no function prologue/epilogue
2578 /// should be generated.
2579 const NAKED = 1 << 4;
2580 /// `#[no_mangle]`: an indicator that the function's name should be the same
2582 const NO_MANGLE = 1 << 5;
2583 /// `#[rustc_std_internal_symbol]`: an indicator that this symbol is a
2584 /// "weird symbol" for the standard library in that it has slightly
2585 /// different linkage, visibility, and reachability rules.
2586 const RUSTC_STD_INTERNAL_SYMBOL = 1 << 6;
2587 /// `#[no_debug]`: an indicator that no debugging information should be
2588 /// generated for this function by LLVM.
2589 const NO_DEBUG = 1 << 7;
2590 /// `#[thread_local]`: indicates a static is actually a thread local
2592 const THREAD_LOCAL = 1 << 8;
2593 /// `#[used]`: indicates that LLVM can't eliminate this function (but the
2595 const USED = 1 << 9;
2596 /// #[ffi_returns_twice], indicates that an extern function can return
2598 const FFI_RETURNS_TWICE = 1 << 10;
2602 impl CodegenFnAttrs {
2603 pub fn new() -> CodegenFnAttrs {
2605 flags: CodegenFnAttrFlags::empty(),
2606 inline: InlineAttr::None,
2607 optimize: OptimizeAttr::None,
2610 target_features: vec![],
2616 /// Returns `true` if `#[inline]` or `#[inline(always)]` is present.
2617 pub fn requests_inline(&self) -> bool {
2619 InlineAttr::Hint | InlineAttr::Always => true,
2620 InlineAttr::None | InlineAttr::Never => false,
2624 /// True if it looks like this symbol needs to be exported, for example:
2626 /// * `#[no_mangle]` is present
2627 /// * `#[export_name(...)]` is present
2628 /// * `#[linkage]` is present
2629 pub fn contains_extern_indicator(&self) -> bool {
2630 self.flags.contains(CodegenFnAttrFlags::NO_MANGLE) ||
2631 self.export_name.is_some() ||
2632 match self.linkage {
2633 // these are private, make sure we don't try to consider
2636 Some(Linkage::Internal) |
2637 Some(Linkage::Private) => false,
2643 #[derive(Copy, Clone, Debug)]
2644 pub enum Node<'hir> {
2646 ForeignItem(&'hir ForeignItem),
2647 TraitItem(&'hir TraitItem),
2648 ImplItem(&'hir ImplItem),
2649 Variant(&'hir Variant),
2650 Field(&'hir StructField),
2651 AnonConst(&'hir AnonConst),
2654 PathSegment(&'hir PathSegment),
2656 TraitRef(&'hir TraitRef),
2661 MacroDef(&'hir MacroDef),
2663 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
2664 /// with synthesized constructors.
2665 Ctor(&'hir VariantData),
2667 Lifetime(&'hir Lifetime),
2668 GenericParam(&'hir GenericParam),
2669 Visibility(&'hir Visibility),