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::Def;
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, Lit, 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};
41 /// HIR doesn't commit to a concrete storage type and has its own alias for a vector.
42 /// It can be `Vec`, `P<[T]>` or potentially `Box<[T]>`, or some other container with similar
43 /// behavior. Unlike AST, HIR is mostly a static structure, so we can use an owned slice instead
44 /// of `Vec` to avoid keeping extra capacity.
45 pub type HirVec<T> = P<[T]>;
47 macro_rules! hir_vec {
48 ($elem:expr; $n:expr) => (
49 $crate::hir::HirVec::from(vec![$elem; $n])
52 $crate::hir::HirVec::from(vec![$($x),*])
60 pub mod itemlikevisit;
66 /// Uniquely identifies a node in the HIR of the current crate. It is
67 /// composed of the `owner`, which is the `DefIndex` of the directly enclosing
68 /// `hir::Item`, `hir::TraitItem`, or `hir::ImplItem` (i.e., the closest "item-like"),
69 /// and the `local_id` which is unique within the given owner.
71 /// This two-level structure makes for more stable values: One can move an item
72 /// around within the source code, or add or remove stuff before it, without
73 /// the `local_id` part of the `HirId` changing, which is a very useful property in
74 /// incremental compilation where we have to persist things through changes to
76 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)]
79 pub local_id: ItemLocalId,
83 pub fn owner_def_id(self) -> DefId {
84 DefId::local(self.owner)
87 pub fn owner_local_def_id(self) -> LocalDefId {
88 LocalDefId::from_def_id(DefId::local(self.owner))
92 impl serialize::UseSpecializedEncodable for HirId {
93 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
104 impl serialize::UseSpecializedDecodable for HirId {
105 fn default_decode<D: Decoder>(d: &mut D) -> Result<HirId, D::Error> {
106 let owner = DefIndex::decode(d)?;
107 let local_id = ItemLocalId::decode(d)?;
116 impl fmt::Display for HirId {
117 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118 write!(f, "{:?}", self)
122 // hack to ensure that we don't try to access the private parts of `ItemLocalId` in this module
123 mod item_local_id_inner {
124 use rustc_data_structures::indexed_vec::Idx;
125 use rustc_macros::HashStable;
127 /// An `ItemLocalId` uniquely identifies something within a given "item-like",
128 /// that is within a hir::Item, hir::TraitItem, or hir::ImplItem. There is no
129 /// guarantee that the numerical value of a given `ItemLocalId` corresponds to
130 /// the node's position within the owning item in any way, but there is a
131 /// guarantee that the `LocalItemId`s within an owner occupy a dense range of
132 /// integers starting at zero, so a mapping that maps all or most nodes within
133 /// an "item-like" to something else can be implement by a `Vec` instead of a
134 /// tree or hash map.
135 pub struct ItemLocalId {
141 pub use self::item_local_id_inner::ItemLocalId;
143 /// The `HirId` corresponding to `CRATE_NODE_ID` and `CRATE_DEF_INDEX`.
144 pub const CRATE_HIR_ID: HirId = HirId {
145 owner: CRATE_DEF_INDEX,
146 local_id: ItemLocalId::from_u32_const(0)
149 pub const DUMMY_HIR_ID: HirId = HirId {
150 owner: CRATE_DEF_INDEX,
151 local_id: DUMMY_ITEM_LOCAL_ID,
154 pub const DUMMY_ITEM_LOCAL_ID: ItemLocalId = ItemLocalId::MAX;
156 #[derive(Clone, RustcEncodable, RustcDecodable, Copy, HashStable)]
157 pub struct Lifetime {
161 /// Either "`'a`", referring to a named lifetime definition,
162 /// or "``" (i.e., `keywords::Invalid`), for elision placeholders.
164 /// HIR lowering inserts these placeholders in type paths that
165 /// refer to type definitions needing lifetime parameters,
166 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
167 pub name: LifetimeName,
170 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy, HashStable)]
172 /// Some user-given name like `T` or `'x`.
175 /// Synthetic name generated when user elided a lifetime in an impl header.
177 /// E.g., the lifetimes in cases like these:
179 /// impl Foo for &u32
180 /// impl Foo<'_> for u32
182 /// in that case, we rewrite to
184 /// impl<'f> Foo for &'f u32
185 /// impl<'f> Foo<'f> for u32
187 /// where `'f` is something like `Fresh(0)`. The indices are
188 /// unique per impl, but not necessarily continuous.
191 /// Indicates an illegal name was given and an error has been
192 /// repored (so we should squelch other derived errors). Occurs
193 /// when, e.g., `'_` is used in the wrong place.
198 pub fn ident(&self) -> Ident {
200 ParamName::Plain(ident) => ident,
201 ParamName::Error | ParamName::Fresh(_) => keywords::UnderscoreLifetime.ident(),
205 pub fn modern(&self) -> ParamName {
207 ParamName::Plain(ident) => ParamName::Plain(ident.modern()),
208 param_name => param_name,
213 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy, HashStable)]
214 pub enum LifetimeName {
215 /// User-given names or fresh (synthetic) names.
218 /// User wrote nothing (e.g., the lifetime in `&u32`).
221 /// Indicates an error during lowering (usually `'_` in wrong place)
222 /// that was already reported.
225 /// User wrote specifies `'_`.
228 /// User wrote `'static`.
233 pub fn ident(&self) -> Ident {
235 LifetimeName::Implicit => keywords::Invalid.ident(),
236 LifetimeName::Error => keywords::Invalid.ident(),
237 LifetimeName::Underscore => keywords::UnderscoreLifetime.ident(),
238 LifetimeName::Static => keywords::StaticLifetime.ident(),
239 LifetimeName::Param(param_name) => param_name.ident(),
243 pub fn is_elided(&self) -> bool {
245 LifetimeName::Implicit | LifetimeName::Underscore => true,
247 // It might seem surprising that `Fresh(_)` counts as
248 // *not* elided -- but this is because, as far as the code
249 // in the compiler is concerned -- `Fresh(_)` variants act
250 // equivalently to "some fresh name". They correspond to
251 // early-bound regions on an impl, in other words.
252 LifetimeName::Error | LifetimeName::Param(_) | LifetimeName::Static => false,
256 fn is_static(&self) -> bool {
257 self == &LifetimeName::Static
260 pub fn modern(&self) -> LifetimeName {
262 LifetimeName::Param(param_name) => LifetimeName::Param(param_name.modern()),
263 lifetime_name => lifetime_name,
268 impl fmt::Display for Lifetime {
269 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
270 self.name.ident().fmt(f)
274 impl fmt::Debug for Lifetime {
275 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
279 print::to_string(print::NO_ANN, |s| s.print_lifetime(self)))
284 pub fn is_elided(&self) -> bool {
285 self.name.is_elided()
288 pub fn is_static(&self) -> bool {
289 self.name.is_static()
293 /// A `Path` is essentially Rust's notion of a name; for instance,
294 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
295 /// along with a bunch of supporting information.
296 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
299 /// The definition that the path resolved to.
301 /// The segments in the path: the things separated by `::`.
302 pub segments: HirVec<PathSegment>,
306 pub fn is_global(&self) -> bool {
307 !self.segments.is_empty() && self.segments[0].ident.name == keywords::PathRoot.name()
311 impl fmt::Debug for Path {
312 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
313 write!(f, "path({})", self)
317 impl fmt::Display for Path {
318 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
319 write!(f, "{}", print::to_string(print::NO_ANN, |s| s.print_path(self, false)))
323 /// A segment of a path: an identifier, an optional lifetime, and a set of
325 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
326 pub struct PathSegment {
327 /// The identifier portion of this path segment.
328 #[stable_hasher(project(name))]
330 // `id` and `def` are optional. We currently only use these in save-analysis,
331 // any path segments without these will not have save-analysis info and
332 // therefore will not have 'jump to def' in IDEs, but otherwise will not be
333 // affected. (In general, we don't bother to get the defs for synthesized
334 // segments, only for segments which have come from the AST).
335 pub hir_id: Option<HirId>,
336 pub def: Option<Def>,
338 /// Type/lifetime parameters attached to this path. They come in
339 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
340 /// this is more than just simple syntactic sugar; the use of
341 /// parens affects the region binding rules, so we preserve the
343 pub args: Option<P<GenericArgs>>,
345 /// Whether to infer remaining type parameters, if any.
346 /// This only applies to expression and pattern paths, and
347 /// out of those only the segments with no type parameters
348 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
349 pub infer_types: bool,
353 /// Converts an identifier to the corresponding segment.
354 pub fn from_ident(ident: Ident) -> PathSegment {
366 hir_id: Option<HirId>,
376 args: if args.is_empty() {
384 // FIXME: hack required because you can't create a static
385 // `GenericArgs`, so you can't just return a `&GenericArgs`.
386 pub fn with_generic_args<F, R>(&self, f: F) -> R
387 where F: FnOnce(&GenericArgs) -> R
389 let dummy = GenericArgs::none();
390 f(if let Some(ref args) = self.args {
398 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
399 pub struct ConstArg {
400 pub value: AnonConst,
404 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
405 pub enum GenericArg {
412 pub fn span(&self) -> Span {
414 GenericArg::Lifetime(l) => l.span,
415 GenericArg::Type(t) => t.span,
416 GenericArg::Const(c) => c.span,
420 pub fn id(&self) -> HirId {
422 GenericArg::Lifetime(l) => l.hir_id,
423 GenericArg::Type(t) => t.hir_id,
424 GenericArg::Const(c) => c.value.hir_id,
429 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
430 pub struct GenericArgs {
431 /// The generic arguments for this path segment.
432 pub args: HirVec<GenericArg>,
433 /// Bindings (equality constraints) on associated types, if present.
434 /// E.g., `Foo<A = Bar>`.
435 pub bindings: HirVec<TypeBinding>,
436 /// Were arguments written in parenthesized form `Fn(T) -> U`?
437 /// This is required mostly for pretty-printing and diagnostics,
438 /// but also for changing lifetime elision rules to be "function-like".
439 pub parenthesized: bool,
443 pub fn none() -> Self {
446 bindings: HirVec::new(),
447 parenthesized: false,
451 pub fn is_empty(&self) -> bool {
452 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
455 pub fn inputs(&self) -> &[Ty] {
456 if self.parenthesized {
457 for arg in &self.args {
459 GenericArg::Lifetime(_) => {}
460 GenericArg::Type(ref ty) => {
461 if let TyKind::Tup(ref tys) = ty.node {
466 GenericArg::Const(_) => {}
470 bug!("GenericArgs::inputs: not a `Fn(T) -> U`");
473 pub fn own_counts(&self) -> GenericParamCount {
474 // We could cache this as a property of `GenericParamCount`, but
475 // the aim is to refactor this away entirely eventually and the
476 // presence of this method will be a constant reminder.
477 let mut own_counts: GenericParamCount = Default::default();
479 for arg in &self.args {
481 GenericArg::Lifetime(_) => own_counts.lifetimes += 1,
482 GenericArg::Type(_) => own_counts.types += 1,
483 GenericArg::Const(_) => own_counts.consts += 1,
491 /// A modifier on a bound, currently this is only used for `?Sized`, where the
492 /// modifier is `Maybe`. Negative bounds should also be handled here.
493 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
494 pub enum TraitBoundModifier {
499 /// The AST represents all type param bounds as types.
500 /// `typeck::collect::compute_bounds` matches these against
501 /// the "special" built-in traits (see `middle::lang_items`) and
502 /// detects `Copy`, `Send` and `Sync`.
503 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
504 pub enum GenericBound {
505 Trait(PolyTraitRef, TraitBoundModifier),
510 pub fn span(&self) -> Span {
512 &GenericBound::Trait(ref t, ..) => t.span,
513 &GenericBound::Outlives(ref l) => l.span,
518 pub type GenericBounds = HirVec<GenericBound>;
520 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable)]
521 pub enum LifetimeParamKind {
522 // Indicates that the lifetime definition was explicitly declared (e.g., in
523 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
526 // Indicates that the lifetime definition was synthetically added
527 // as a result of an in-band lifetime usage (e.g., in
528 // `fn foo(x: &'a u8) -> &'a u8 { x }`).
531 // Indication that the lifetime was elided (e.g., in both cases in
532 // `fn foo(x: &u8) -> &'_ u8 { x }`).
535 // Indication that the lifetime name was somehow in error.
539 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
540 pub enum GenericParamKind {
541 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
543 kind: LifetimeParamKind,
546 default: Option<P<Ty>>,
547 synthetic: Option<SyntheticTyParamKind>,
554 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
555 pub struct GenericParam {
558 pub attrs: HirVec<Attribute>,
559 pub bounds: GenericBounds,
561 pub pure_wrt_drop: bool,
563 pub kind: GenericParamKind,
567 pub struct GenericParamCount {
568 pub lifetimes: usize,
573 /// Represents lifetimes and type parameters attached to a declaration
574 /// of a function, enum, trait, etc.
575 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
576 pub struct Generics {
577 pub params: HirVec<GenericParam>,
578 pub where_clause: WhereClause,
583 pub fn empty() -> Generics {
585 params: HirVec::new(),
586 where_clause: WhereClause {
587 hir_id: DUMMY_HIR_ID,
588 predicates: HirVec::new(),
594 pub fn own_counts(&self) -> GenericParamCount {
595 // We could cache this as a property of `GenericParamCount`, but
596 // the aim is to refactor this away entirely eventually and the
597 // presence of this method will be a constant reminder.
598 let mut own_counts: GenericParamCount = Default::default();
600 for param in &self.params {
602 GenericParamKind::Lifetime { .. } => own_counts.lifetimes += 1,
603 GenericParamKind::Type { .. } => own_counts.types += 1,
604 GenericParamKind::Const { .. } => own_counts.consts += 1,
611 pub fn get_named(&self, name: &InternedString) -> Option<&GenericParam> {
612 for param in &self.params {
613 if *name == param.name.ident().as_interned_str() {
621 /// Synthetic type parameters are converted to another form during lowering; this allows
622 /// us to track the original form they had, and is useful for error messages.
623 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
624 pub enum SyntheticTyParamKind {
628 /// A where-clause in a definition.
629 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
630 pub struct WhereClause {
632 pub predicates: HirVec<WherePredicate>,
636 pub fn span(&self) -> Option<Span> {
637 self.predicates.iter().map(|predicate| predicate.span())
638 .fold(None, |acc, i| match (acc, i) {
639 (None, i) => Some(i),
647 /// A single predicate in a where-clause.
648 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
649 pub enum WherePredicate {
650 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
651 BoundPredicate(WhereBoundPredicate),
652 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
653 RegionPredicate(WhereRegionPredicate),
654 /// An equality predicate (unsupported).
655 EqPredicate(WhereEqPredicate),
658 impl WherePredicate {
659 pub fn span(&self) -> Span {
661 &WherePredicate::BoundPredicate(ref p) => p.span,
662 &WherePredicate::RegionPredicate(ref p) => p.span,
663 &WherePredicate::EqPredicate(ref p) => p.span,
668 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
669 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
670 pub struct WhereBoundPredicate {
672 /// Any generics from a `for` binding.
673 pub bound_generic_params: HirVec<GenericParam>,
674 /// The type being bounded.
675 pub bounded_ty: P<Ty>,
676 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
677 pub bounds: GenericBounds,
680 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
681 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
682 pub struct WhereRegionPredicate {
684 pub lifetime: Lifetime,
685 pub bounds: GenericBounds,
688 /// An equality predicate (e.g., `T = int`); currently unsupported.
689 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
690 pub struct WhereEqPredicate {
697 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
698 pub struct ModuleItems {
699 // Use BTreeSets here so items are in the same order as in the
700 // list of all items in Crate
701 pub items: BTreeSet<HirId>,
702 pub trait_items: BTreeSet<TraitItemId>,
703 pub impl_items: BTreeSet<ImplItemId>,
706 /// The top-level data structure that stores the entire contents of
707 /// the crate currently being compiled.
709 /// For more details, see the [rustc guide].
711 /// [rustc guide]: https://rust-lang.github.io/rustc-guide/hir.html
712 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
715 pub attrs: HirVec<Attribute>,
717 pub exported_macros: HirVec<MacroDef>,
719 // N.B., we use a BTreeMap here so that `visit_all_items` iterates
720 // over the ids in increasing order. In principle it should not
721 // matter what order we visit things in, but in *practice* it
722 // does, because it can affect the order in which errors are
723 // detected, which in turn can make compile-fail tests yield
724 // slightly different results.
725 pub items: BTreeMap<HirId, Item>,
727 pub trait_items: BTreeMap<TraitItemId, TraitItem>,
728 pub impl_items: BTreeMap<ImplItemId, ImplItem>,
729 pub bodies: BTreeMap<BodyId, Body>,
730 pub trait_impls: BTreeMap<DefId, Vec<HirId>>,
732 /// A list of the body ids written out in the order in which they
733 /// appear in the crate. If you're going to process all the bodies
734 /// in the crate, you should iterate over this list rather than the keys
736 pub body_ids: Vec<BodyId>,
738 /// A list of modules written out in the order in which they
739 /// appear in the crate. This includes the main crate module.
740 pub modules: BTreeMap<NodeId, ModuleItems>,
744 pub fn item(&self, id: HirId) -> &Item {
748 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem {
749 &self.trait_items[&id]
752 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem {
753 &self.impl_items[&id]
756 /// Visits all items in the crate in some deterministic (but
757 /// unspecified) order. If you just need to process every item,
758 /// but don't care about nesting, this method is the best choice.
760 /// If you do care about nesting -- usually because your algorithm
761 /// follows lexical scoping rules -- then you want a different
762 /// approach. You should override `visit_nested_item` in your
763 /// visitor and then call `intravisit::walk_crate` instead.
764 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
765 where V: itemlikevisit::ItemLikeVisitor<'hir>
767 for (_, item) in &self.items {
768 visitor.visit_item(item);
771 for (_, trait_item) in &self.trait_items {
772 visitor.visit_trait_item(trait_item);
775 for (_, impl_item) in &self.impl_items {
776 visitor.visit_impl_item(impl_item);
780 /// A parallel version of `visit_all_item_likes`.
781 pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
782 where V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send
785 par_for_each_in(&self.items, |(_, item)| {
786 visitor.visit_item(item);
789 par_for_each_in(&self.trait_items, |(_, trait_item)| {
790 visitor.visit_trait_item(trait_item);
793 par_for_each_in(&self.impl_items, |(_, impl_item)| {
794 visitor.visit_impl_item(impl_item);
799 pub fn body(&self, id: BodyId) -> &Body {
804 /// A macro definition, in this crate or imported from another.
806 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
807 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
808 pub struct MacroDef {
811 pub attrs: HirVec<Attribute>,
814 pub body: TokenStream,
818 /// A block of statements `{ .. }`, which may have a label (in this case the
819 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
820 /// the `rules` being anything but `DefaultBlock`.
821 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
823 /// Statements in a block.
824 pub stmts: HirVec<Stmt>,
825 /// An expression at the end of the block
826 /// without a semicolon, if any.
827 pub expr: Option<P<Expr>>,
828 #[stable_hasher(ignore)]
830 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
831 pub rules: BlockCheckMode,
833 /// If true, then there may exist `break 'a` values that aim to
834 /// break out of this block early.
835 /// Used by `'label: {}` blocks and by `catch` statements.
836 pub targeted_by_break: bool,
839 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
841 #[stable_hasher(ignore)]
847 impl fmt::Debug for Pat {
848 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
849 write!(f, "pat({}: {})", self.hir_id,
850 print::to_string(print::NO_ANN, |s| s.print_pat(self)))
855 // FIXME(#19596) this is a workaround, but there should be a better way
856 fn walk_<G>(&self, it: &mut G) -> bool
857 where G: FnMut(&Pat) -> bool
864 PatKind::Binding(.., Some(ref p)) => p.walk_(it),
865 PatKind::Struct(_, ref fields, _) => {
866 fields.iter().all(|field| field.node.pat.walk_(it))
868 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
869 s.iter().all(|p| p.walk_(it))
871 PatKind::Box(ref s) | PatKind::Ref(ref s, _) => {
874 PatKind::Slice(ref before, ref slice, ref after) => {
878 .all(|p| p.walk_(it))
883 PatKind::Binding(..) |
884 PatKind::Path(_) => {
890 pub fn walk<F>(&self, mut it: F) -> bool
891 where F: FnMut(&Pat) -> bool
897 /// A single field in a struct pattern.
899 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
900 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
901 /// except `is_shorthand` is true.
902 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
903 pub struct FieldPat {
904 #[stable_hasher(ignore)]
906 /// The identifier for the field.
907 #[stable_hasher(project(name))]
909 /// The pattern the field is destructured to.
911 pub is_shorthand: bool,
914 /// Explicit binding annotations given in the HIR for a binding. Note
915 /// that this is not the final binding *mode* that we infer after type
917 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable)]
918 pub enum BindingAnnotation {
919 /// No binding annotation given: this means that the final binding mode
920 /// will depend on whether we have skipped through a `&` reference
921 /// when matching. For example, the `x` in `Some(x)` will have binding
922 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
923 /// ultimately be inferred to be by-reference.
925 /// Note that implicit reference skipping is not implemented yet (#42640).
928 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
931 /// Annotated as `ref`, like `ref x`
934 /// Annotated as `ref mut x`.
938 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
944 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
946 /// Represents a wildcard pattern (i.e., `_`).
949 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
950 /// The `HirId` is the canonical ID for the variable being bound,
951 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
952 /// which is the pattern ID of the first `x`.
953 Binding(BindingAnnotation, HirId, Ident, Option<P<Pat>>),
955 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
956 /// The `bool` is `true` in the presence of a `..`.
957 Struct(QPath, HirVec<Spanned<FieldPat>>, bool),
959 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
960 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
961 /// `0 <= position <= subpats.len()`
962 TupleStruct(QPath, HirVec<P<Pat>>, Option<usize>),
964 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
967 /// A tuple pattern (e.g., `(a, b)`).
968 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
969 /// `0 <= position <= subpats.len()`
970 Tuple(HirVec<P<Pat>>, Option<usize>),
975 /// A reference pattern (e.g., `&mut (a, b)`).
976 Ref(P<Pat>, Mutability),
981 /// A range pattern (e.g., `1...2` or `1..2`).
982 Range(P<Expr>, P<Expr>, RangeEnd),
984 /// `[a, b, ..i, y, z]` is represented as:
985 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`.
986 Slice(HirVec<P<Pat>>, Option<P<Pat>>, HirVec<P<Pat>>),
989 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, HashStable,
990 RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
991 pub enum Mutability {
997 /// Returns `MutMutable` only if both arguments are mutable.
998 pub fn and(self, other: Self) -> Self {
1000 MutMutable => other,
1001 MutImmutable => MutImmutable,
1006 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, Hash, HashStable)]
1007 pub enum BinOpKind {
1008 /// The `+` operator (addition).
1010 /// The `-` operator (subtraction).
1012 /// The `*` operator (multiplication).
1014 /// The `/` operator (division).
1016 /// The `%` operator (modulus).
1018 /// The `&&` operator (logical and).
1020 /// The `||` operator (logical or).
1022 /// The `^` operator (bitwise xor).
1024 /// The `&` operator (bitwise and).
1026 /// The `|` operator (bitwise or).
1028 /// The `<<` operator (shift left).
1030 /// The `>>` operator (shift right).
1032 /// The `==` operator (equality).
1034 /// The `<` operator (less than).
1036 /// The `<=` operator (less than or equal to).
1038 /// The `!=` operator (not equal to).
1040 /// The `>=` operator (greater than or equal to).
1042 /// The `>` operator (greater than).
1047 pub fn as_str(self) -> &'static str {
1049 BinOpKind::Add => "+",
1050 BinOpKind::Sub => "-",
1051 BinOpKind::Mul => "*",
1052 BinOpKind::Div => "/",
1053 BinOpKind::Rem => "%",
1054 BinOpKind::And => "&&",
1055 BinOpKind::Or => "||",
1056 BinOpKind::BitXor => "^",
1057 BinOpKind::BitAnd => "&",
1058 BinOpKind::BitOr => "|",
1059 BinOpKind::Shl => "<<",
1060 BinOpKind::Shr => ">>",
1061 BinOpKind::Eq => "==",
1062 BinOpKind::Lt => "<",
1063 BinOpKind::Le => "<=",
1064 BinOpKind::Ne => "!=",
1065 BinOpKind::Ge => ">=",
1066 BinOpKind::Gt => ">",
1070 pub fn is_lazy(self) -> bool {
1072 BinOpKind::And | BinOpKind::Or => true,
1077 pub fn is_shift(self) -> bool {
1079 BinOpKind::Shl | BinOpKind::Shr => true,
1084 pub fn is_comparison(self) -> bool {
1091 BinOpKind::Ge => true,
1103 BinOpKind::Shr => false,
1107 /// Returns `true` if the binary operator takes its arguments by value.
1108 pub fn is_by_value(self) -> bool {
1109 !self.is_comparison()
1113 impl Into<ast::BinOpKind> for BinOpKind {
1114 fn into(self) -> ast::BinOpKind {
1116 BinOpKind::Add => ast::BinOpKind::Add,
1117 BinOpKind::Sub => ast::BinOpKind::Sub,
1118 BinOpKind::Mul => ast::BinOpKind::Mul,
1119 BinOpKind::Div => ast::BinOpKind::Div,
1120 BinOpKind::Rem => ast::BinOpKind::Rem,
1121 BinOpKind::And => ast::BinOpKind::And,
1122 BinOpKind::Or => ast::BinOpKind::Or,
1123 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1124 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1125 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1126 BinOpKind::Shl => ast::BinOpKind::Shl,
1127 BinOpKind::Shr => ast::BinOpKind::Shr,
1128 BinOpKind::Eq => ast::BinOpKind::Eq,
1129 BinOpKind::Lt => ast::BinOpKind::Lt,
1130 BinOpKind::Le => ast::BinOpKind::Le,
1131 BinOpKind::Ne => ast::BinOpKind::Ne,
1132 BinOpKind::Ge => ast::BinOpKind::Ge,
1133 BinOpKind::Gt => ast::BinOpKind::Gt,
1138 pub type BinOp = Spanned<BinOpKind>;
1140 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, Hash, HashStable)]
1142 /// The `*` operator (deferencing).
1144 /// The `!` operator (logical negation).
1146 /// The `-` operator (negation).
1151 pub fn as_str(self) -> &'static str {
1159 /// Returns `true` if the unary operator takes its argument by value.
1160 pub fn is_by_value(self) -> bool {
1162 UnNeg | UnNot => true,
1169 #[derive(Clone, RustcEncodable, RustcDecodable)]
1176 impl fmt::Debug for Stmt {
1177 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1178 write!(f, "stmt({}: {})", self.hir_id,
1179 print::to_string(print::NO_ANN, |s| s.print_stmt(self)))
1183 /// The contents of a statement.
1184 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
1186 /// A local (`let`) binding.
1189 /// An item binding.
1192 /// An expression without a trailing semi-colon (must have unit type).
1195 /// An expression with a trailing semi-colon (may have any type).
1200 pub fn attrs(&self) -> &[Attribute] {
1202 StmtKind::Local(ref l) => &l.attrs,
1203 StmtKind::Item(_) => &[],
1204 StmtKind::Expr(ref e) |
1205 StmtKind::Semi(ref e) => &e.attrs,
1210 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1211 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1214 /// Type annotation, if any (otherwise the type will be inferred).
1215 pub ty: Option<P<Ty>>,
1216 /// Initializer expression to set the value, if any.
1217 pub init: Option<P<Expr>>,
1220 pub attrs: ThinVec<Attribute>,
1221 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1222 /// desugaring. Otherwise will be `Normal`.
1223 pub source: LocalSource,
1226 /// Represents a single arm of a `match` expression, e.g.
1227 /// `<pats> (if <guard>) => <body>`.
1228 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1230 pub attrs: HirVec<Attribute>,
1231 /// Multiple patterns can be combined with `|`
1232 pub pats: HirVec<P<Pat>>,
1233 /// Optional guard clause.
1234 pub guard: Option<Guard>,
1235 /// The expression the arm evaluates to if this arm matches.
1239 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1244 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1246 #[stable_hasher(ignore)]
1251 pub is_shorthand: bool,
1254 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable)]
1255 pub enum BlockCheckMode {
1257 UnsafeBlock(UnsafeSource),
1258 PushUnsafeBlock(UnsafeSource),
1259 PopUnsafeBlock(UnsafeSource),
1262 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable)]
1263 pub enum UnsafeSource {
1268 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1273 /// The body of a function, closure, or constant value. In the case of
1274 /// a function, the body contains not only the function body itself
1275 /// (which is an expression), but also the argument patterns, since
1276 /// those are something that the caller doesn't really care about.
1281 /// fn foo((x, y): (u32, u32)) -> u32 {
1286 /// Here, the `Body` associated with `foo()` would contain:
1288 /// - an `arguments` array containing the `(x, y)` pattern
1289 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1290 /// - `is_generator` would be false
1292 /// All bodies have an **owner**, which can be accessed via the HIR
1293 /// map using `body_owner_def_id()`.
1294 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1296 pub arguments: HirVec<Arg>,
1298 pub is_generator: bool,
1302 pub fn id(&self) -> BodyId {
1304 hir_id: self.value.hir_id,
1309 #[derive(Copy, Clone, Debug)]
1310 pub enum BodyOwnerKind {
1311 /// Functions and methods.
1317 /// Constants and associated constants.
1320 /// Initializer of a `static` item.
1324 impl BodyOwnerKind {
1325 pub fn is_fn_or_closure(self) -> bool {
1327 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1328 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1333 /// A constant (expression) that's not an item or associated item,
1334 /// but needs its own `DefId` for type-checking, const-eval, etc.
1335 /// These are usually found nested inside types (e.g., array lengths)
1336 /// or expressions (e.g., repeat counts), and also used to define
1337 /// explicit discriminant values for enum variants.
1338 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1339 pub struct AnonConst {
1345 #[derive(Clone, RustcEncodable, RustcDecodable)]
1349 pub attrs: ThinVec<Attribute>,
1353 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1354 #[cfg(target_arch = "x86_64")]
1355 static_assert!(MEM_SIZE_OF_EXPR: std::mem::size_of::<Expr>() == 72);
1358 pub fn precedence(&self) -> ExprPrecedence {
1360 ExprKind::Box(_) => ExprPrecedence::Box,
1361 ExprKind::Array(_) => ExprPrecedence::Array,
1362 ExprKind::Call(..) => ExprPrecedence::Call,
1363 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1364 ExprKind::Tup(_) => ExprPrecedence::Tup,
1365 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1366 ExprKind::Unary(..) => ExprPrecedence::Unary,
1367 ExprKind::Lit(_) => ExprPrecedence::Lit,
1368 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1369 ExprKind::Use(ref expr, ..) => expr.precedence(),
1370 ExprKind::If(..) => ExprPrecedence::If,
1371 ExprKind::While(..) => ExprPrecedence::While,
1372 ExprKind::Loop(..) => ExprPrecedence::Loop,
1373 ExprKind::Match(..) => ExprPrecedence::Match,
1374 ExprKind::Closure(..) => ExprPrecedence::Closure,
1375 ExprKind::Block(..) => ExprPrecedence::Block,
1376 ExprKind::Assign(..) => ExprPrecedence::Assign,
1377 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1378 ExprKind::Field(..) => ExprPrecedence::Field,
1379 ExprKind::Index(..) => ExprPrecedence::Index,
1380 ExprKind::Path(..) => ExprPrecedence::Path,
1381 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1382 ExprKind::Break(..) => ExprPrecedence::Break,
1383 ExprKind::Continue(..) => ExprPrecedence::Continue,
1384 ExprKind::Ret(..) => ExprPrecedence::Ret,
1385 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1386 ExprKind::Struct(..) => ExprPrecedence::Struct,
1387 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1388 ExprKind::Yield(..) => ExprPrecedence::Yield,
1389 ExprKind::Err => ExprPrecedence::Err,
1393 pub fn is_place_expr(&self) -> bool {
1395 ExprKind::Path(QPath::Resolved(_, ref path)) => {
1397 Def::Local(..) | Def::Upvar(..) | Def::Static(..) | Def::Err => true,
1402 ExprKind::Type(ref e, _) => {
1406 ExprKind::Unary(UnDeref, _) |
1407 ExprKind::Field(..) |
1408 ExprKind::Index(..) => {
1412 // Partially qualified paths in expressions can only legally
1413 // refer to associated items which are always rvalues.
1414 ExprKind::Path(QPath::TypeRelative(..)) |
1416 ExprKind::Call(..) |
1417 ExprKind::MethodCall(..) |
1418 ExprKind::Struct(..) |
1421 ExprKind::Match(..) |
1422 ExprKind::Closure(..) |
1423 ExprKind::Block(..) |
1424 ExprKind::Repeat(..) |
1425 ExprKind::Array(..) |
1426 ExprKind::Break(..) |
1427 ExprKind::Continue(..) |
1429 ExprKind::While(..) |
1430 ExprKind::Loop(..) |
1431 ExprKind::Assign(..) |
1432 ExprKind::InlineAsm(..) |
1433 ExprKind::AssignOp(..) |
1435 ExprKind::Unary(..) |
1437 ExprKind::AddrOf(..) |
1438 ExprKind::Binary(..) |
1439 ExprKind::Yield(..) |
1440 ExprKind::Cast(..) |
1449 impl fmt::Debug for Expr {
1450 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1451 write!(f, "expr({}: {})", self.hir_id,
1452 print::to_string(print::NO_ANN, |s| s.print_expr(self)))
1456 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1458 /// A `box x` expression.
1460 /// An array (e.g., `[a, b, c, d]`).
1461 Array(HirVec<Expr>),
1462 /// A function call.
1464 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1465 /// and the second field is the list of arguments.
1466 /// This also represents calling the constructor of
1467 /// tuple-like ADTs such as tuple structs and enum variants.
1468 Call(P<Expr>, HirVec<Expr>),
1469 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1471 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1472 /// (within the angle brackets).
1473 /// The first element of the vector of `Expr`s is the expression that evaluates
1474 /// to the object on which the method is being called on (the receiver),
1475 /// and the remaining elements are the rest of the arguments.
1476 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1477 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1478 MethodCall(P<PathSegment>, Span, HirVec<Expr>),
1479 /// A tuple (e.g., `(a, b, c ,d)`).
1481 /// A binary operation (e.g., `a + b`, `a * b`).
1482 Binary(BinOp, P<Expr>, P<Expr>),
1483 /// A unary operation (e.g., `!x`, `*x`).
1484 Unary(UnOp, P<Expr>),
1485 /// A literal (e.g., `1`, `"foo"`).
1487 /// A cast (e.g., `foo as f64`).
1488 Cast(P<Expr>, P<Ty>),
1489 /// A type reference (e.g., `Foo`).
1490 Type(P<Expr>, P<Ty>),
1491 /// Semantically equivalent to `{ let _t = expr; _t }`.
1492 /// Maps directly to `hair::ExprKind::Use`.
1493 /// Only exists to tweak the drop order in HIR.
1495 /// An `if` block, with an optional else block.
1497 /// I.e., `if <expr> { <expr> } else { <expr> }`.
1498 If(P<Expr>, P<Expr>, Option<P<Expr>>),
1499 /// A while loop, with an optional label
1501 /// I.e., `'label: while expr { <block> }`.
1502 While(P<Expr>, P<Block>, Option<Label>),
1503 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1505 /// I.e., `'label: loop { <block> }`.
1506 Loop(P<Block>, Option<Label>, LoopSource),
1507 /// A `match` block, with a source that indicates whether or not it is
1508 /// the result of a desugaring, and if so, which kind.
1509 Match(P<Expr>, HirVec<Arm>, MatchSource),
1510 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1512 /// The final span is the span of the argument block `|...|`.
1514 /// This may also be a generator literal, indicated by the final boolean,
1515 /// in that case there is an `GeneratorClause`.
1516 Closure(CaptureClause, P<FnDecl>, BodyId, Span, Option<GeneratorMovability>),
1517 /// A block (e.g., `'label: { ... }`).
1518 Block(P<Block>, Option<Label>),
1520 /// An assignment (e.g., `a = foo()`).
1521 Assign(P<Expr>, P<Expr>),
1522 /// An assignment with an operator.
1525 AssignOp(BinOp, P<Expr>, P<Expr>),
1526 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1527 Field(P<Expr>, Ident),
1528 /// An indexing operation (`foo[2]`).
1529 Index(P<Expr>, P<Expr>),
1531 /// Path to a definition, possibly containing lifetime or type parameters.
1534 /// A referencing operation (i.e., `&a` or `&mut a`).
1535 AddrOf(Mutability, P<Expr>),
1536 /// A `break`, with an optional label to break.
1537 Break(Destination, Option<P<Expr>>),
1538 /// A `continue`, with an optional label.
1539 Continue(Destination),
1540 /// A `return`, with an optional value to be returned.
1541 Ret(Option<P<Expr>>),
1543 /// Inline assembly (from `asm!`), with its outputs and inputs.
1544 InlineAsm(P<InlineAsm>, HirVec<Expr>, HirVec<Expr>),
1546 /// A struct or struct-like variant literal expression.
1548 /// For example, `Foo {x: 1, y: 2}`, or
1549 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
1550 Struct(P<QPath>, HirVec<Field>, Option<P<Expr>>),
1552 /// An array literal constructed from one repeated element.
1554 /// For example, `[1; 5]`. The first expression is the element
1555 /// to be repeated; the second is the number of times to repeat it.
1556 Repeat(P<Expr>, AnonConst),
1558 /// A suspension point for generators (i.e., `yield <expr>`).
1561 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1565 /// Optionally `Self`-qualified value/type path or associated extension.
1566 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1568 /// Path to a definition, optionally "fully-qualified" with a `Self`
1569 /// type, if the path points to an associated item in a trait.
1571 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1572 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1573 /// even though they both have the same two-segment `Clone::clone` `Path`.
1574 Resolved(Option<P<Ty>>, P<Path>),
1576 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1577 /// Will be resolved by type-checking to an associated item.
1579 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1580 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1581 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1582 TypeRelative(P<Ty>, P<PathSegment>)
1585 /// Hints at the original code for a let statement.
1586 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, HashStable)]
1587 pub enum LocalSource {
1588 /// A `match _ { .. }`.
1590 /// A desugared `for _ in _ { .. }` loop.
1592 /// When lowering async functions, we create locals within the `async move` so that
1593 /// all arguments are dropped after the future is polled.
1595 /// ```ignore (pseudo-Rust)
1596 /// async fn foo(<pattern> @ x: Type) {
1598 /// let <pattern> = x;
1605 /// Hints at the original code for a `match _ { .. }`.
1606 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy, HashStable)]
1607 pub enum MatchSource {
1608 /// A `match _ { .. }`.
1610 /// An `if let _ = _ { .. }` (optionally with `else { .. }`).
1612 contains_else_clause: bool,
1614 /// A `while let _ = _ { .. }` (which was desugared to a
1615 /// `loop { match _ { .. } }`).
1617 /// A desugared `for _ in _ { .. }` loop.
1619 /// A desugared `?` operator.
1623 /// The loop type that yielded an `ExprKind::Loop`.
1624 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable)]
1625 pub enum LoopSource {
1626 /// A `loop { .. }` loop.
1628 /// A `while let _ = _ { .. }` loop.
1630 /// A `for _ in _ { .. }` loop.
1634 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, HashStable)]
1635 pub enum LoopIdError {
1637 UnlabeledCfInWhileCondition,
1641 impl fmt::Display for LoopIdError {
1642 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1643 fmt::Display::fmt(match *self {
1644 LoopIdError::OutsideLoopScope => "not inside loop scope",
1645 LoopIdError::UnlabeledCfInWhileCondition =>
1646 "unlabeled control flow (break or continue) in while condition",
1647 LoopIdError::UnresolvedLabel => "label not found",
1652 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, HashStable)]
1653 pub struct Destination {
1654 // This is `Some(_)` iff there is an explicit user-specified `label
1655 pub label: Option<Label>,
1657 // These errors are caught and then reported during the diagnostics pass in
1658 // librustc_passes/loops.rs
1659 pub target_id: Result<HirId, LoopIdError>,
1662 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, HashStable,
1663 RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1664 pub enum GeneratorMovability {
1669 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, HashStable)]
1670 pub enum CaptureClause {
1675 // N.B., if you change this, you'll probably want to change the corresponding
1676 // type structure in middle/ty.rs as well.
1677 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1680 pub mutbl: Mutability,
1683 /// Represents a method's signature in a trait declaration or implementation.
1684 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1685 pub struct MethodSig {
1686 pub header: FnHeader,
1687 pub decl: P<FnDecl>,
1690 // The bodies for items are stored "out of line", in a separate
1691 // hashmap in the `Crate`. Here we just record the node-id of the item
1692 // so it can fetched later.
1693 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1694 pub struct TraitItemId {
1698 /// Represents an item declaration within a trait declaration,
1699 /// possibly including a default implementation. A trait item is
1700 /// either required (meaning it doesn't have an implementation, just a
1701 /// signature) or provided (meaning it has a default implementation).
1702 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1703 pub struct TraitItem {
1706 pub attrs: HirVec<Attribute>,
1707 pub generics: Generics,
1708 pub node: TraitItemKind,
1712 /// A trait method's body (or just argument names).
1713 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1714 pub enum TraitMethod {
1715 /// No default body in the trait, just a signature.
1716 Required(HirVec<Ident>),
1718 /// Both signature and body are provided in the trait.
1722 /// Represents a trait method or associated constant or type
1723 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1724 pub enum TraitItemKind {
1725 /// An associated constant with an optional value (otherwise `impl`s
1726 /// must contain a value)
1727 Const(P<Ty>, Option<BodyId>),
1728 /// A method with an optional body
1729 Method(MethodSig, TraitMethod),
1730 /// An associated type with (possibly empty) bounds and optional concrete
1732 Type(GenericBounds, Option<P<Ty>>),
1735 // The bodies for items are stored "out of line", in a separate
1736 // hashmap in the `Crate`. Here we just record the node-id of the item
1737 // so it can fetched later.
1738 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1739 pub struct ImplItemId {
1743 /// Represents anything within an `impl` block
1744 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1745 pub struct ImplItem {
1748 pub vis: Visibility,
1749 pub defaultness: Defaultness,
1750 pub attrs: HirVec<Attribute>,
1751 pub generics: Generics,
1752 pub node: ImplItemKind,
1756 /// Represents different contents within `impl`s
1757 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1758 pub enum ImplItemKind {
1759 /// An associated constant of the given type, set to the constant result
1760 /// of the expression
1761 Const(P<Ty>, BodyId),
1762 /// A method implementation with the given signature and body
1763 Method(MethodSig, BodyId),
1764 /// An associated type
1766 /// An associated existential type
1767 Existential(GenericBounds),
1770 // Bind a type to an associated type: `A=Foo`.
1771 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1772 pub struct TypeBinding {
1774 #[stable_hasher(project(name))]
1780 #[derive(Clone, RustcEncodable, RustcDecodable)]
1787 impl fmt::Debug for Ty {
1788 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1789 write!(f, "type({})",
1790 print::to_string(print::NO_ANN, |s| s.print_type(self)))
1794 /// Not represented directly in the AST; referred to by name through a `ty_path`.
1795 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy, HashStable)]
1805 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1806 pub struct BareFnTy {
1807 pub unsafety: Unsafety,
1809 pub generic_params: HirVec<GenericParam>,
1810 pub decl: P<FnDecl>,
1811 pub arg_names: HirVec<Ident>,
1814 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1815 pub struct ExistTy {
1816 pub generics: Generics,
1817 pub bounds: GenericBounds,
1818 pub impl_trait_fn: Option<DefId>,
1819 pub origin: ExistTyOrigin,
1822 /// Where the existential type came from
1823 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1824 pub enum ExistTyOrigin {
1825 /// `existential type Foo: Trait;`
1833 /// The various kinds of types recognized by the compiler.
1834 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1836 /// A variable length slice (i.e., `[T]`).
1838 /// A fixed length array (i.e., `[T; n]`).
1839 Array(P<Ty>, AnonConst),
1840 /// A raw pointer (i.e., `*const T` or `*mut T`).
1842 /// A reference (i.e., `&'a T` or `&'a mut T`).
1843 Rptr(Lifetime, MutTy),
1844 /// A bare function (e.g., `fn(usize) -> bool`).
1845 BareFn(P<BareFnTy>),
1846 /// The never type (`!`).
1848 /// A tuple (`(A, B, C, D,...)`).
1850 /// A path to a type definition (`module::module::...::Type`), or an
1851 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
1853 /// Type parameters may be stored in each `PathSegment`.
1855 /// A type definition itself. This is currently only used for the `existential type`
1856 /// item that `impl Trait` in return position desugars to.
1858 /// The generic argument list contains the lifetimes (and in the future possibly parameters)
1859 /// that are actually bound on the `impl Trait`.
1860 Def(ItemId, HirVec<GenericArg>),
1861 /// A trait object type `Bound1 + Bound2 + Bound3`
1862 /// where `Bound` is a trait or a lifetime.
1863 TraitObject(HirVec<PolyTraitRef>, Lifetime),
1866 /// `TyKind::Infer` means the type should be inferred instead of it having been
1867 /// specified. This can appear anywhere in a type.
1869 /// Placeholder for a type that has failed to be defined.
1871 /// Placeholder for C-variadic arguments. We "spoof" the `VaList` created
1872 /// from the variadic arguments. This type is only valid up to typeck.
1876 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1877 pub struct InlineAsmOutput {
1878 pub constraint: Symbol,
1880 pub is_indirect: bool,
1884 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1885 pub struct InlineAsm {
1887 pub asm_str_style: StrStyle,
1888 pub outputs: HirVec<InlineAsmOutput>,
1889 pub inputs: HirVec<Symbol>,
1890 pub clobbers: HirVec<Symbol>,
1892 pub alignstack: bool,
1893 pub dialect: AsmDialect,
1894 #[stable_hasher(ignore)] // This is used for error reporting
1895 pub ctxt: SyntaxContext,
1898 /// Represents an argument in a function header.
1899 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1903 pub source: ArgSource,
1907 /// Returns the pattern representing the original binding for this argument.
1908 pub fn original_pat(&self) -> &P<Pat> {
1909 match &self.source {
1910 ArgSource::Normal => &self.pat,
1911 ArgSource::AsyncFn(pat) => &pat,
1916 /// Represents the source of an argument in a function header.
1917 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1918 pub enum ArgSource {
1919 /// Argument as specified by the user.
1921 /// Generated argument from `async fn` lowering, contains the original binding pattern.
1925 /// Represents the header (not the body) of a function declaration.
1926 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1928 pub inputs: HirVec<Ty>,
1929 pub output: FunctionRetTy,
1930 pub c_variadic: bool,
1931 /// Does the function have an implicit self?
1932 pub implicit_self: ImplicitSelfKind,
1935 /// Represents what type of implicit self a function has, if any.
1936 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, HashStable)]
1937 pub enum ImplicitSelfKind {
1938 /// Represents a `fn x(self);`.
1940 /// Represents a `fn x(mut self);`.
1942 /// Represents a `fn x(&self);`.
1944 /// Represents a `fn x(&mut self);`.
1946 /// Represents when a function does not have a self argument or
1947 /// when a function has a `self: X` argument.
1951 impl ImplicitSelfKind {
1952 /// Does this represent an implicit self?
1953 pub fn has_implicit_self(&self) -> bool {
1955 ImplicitSelfKind::None => false,
1961 /// Is the trait definition an auto trait?
1962 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1968 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, HashStable,
1969 Ord, RustcEncodable, RustcDecodable, Debug)]
1975 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, HashStable,
1976 RustcEncodable, RustcDecodable, Hash, Debug)]
1982 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1983 pub enum Constness {
1988 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1989 pub enum Defaultness {
1990 Default { has_value: bool },
1995 pub fn has_value(&self) -> bool {
1997 Defaultness::Default { has_value, .. } => has_value,
1998 Defaultness::Final => true,
2002 pub fn is_final(&self) -> bool {
2003 *self == Defaultness::Final
2006 pub fn is_default(&self) -> bool {
2008 Defaultness::Default { .. } => true,
2014 impl fmt::Display for Unsafety {
2015 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2016 fmt::Display::fmt(match *self {
2017 Unsafety::Normal => "normal",
2018 Unsafety::Unsafe => "unsafe",
2024 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2025 pub enum ImplPolarity {
2026 /// `impl Trait for Type`
2028 /// `impl !Trait for Type`
2032 impl fmt::Debug for ImplPolarity {
2033 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2035 ImplPolarity::Positive => "positive".fmt(f),
2036 ImplPolarity::Negative => "negative".fmt(f),
2042 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2043 pub enum FunctionRetTy {
2044 /// Return type is not specified.
2046 /// Functions default to `()` and
2047 /// closures default to inference. Span points to where return
2048 /// type would be inserted.
2049 DefaultReturn(Span),
2050 /// Everything else.
2054 impl fmt::Display for FunctionRetTy {
2055 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2057 Return(ref ty) => print::to_string(print::NO_ANN, |s| s.print_type(ty)).fmt(f),
2058 DefaultReturn(_) => "()".fmt(f),
2063 impl FunctionRetTy {
2064 pub fn span(&self) -> Span {
2066 DefaultReturn(span) => span,
2067 Return(ref ty) => ty.span,
2072 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2074 /// A span from the first token past `{` to the last token until `}`.
2075 /// For `mod foo;`, the inner span ranges from the first token
2076 /// to the last token in the external file.
2078 pub item_ids: HirVec<ItemId>,
2081 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2082 pub struct ForeignMod {
2084 pub items: HirVec<ForeignItem>,
2087 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2088 pub struct GlobalAsm {
2090 #[stable_hasher(ignore)] // This is used for error reporting
2091 pub ctxt: SyntaxContext,
2094 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2095 pub struct EnumDef {
2096 pub variants: HirVec<Variant>,
2099 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2100 pub struct VariantKind {
2101 /// Name of the variant.
2102 #[stable_hasher(project(name))]
2104 /// Attributes of the variant.
2105 pub attrs: HirVec<Attribute>,
2106 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2108 /// Fields and constructor id of the variant.
2109 pub data: VariantData,
2110 /// Explicit discriminant (e.g., `Foo = 1`).
2111 pub disr_expr: Option<AnonConst>,
2114 pub type Variant = Spanned<VariantKind>;
2116 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2118 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2119 /// Also produced for each element of a list `use`, e.g.
2120 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2123 /// Glob import, e.g., `use foo::*`.
2126 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2127 /// an additional `use foo::{}` for performing checks such as
2128 /// unstable feature gating. May be removed in the future.
2132 /// TraitRef's appear in impls.
2134 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
2135 /// that the ref_id is for. Note that ref_id's value is not the NodeId of the
2136 /// trait being referred to but just a unique NodeId that serves as a key
2137 /// within the DefMap.
2138 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2139 pub struct TraitRef {
2141 // Don't hash the ref_id. It is tracked via the thing it is used to access
2142 #[stable_hasher(ignore)]
2143 pub hir_ref_id: HirId,
2147 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2148 pub fn trait_def_id(&self) -> DefId {
2149 match self.path.def {
2150 Def::Trait(did) => did,
2151 Def::TraitAlias(did) => did,
2155 _ => unreachable!(),
2160 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2161 pub struct PolyTraitRef {
2162 /// The `'a` in `<'a> Foo<&'a T>`.
2163 pub bound_generic_params: HirVec<GenericParam>,
2165 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2166 pub trait_ref: TraitRef,
2171 pub type Visibility = Spanned<VisibilityKind>;
2173 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2174 pub enum VisibilityKind {
2177 Restricted { path: P<Path>, hir_id: HirId },
2181 impl VisibilityKind {
2182 pub fn is_pub(&self) -> bool {
2184 VisibilityKind::Public => true,
2189 pub fn is_pub_restricted(&self) -> bool {
2191 VisibilityKind::Public |
2192 VisibilityKind::Inherited => false,
2193 VisibilityKind::Crate(..) |
2194 VisibilityKind::Restricted { .. } => true,
2198 pub fn descr(&self) -> &'static str {
2200 VisibilityKind::Public => "public",
2201 VisibilityKind::Inherited => "private",
2202 VisibilityKind::Crate(..) => "crate-visible",
2203 VisibilityKind::Restricted { .. } => "restricted",
2208 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2209 pub struct StructField {
2211 #[stable_hasher(project(name))]
2213 pub vis: Visibility,
2216 pub attrs: HirVec<Attribute>,
2220 // Still necessary in couple of places
2221 pub fn is_positional(&self) -> bool {
2222 let first = self.ident.as_str().as_bytes()[0];
2223 first >= b'0' && first <= b'9'
2227 /// Fields and constructor ids of enum variants and structs
2228 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2229 pub enum VariantData {
2232 /// e.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2233 Struct(HirVec<StructField>, /* recovered */ bool),
2236 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2237 Tuple(HirVec<StructField>, HirId),
2240 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2245 /// Return the fields of this variant.
2246 pub fn fields(&self) -> &[StructField] {
2248 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2253 /// Return the `HirId` of this variant's constructor, if it has one.
2254 pub fn ctor_hir_id(&self) -> Option<HirId> {
2256 VariantData::Struct(_, _) => None,
2257 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2262 // The bodies for items are stored "out of line", in a separate
2263 // hashmap in the `Crate`. Here we just record the node-id of the item
2264 // so it can fetched later.
2265 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2272 /// The name might be a dummy name in case of anonymous items
2273 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2277 pub attrs: HirVec<Attribute>,
2279 pub vis: Visibility,
2283 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, HashStable)]
2284 pub struct FnHeader {
2285 pub unsafety: Unsafety,
2286 pub constness: Constness,
2287 pub asyncness: IsAsync,
2291 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2293 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2295 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2296 ExternCrate(Option<Name>),
2298 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2302 /// `use foo::bar::baz;` (with `as baz` implicitly on the right)
2303 Use(P<Path>, UseKind),
2306 Static(P<Ty>, Mutability, BodyId),
2308 Const(P<Ty>, BodyId),
2309 /// A function declaration
2310 Fn(P<FnDecl>, FnHeader, Generics, BodyId),
2313 /// An external module
2314 ForeignMod(ForeignMod),
2315 /// Module-level inline assembly (from global_asm!)
2316 GlobalAsm(P<GlobalAsm>),
2317 /// A type alias, e.g., `type Foo = Bar<u8>`
2318 Ty(P<Ty>, Generics),
2319 /// An existential type definition, e.g., `existential type Foo: Bar;`
2320 Existential(ExistTy),
2321 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`
2322 Enum(EnumDef, Generics),
2323 /// A struct definition, e.g., `struct Foo<A> {x: A}`
2324 Struct(VariantData, Generics),
2325 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`
2326 Union(VariantData, Generics),
2327 /// Represents a Trait Declaration
2328 Trait(IsAuto, Unsafety, Generics, GenericBounds, HirVec<TraitItemRef>),
2329 /// Represents a Trait Alias Declaration
2330 TraitAlias(Generics, GenericBounds),
2332 /// An implementation, eg `impl<A> Trait for Foo { .. }`
2337 Option<TraitRef>, // (optional) trait this impl implements
2339 HirVec<ImplItemRef>),
2343 pub fn descriptive_variant(&self) -> &str {
2345 ItemKind::ExternCrate(..) => "extern crate",
2346 ItemKind::Use(..) => "use",
2347 ItemKind::Static(..) => "static item",
2348 ItemKind::Const(..) => "constant item",
2349 ItemKind::Fn(..) => "function",
2350 ItemKind::Mod(..) => "module",
2351 ItemKind::ForeignMod(..) => "foreign module",
2352 ItemKind::GlobalAsm(..) => "global asm",
2353 ItemKind::Ty(..) => "type alias",
2354 ItemKind::Existential(..) => "existential type",
2355 ItemKind::Enum(..) => "enum",
2356 ItemKind::Struct(..) => "struct",
2357 ItemKind::Union(..) => "union",
2358 ItemKind::Trait(..) => "trait",
2359 ItemKind::TraitAlias(..) => "trait alias",
2360 ItemKind::Impl(..) => "impl",
2364 pub fn adt_kind(&self) -> Option<AdtKind> {
2366 ItemKind::Struct(..) => Some(AdtKind::Struct),
2367 ItemKind::Union(..) => Some(AdtKind::Union),
2368 ItemKind::Enum(..) => Some(AdtKind::Enum),
2373 pub fn generics(&self) -> Option<&Generics> {
2375 ItemKind::Fn(_, _, ref generics, _) |
2376 ItemKind::Ty(_, ref generics) |
2377 ItemKind::Existential(ExistTy { ref generics, impl_trait_fn: None, .. }) |
2378 ItemKind::Enum(_, ref generics) |
2379 ItemKind::Struct(_, ref generics) |
2380 ItemKind::Union(_, ref generics) |
2381 ItemKind::Trait(_, _, ref generics, _, _) |
2382 ItemKind::Impl(_, _, _, ref generics, _, _, _)=> generics,
2388 /// A reference from an trait to one of its associated items. This
2389 /// contains the item's id, naturally, but also the item's name and
2390 /// some other high-level details (like whether it is an associated
2391 /// type or method, and whether it is public). This allows other
2392 /// passes to find the impl they want without loading the ID (which
2393 /// means fewer edges in the incremental compilation graph).
2394 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2395 pub struct TraitItemRef {
2396 pub id: TraitItemId,
2397 #[stable_hasher(project(name))]
2399 pub kind: AssociatedItemKind,
2401 pub defaultness: Defaultness,
2404 /// A reference from an impl to one of its associated items. This
2405 /// contains the item's ID, naturally, but also the item's name and
2406 /// some other high-level details (like whether it is an associated
2407 /// type or method, and whether it is public). This allows other
2408 /// passes to find the impl they want without loading the ID (which
2409 /// means fewer edges in the incremental compilation graph).
2410 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2411 pub struct ImplItemRef {
2413 #[stable_hasher(project(name))]
2415 pub kind: AssociatedItemKind,
2417 pub vis: Visibility,
2418 pub defaultness: Defaultness,
2421 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2422 pub enum AssociatedItemKind {
2424 Method { has_self: bool },
2429 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2430 pub struct ForeignItem {
2431 #[stable_hasher(project(name))]
2433 pub attrs: HirVec<Attribute>,
2434 pub node: ForeignItemKind,
2437 pub vis: Visibility,
2440 /// An item within an `extern` block.
2441 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2442 pub enum ForeignItemKind {
2443 /// A foreign function.
2444 Fn(P<FnDecl>, HirVec<Ident>, Generics),
2445 /// A foreign static item (`static ext: u8`).
2446 Static(P<Ty>, Mutability),
2451 impl ForeignItemKind {
2452 pub fn descriptive_variant(&self) -> &str {
2454 ForeignItemKind::Fn(..) => "foreign function",
2455 ForeignItemKind::Static(..) => "foreign static item",
2456 ForeignItemKind::Type => "foreign type",
2461 /// A free variable referred to in a function.
2462 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable, HashStable)]
2463 pub struct Freevar<Id = HirId> {
2464 /// The variable being accessed free.
2465 pub def: def::Def<Id>,
2467 // First span where it is accessed (there can be multiple).
2471 impl<Id: fmt::Debug + Copy> Freevar<Id> {
2472 pub fn map_id<R>(self, map: impl FnMut(Id) -> R) -> Freevar<R> {
2474 def: self.def.map_id(map),
2479 pub fn var_id(&self) -> Id {
2481 Def::Local(id) | Def::Upvar(id, ..) => id,
2482 _ => bug!("Freevar::var_id: bad def ({:?})", self.def)
2487 pub type FreevarMap = NodeMap<Vec<Freevar<ast::NodeId>>>;
2489 pub type CaptureModeMap = NodeMap<CaptureClause>;
2491 #[derive(Clone, Debug)]
2492 pub struct TraitCandidate {
2494 pub import_id: Option<NodeId>,
2497 // Trait method resolution
2498 pub type TraitMap = NodeMap<Vec<TraitCandidate>>;
2500 // Map from the NodeId of a glob import to a list of items which are actually
2502 pub type GlobMap = NodeMap<FxHashSet<Name>>;
2505 pub fn provide(providers: &mut Providers<'_>) {
2506 check_attr::provide(providers);
2507 providers.describe_def = map::describe_def;
2510 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
2511 pub struct CodegenFnAttrs {
2512 pub flags: CodegenFnAttrFlags,
2513 /// Parsed representation of the `#[inline]` attribute
2514 pub inline: InlineAttr,
2515 /// Parsed representation of the `#[optimize]` attribute
2516 pub optimize: OptimizeAttr,
2517 /// The `#[export_name = "..."]` attribute, indicating a custom symbol a
2518 /// function should be exported under
2519 pub export_name: Option<Symbol>,
2520 /// The `#[link_name = "..."]` attribute, indicating a custom symbol an
2521 /// imported function should be imported as. Note that `export_name`
2522 /// probably isn't set when this is set, this is for foreign items while
2523 /// `#[export_name]` is for Rust-defined functions.
2524 pub link_name: Option<Symbol>,
2525 /// The `#[target_feature(enable = "...")]` attribute and the enabled
2526 /// features (only enabled features are supported right now).
2527 pub target_features: Vec<Symbol>,
2528 /// The `#[linkage = "..."]` attribute and the value we found.
2529 pub linkage: Option<Linkage>,
2530 /// The `#[link_section = "..."]` attribute, or what executable section this
2531 /// should be placed in.
2532 pub link_section: Option<Symbol>,
2536 #[derive(RustcEncodable, RustcDecodable, HashStable)]
2537 pub struct CodegenFnAttrFlags: u32 {
2538 /// `#[cold]`: a hint to LLVM that this function, when called, is never on
2540 const COLD = 1 << 0;
2541 /// `#[allocator]`: a hint to LLVM that the pointer returned from this
2542 /// function is never null.
2543 const ALLOCATOR = 1 << 1;
2544 /// `#[unwind]`: an indicator that this function may unwind despite what
2545 /// its ABI signature may otherwise imply.
2546 const UNWIND = 1 << 2;
2547 /// `#[rust_allocator_nounwind]`, an indicator that an imported FFI
2548 /// function will never unwind. Probably obsolete by recent changes with
2549 /// #[unwind], but hasn't been removed/migrated yet
2550 const RUSTC_ALLOCATOR_NOUNWIND = 1 << 3;
2551 /// `#[naked]`: an indicator to LLVM that no function prologue/epilogue
2552 /// should be generated.
2553 const NAKED = 1 << 4;
2554 /// `#[no_mangle]`: an indicator that the function's name should be the same
2556 const NO_MANGLE = 1 << 5;
2557 /// `#[rustc_std_internal_symbol]`: an indicator that this symbol is a
2558 /// "weird symbol" for the standard library in that it has slightly
2559 /// different linkage, visibility, and reachability rules.
2560 const RUSTC_STD_INTERNAL_SYMBOL = 1 << 6;
2561 /// `#[no_debug]`: an indicator that no debugging information should be
2562 /// generated for this function by LLVM.
2563 const NO_DEBUG = 1 << 7;
2564 /// `#[thread_local]`: indicates a static is actually a thread local
2566 const THREAD_LOCAL = 1 << 8;
2567 /// `#[used]`: indicates that LLVM can't eliminate this function (but the
2569 const USED = 1 << 9;
2570 /// #[ffi_returns_twice], indicates that an extern function can return
2572 const FFI_RETURNS_TWICE = 1 << 10;
2576 impl CodegenFnAttrs {
2577 pub fn new() -> CodegenFnAttrs {
2579 flags: CodegenFnAttrFlags::empty(),
2580 inline: InlineAttr::None,
2581 optimize: OptimizeAttr::None,
2584 target_features: vec![],
2590 /// Returns `true` if `#[inline]` or `#[inline(always)]` is present.
2591 pub fn requests_inline(&self) -> bool {
2593 InlineAttr::Hint | InlineAttr::Always => true,
2594 InlineAttr::None | InlineAttr::Never => false,
2598 /// True if it looks like this symbol needs to be exported, for example:
2600 /// * `#[no_mangle]` is present
2601 /// * `#[export_name(...)]` is present
2602 /// * `#[linkage]` is present
2603 pub fn contains_extern_indicator(&self) -> bool {
2604 self.flags.contains(CodegenFnAttrFlags::NO_MANGLE) ||
2605 self.export_name.is_some() ||
2606 match self.linkage {
2607 // these are private, make sure we don't try to consider
2610 Some(Linkage::Internal) |
2611 Some(Linkage::Private) => false,
2617 #[derive(Copy, Clone, Debug)]
2618 pub enum Node<'hir> {
2620 ForeignItem(&'hir ForeignItem),
2621 TraitItem(&'hir TraitItem),
2622 ImplItem(&'hir ImplItem),
2623 Variant(&'hir Variant),
2624 Field(&'hir StructField),
2625 AnonConst(&'hir AnonConst),
2628 PathSegment(&'hir PathSegment),
2630 TraitRef(&'hir TraitRef),
2635 MacroDef(&'hir MacroDef),
2637 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
2638 /// with synthesized constructors.
2639 Ctor(&'hir VariantData),
2641 Lifetime(&'hir Lifetime),
2642 GenericParam(&'hir GenericParam),
2643 Visibility(&'hir Visibility),