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::{ParallelIterator, par_iter, Send, Sync};
34 use rustc_data_structures::thin_vec::ThinVec;
36 use serialize::{self, Encoder, Encodable, Decoder, Decodable};
37 use std::collections::{BTreeSet, BTreeMap};
40 /// HIR doesn't commit to a concrete storage type and has its own alias for a vector.
41 /// It can be `Vec`, `P<[T]>` or potentially `Box<[T]>`, or some other container with similar
42 /// behavior. Unlike AST, HIR is mostly a static structure, so we can use an owned slice instead
43 /// of `Vec` to avoid keeping extra capacity.
44 pub type HirVec<T> = P<[T]>;
46 macro_rules! hir_vec {
47 ($elem:expr; $n:expr) => (
48 $crate::hir::HirVec::from(vec![$elem; $n])
51 $crate::hir::HirVec::from(vec![$($x),*])
59 pub mod itemlikevisit;
65 /// Uniquely identifies a node in the HIR of the current crate. It is
66 /// composed of the `owner`, which is the `DefIndex` of the directly enclosing
67 /// `hir::Item`, `hir::TraitItem`, or `hir::ImplItem` (i.e., the closest "item-like"),
68 /// and the `local_id` which is unique within the given owner.
70 /// This two-level structure makes for more stable values: One can move an item
71 /// around within the source code, or add or remove stuff before it, without
72 /// the `local_id` part of the `HirId` changing, which is a very useful property in
73 /// incremental compilation where we have to persist things through changes to
75 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)]
78 pub local_id: ItemLocalId,
82 pub fn owner_def_id(self) -> DefId {
83 DefId::local(self.owner)
86 pub fn owner_local_def_id(self) -> LocalDefId {
87 LocalDefId::from_def_id(DefId::local(self.owner))
91 impl serialize::UseSpecializedEncodable for HirId {
92 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
103 impl serialize::UseSpecializedDecodable for HirId {
104 fn default_decode<D: Decoder>(d: &mut D) -> Result<HirId, D::Error> {
105 let owner = DefIndex::decode(d)?;
106 let local_id = ItemLocalId::decode(d)?;
115 impl fmt::Display for HirId {
116 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117 write!(f, "{:?}", self)
121 // hack to ensure that we don't try to access the private parts of `ItemLocalId` in this module
122 mod item_local_id_inner {
123 use rustc_data_structures::indexed_vec::Idx;
124 /// An `ItemLocalId` uniquely identifies something within a given "item-like",
125 /// that is within a hir::Item, hir::TraitItem, or hir::ImplItem. There is no
126 /// guarantee that the numerical value of a given `ItemLocalId` corresponds to
127 /// the node's position within the owning item in any way, but there is a
128 /// guarantee that the `LocalItemId`s within an owner occupy a dense range of
129 /// integers starting at zero, so a mapping that maps all or most nodes within
130 /// an "item-like" to something else can be implement by a `Vec` instead of a
131 /// tree or hash map.
133 pub struct ItemLocalId { .. }
137 pub use self::item_local_id_inner::ItemLocalId;
139 /// The `HirId` corresponding to `CRATE_NODE_ID` and `CRATE_DEF_INDEX`.
140 pub const CRATE_HIR_ID: HirId = HirId {
141 owner: CRATE_DEF_INDEX,
142 local_id: ItemLocalId::from_u32_const(0)
145 pub const DUMMY_HIR_ID: HirId = HirId {
146 owner: CRATE_DEF_INDEX,
147 local_id: DUMMY_ITEM_LOCAL_ID,
150 pub const DUMMY_ITEM_LOCAL_ID: ItemLocalId = ItemLocalId::MAX;
152 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
153 pub struct Lifetime {
157 /// Either "`'a`", referring to a named lifetime definition,
158 /// or "``" (i.e., `keywords::Invalid`), for elision placeholders.
160 /// HIR lowering inserts these placeholders in type paths that
161 /// refer to type definitions needing lifetime parameters,
162 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
163 pub name: LifetimeName,
166 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
168 /// Some user-given name like `T` or `'x`.
171 /// Synthetic name generated when user elided a lifetime in an impl header.
173 /// E.g., the lifetimes in cases like these:
175 /// impl Foo for &u32
176 /// impl Foo<'_> for u32
178 /// in that case, we rewrite to
180 /// impl<'f> Foo for &'f u32
181 /// impl<'f> Foo<'f> for u32
183 /// where `'f` is something like `Fresh(0)`. The indices are
184 /// unique per impl, but not necessarily continuous.
187 /// Indicates an illegal name was given and an error has been
188 /// repored (so we should squelch other derived errors). Occurs
189 /// when, e.g., `'_` is used in the wrong place.
194 pub fn ident(&self) -> Ident {
196 ParamName::Plain(ident) => ident,
197 ParamName::Error | ParamName::Fresh(_) => keywords::UnderscoreLifetime.ident(),
201 pub fn modern(&self) -> ParamName {
203 ParamName::Plain(ident) => ParamName::Plain(ident.modern()),
204 param_name => param_name,
209 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
210 pub enum LifetimeName {
211 /// User-given names or fresh (synthetic) names.
214 /// User wrote nothing (e.g., the lifetime in `&u32`).
217 /// Indicates an error during lowering (usually `'_` in wrong place)
218 /// that was already reported.
221 /// User wrote specifies `'_`.
224 /// User wrote `'static`.
229 pub fn ident(&self) -> Ident {
231 LifetimeName::Implicit => keywords::Invalid.ident(),
232 LifetimeName::Error => keywords::Invalid.ident(),
233 LifetimeName::Underscore => keywords::UnderscoreLifetime.ident(),
234 LifetimeName::Static => keywords::StaticLifetime.ident(),
235 LifetimeName::Param(param_name) => param_name.ident(),
239 pub fn is_elided(&self) -> bool {
241 LifetimeName::Implicit | LifetimeName::Underscore => true,
243 // It might seem surprising that `Fresh(_)` counts as
244 // *not* elided -- but this is because, as far as the code
245 // in the compiler is concerned -- `Fresh(_)` variants act
246 // equivalently to "some fresh name". They correspond to
247 // early-bound regions on an impl, in other words.
248 LifetimeName::Error | LifetimeName::Param(_) | LifetimeName::Static => false,
252 fn is_static(&self) -> bool {
253 self == &LifetimeName::Static
256 pub fn modern(&self) -> LifetimeName {
258 LifetimeName::Param(param_name) => LifetimeName::Param(param_name.modern()),
259 lifetime_name => lifetime_name,
264 impl fmt::Display for Lifetime {
265 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
266 self.name.ident().fmt(f)
270 impl fmt::Debug for Lifetime {
271 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
275 print::to_string(print::NO_ANN, |s| s.print_lifetime(self)))
280 pub fn is_elided(&self) -> bool {
281 self.name.is_elided()
284 pub fn is_static(&self) -> bool {
285 self.name.is_static()
289 /// A `Path` is essentially Rust's notion of a name; for instance,
290 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
291 /// along with a bunch of supporting information.
292 #[derive(Clone, RustcEncodable, RustcDecodable)]
295 /// The definition that the path resolved to.
297 /// The segments in the path: the things separated by `::`.
298 pub segments: HirVec<PathSegment>,
302 pub fn is_global(&self) -> bool {
303 !self.segments.is_empty() && self.segments[0].ident.name == keywords::PathRoot.name()
307 impl fmt::Debug for Path {
308 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
309 write!(f, "path({})", self)
313 impl fmt::Display for Path {
314 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
315 write!(f, "{}", print::to_string(print::NO_ANN, |s| s.print_path(self, false)))
319 /// A segment of a path: an identifier, an optional lifetime, and a set of
321 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
322 pub struct PathSegment {
323 /// The identifier portion of this path segment.
325 // `id` and `def` are optional. We currently only use these in save-analysis,
326 // any path segments without these will not have save-analysis info and
327 // therefore will not have 'jump to def' in IDEs, but otherwise will not be
328 // affected. (In general, we don't bother to get the defs for synthesized
329 // segments, only for segments which have come from the AST).
330 pub id: Option<NodeId>,
331 pub hir_id: Option<HirId>,
332 pub def: Option<Def>,
334 /// Type/lifetime parameters attached to this path. They come in
335 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
336 /// this is more than just simple syntactic sugar; the use of
337 /// parens affects the region binding rules, so we preserve the
339 pub args: Option<P<GenericArgs>>,
341 /// Whether to infer remaining type parameters, if any.
342 /// This only applies to expression and pattern paths, and
343 /// out of those only the segments with no type parameters
344 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
345 pub infer_types: bool,
349 /// Converts an identifier to the corresponding segment.
350 pub fn from_ident(ident: Ident) -> PathSegment {
364 hir_id: Option<HirId>,
375 args: if args.is_empty() {
383 // FIXME: hack required because you can't create a static
384 // `GenericArgs`, so you can't just return a `&GenericArgs`.
385 pub fn with_generic_args<F, R>(&self, f: F) -> R
386 where F: FnOnce(&GenericArgs) -> R
388 let dummy = GenericArgs::none();
389 f(if let Some(ref args) = self.args {
397 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
398 pub struct ConstArg {
399 pub value: AnonConst,
403 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
404 pub enum GenericArg {
411 pub fn span(&self) -> Span {
413 GenericArg::Lifetime(l) => l.span,
414 GenericArg::Type(t) => t.span,
415 GenericArg::Const(c) => c.span,
419 pub fn id(&self) -> HirId {
421 GenericArg::Lifetime(l) => l.hir_id,
422 GenericArg::Type(t) => t.hir_id,
423 GenericArg::Const(c) => c.value.hir_id,
428 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
429 pub struct GenericArgs {
430 /// The generic arguments for this path segment.
431 pub args: HirVec<GenericArg>,
432 /// Bindings (equality constraints) on associated types, if present.
433 /// E.g., `Foo<A = Bar>`.
434 pub bindings: HirVec<TypeBinding>,
435 /// Were arguments written in parenthesized form `Fn(T) -> U`?
436 /// This is required mostly for pretty-printing and diagnostics,
437 /// but also for changing lifetime elision rules to be "function-like".
438 pub parenthesized: bool,
442 pub fn none() -> Self {
445 bindings: HirVec::new(),
446 parenthesized: false,
450 pub fn is_empty(&self) -> bool {
451 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
454 pub fn inputs(&self) -> &[Ty] {
455 if self.parenthesized {
456 for arg in &self.args {
458 GenericArg::Lifetime(_) => {}
459 GenericArg::Type(ref ty) => {
460 if let TyKind::Tup(ref tys) = ty.node {
465 GenericArg::Const(_) => {}
469 bug!("GenericArgs::inputs: not a `Fn(T) -> U`");
472 pub fn own_counts(&self) -> GenericParamCount {
473 // We could cache this as a property of `GenericParamCount`, but
474 // the aim is to refactor this away entirely eventually and the
475 // presence of this method will be a constant reminder.
476 let mut own_counts: GenericParamCount = Default::default();
478 for arg in &self.args {
480 GenericArg::Lifetime(_) => own_counts.lifetimes += 1,
481 GenericArg::Type(_) => own_counts.types += 1,
482 GenericArg::Const(_) => own_counts.consts += 1,
490 /// A modifier on a bound, currently this is only used for `?Sized`, where the
491 /// modifier is `Maybe`. Negative bounds should also be handled here.
492 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
493 pub enum TraitBoundModifier {
498 /// The AST represents all type param bounds as types.
499 /// `typeck::collect::compute_bounds` matches these against
500 /// the "special" built-in traits (see `middle::lang_items`) and
501 /// detects `Copy`, `Send` and `Sync`.
502 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
503 pub enum GenericBound {
504 Trait(PolyTraitRef, TraitBoundModifier),
509 pub fn span(&self) -> Span {
511 &GenericBound::Trait(ref t, ..) => t.span,
512 &GenericBound::Outlives(ref l) => l.span,
517 pub type GenericBounds = HirVec<GenericBound>;
519 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
520 pub enum LifetimeParamKind {
521 // Indicates that the lifetime definition was explicitly declared (e.g., in
522 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
525 // Indicates that the lifetime definition was synthetically added
526 // as a result of an in-band lifetime usage (e.g., in
527 // `fn foo(x: &'a u8) -> &'a u8 { x }`).
530 // Indication that the lifetime was elided (e.g., in both cases in
531 // `fn foo(x: &u8) -> &'_ u8 { x }`).
534 // Indication that the lifetime name was somehow in error.
538 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
539 pub enum GenericParamKind {
540 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
542 kind: LifetimeParamKind,
545 default: Option<P<Ty>>,
546 synthetic: Option<SyntheticTyParamKind>,
553 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
554 pub struct GenericParam {
557 pub attrs: HirVec<Attribute>,
558 pub bounds: GenericBounds,
560 pub pure_wrt_drop: bool,
562 pub kind: GenericParamKind,
566 pub struct GenericParamCount {
567 pub lifetimes: usize,
572 /// Represents lifetimes and type parameters attached to a declaration
573 /// of a function, enum, trait, etc.
574 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
575 pub struct Generics {
576 pub params: HirVec<GenericParam>,
577 pub where_clause: WhereClause,
582 pub fn empty() -> Generics {
584 params: HirVec::new(),
585 where_clause: WhereClause {
586 hir_id: DUMMY_HIR_ID,
587 predicates: HirVec::new(),
593 pub fn own_counts(&self) -> GenericParamCount {
594 // We could cache this as a property of `GenericParamCount`, but
595 // the aim is to refactor this away entirely eventually and the
596 // presence of this method will be a constant reminder.
597 let mut own_counts: GenericParamCount = Default::default();
599 for param in &self.params {
601 GenericParamKind::Lifetime { .. } => own_counts.lifetimes += 1,
602 GenericParamKind::Type { .. } => own_counts.types += 1,
603 GenericParamKind::Const { .. } => own_counts.consts += 1,
610 pub fn get_named(&self, name: &InternedString) -> Option<&GenericParam> {
611 for param in &self.params {
612 if *name == param.name.ident().as_interned_str() {
620 /// Synthetic type parameters are converted to another form during lowering; this allows
621 /// us to track the original form they had, and is useful for error messages.
622 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
623 pub enum SyntheticTyParamKind {
627 /// A where-clause in a definition.
628 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
629 pub struct WhereClause {
631 pub predicates: HirVec<WherePredicate>,
635 pub fn span(&self) -> Option<Span> {
636 self.predicates.iter().map(|predicate| predicate.span())
637 .fold(None, |acc, i| match (acc, i) {
638 (None, i) => Some(i),
646 /// A single predicate in a where-clause.
647 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
648 pub enum WherePredicate {
649 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
650 BoundPredicate(WhereBoundPredicate),
651 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
652 RegionPredicate(WhereRegionPredicate),
653 /// An equality predicate (unsupported).
654 EqPredicate(WhereEqPredicate),
657 impl WherePredicate {
658 pub fn span(&self) -> Span {
660 &WherePredicate::BoundPredicate(ref p) => p.span,
661 &WherePredicate::RegionPredicate(ref p) => p.span,
662 &WherePredicate::EqPredicate(ref p) => p.span,
667 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
668 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
669 pub struct WhereBoundPredicate {
671 /// Any generics from a `for` binding.
672 pub bound_generic_params: HirVec<GenericParam>,
673 /// The type being bounded.
674 pub bounded_ty: P<Ty>,
675 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
676 pub bounds: GenericBounds,
679 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
680 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
681 pub struct WhereRegionPredicate {
683 pub lifetime: Lifetime,
684 pub bounds: GenericBounds,
687 /// An equality predicate (e.g., `T = int`); currently unsupported.
688 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
689 pub struct WhereEqPredicate {
696 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
697 pub struct ModuleItems {
698 // Use BTreeSets here so items are in the same order as in the
699 // list of all items in Crate
700 pub items: BTreeSet<NodeId>,
701 pub trait_items: BTreeSet<TraitItemId>,
702 pub impl_items: BTreeSet<ImplItemId>,
705 /// The top-level data structure that stores the entire contents of
706 /// the crate currently being compiled.
708 /// For more details, see the [rustc guide].
710 /// [rustc guide]: https://rust-lang.github.io/rustc-guide/hir.html
711 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
714 pub attrs: HirVec<Attribute>,
716 pub exported_macros: HirVec<MacroDef>,
718 // N.B., we use a BTreeMap here so that `visit_all_items` iterates
719 // over the ids in increasing order. In principle it should not
720 // matter what order we visit things in, but in *practice* it
721 // does, because it can affect the order in which errors are
722 // detected, which in turn can make compile-fail tests yield
723 // slightly different results.
724 pub items: BTreeMap<NodeId, Item>,
726 pub trait_items: BTreeMap<TraitItemId, TraitItem>,
727 pub impl_items: BTreeMap<ImplItemId, ImplItem>,
728 pub bodies: BTreeMap<BodyId, Body>,
729 pub trait_impls: BTreeMap<DefId, Vec<NodeId>>,
730 pub trait_auto_impl: BTreeMap<DefId, NodeId>,
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: NodeId) -> &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_iter(&self.items).for_each(|(_, item)| {
786 visitor.visit_item(item);
789 par_iter(&self.trait_items).for_each(|(_, trait_item)| {
790 visitor.visit_trait_item(trait_item);
793 par_iter(&self.impl_items).for_each(|(_, 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)]
808 pub struct MacroDef {
811 pub attrs: HirVec<Attribute>,
814 pub body: TokenStream,
818 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
820 /// Statements in a block.
821 pub stmts: HirVec<Stmt>,
822 /// An expression at the end of the block
823 /// without a semicolon, if any.
824 pub expr: Option<P<Expr>>,
826 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
827 pub rules: BlockCheckMode,
829 /// If true, then there may exist `break 'a` values that aim to
830 /// break out of this block early.
831 /// Used by `'label: {}` blocks and by `catch` statements.
832 pub targeted_by_break: bool,
835 #[derive(Clone, RustcEncodable, RustcDecodable)]
843 impl fmt::Debug for Pat {
844 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
845 write!(f, "pat({}: {})", self.id,
846 print::to_string(print::NO_ANN, |s| s.print_pat(self)))
851 // FIXME(#19596) this is a workaround, but there should be a better way
852 fn walk_<G>(&self, it: &mut G) -> bool
853 where G: FnMut(&Pat) -> bool
860 PatKind::Binding(.., Some(ref p)) => p.walk_(it),
861 PatKind::Struct(_, ref fields, _) => {
862 fields.iter().all(|field| field.node.pat.walk_(it))
864 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
865 s.iter().all(|p| p.walk_(it))
867 PatKind::Box(ref s) | PatKind::Ref(ref s, _) => {
870 PatKind::Slice(ref before, ref slice, ref after) => {
874 .all(|p| p.walk_(it))
879 PatKind::Binding(..) |
880 PatKind::Path(_) => {
886 pub fn walk<F>(&self, mut it: F) -> bool
887 where F: FnMut(&Pat) -> bool
893 /// A single field in a struct pattern.
895 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
896 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
897 /// except `is_shorthand` is true.
898 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
899 pub struct FieldPat {
902 /// The identifier for the field.
904 /// The pattern the field is destructured to.
906 pub is_shorthand: bool,
909 /// Explicit binding annotations given in the HIR for a binding. Note
910 /// that this is not the final binding *mode* that we infer after type
912 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
913 pub enum BindingAnnotation {
914 /// No binding annotation given: this means that the final binding mode
915 /// will depend on whether we have skipped through a `&` reference
916 /// when matching. For example, the `x` in `Some(x)` will have binding
917 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
918 /// ultimately be inferred to be by-reference.
920 /// Note that implicit reference skipping is not implemented yet (#42640).
923 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
926 /// Annotated as `ref`, like `ref x`
929 /// Annotated as `ref mut x`.
933 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
939 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
941 /// Represents a wildcard pattern (i.e., `_`).
944 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
945 /// The `NodeId` is the canonical ID for the variable being bound,
946 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
947 /// which is the pattern ID of the first `x`.
948 Binding(BindingAnnotation, NodeId, HirId, Ident, Option<P<Pat>>),
950 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
951 /// The `bool` is `true` in the presence of a `..`.
952 Struct(QPath, HirVec<Spanned<FieldPat>>, bool),
954 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
955 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
956 /// `0 <= position <= subpats.len()`
957 TupleStruct(QPath, HirVec<P<Pat>>, Option<usize>),
959 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
962 /// A tuple pattern (e.g., `(a, b)`).
963 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
964 /// `0 <= position <= subpats.len()`
965 Tuple(HirVec<P<Pat>>, Option<usize>),
970 /// A reference pattern (e.g., `&mut (a, b)`).
971 Ref(P<Pat>, Mutability),
976 /// A range pattern (e.g., `1...2` or `1..2`).
977 Range(P<Expr>, P<Expr>, RangeEnd),
979 /// `[a, b, ..i, y, z]` is represented as:
980 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`.
981 Slice(HirVec<P<Pat>>, Option<P<Pat>>, HirVec<P<Pat>>),
984 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
985 pub enum Mutability {
991 /// Returns `MutMutable` only if both arguments are mutable.
992 pub fn and(self, other: Self) -> Self {
995 MutImmutable => MutImmutable,
1000 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, Hash)]
1001 pub enum BinOpKind {
1002 /// The `+` operator (addition).
1004 /// The `-` operator (subtraction).
1006 /// The `*` operator (multiplication).
1008 /// The `/` operator (division).
1010 /// The `%` operator (modulus).
1012 /// The `&&` operator (logical and).
1014 /// The `||` operator (logical or).
1016 /// The `^` operator (bitwise xor).
1018 /// The `&` operator (bitwise and).
1020 /// The `|` operator (bitwise or).
1022 /// The `<<` operator (shift left).
1024 /// The `>>` operator (shift right).
1026 /// The `==` operator (equality).
1028 /// The `<` operator (less than).
1030 /// The `<=` operator (less than or equal to).
1032 /// The `!=` operator (not equal to).
1034 /// The `>=` operator (greater than or equal to).
1036 /// The `>` operator (greater than).
1041 pub fn as_str(self) -> &'static str {
1043 BinOpKind::Add => "+",
1044 BinOpKind::Sub => "-",
1045 BinOpKind::Mul => "*",
1046 BinOpKind::Div => "/",
1047 BinOpKind::Rem => "%",
1048 BinOpKind::And => "&&",
1049 BinOpKind::Or => "||",
1050 BinOpKind::BitXor => "^",
1051 BinOpKind::BitAnd => "&",
1052 BinOpKind::BitOr => "|",
1053 BinOpKind::Shl => "<<",
1054 BinOpKind::Shr => ">>",
1055 BinOpKind::Eq => "==",
1056 BinOpKind::Lt => "<",
1057 BinOpKind::Le => "<=",
1058 BinOpKind::Ne => "!=",
1059 BinOpKind::Ge => ">=",
1060 BinOpKind::Gt => ">",
1064 pub fn is_lazy(self) -> bool {
1066 BinOpKind::And | BinOpKind::Or => true,
1071 pub fn is_shift(self) -> bool {
1073 BinOpKind::Shl | BinOpKind::Shr => true,
1078 pub fn is_comparison(self) -> bool {
1085 BinOpKind::Ge => true,
1097 BinOpKind::Shr => false,
1101 /// Returns `true` if the binary operator takes its arguments by value.
1102 pub fn is_by_value(self) -> bool {
1103 !self.is_comparison()
1107 impl Into<ast::BinOpKind> for BinOpKind {
1108 fn into(self) -> ast::BinOpKind {
1110 BinOpKind::Add => ast::BinOpKind::Add,
1111 BinOpKind::Sub => ast::BinOpKind::Sub,
1112 BinOpKind::Mul => ast::BinOpKind::Mul,
1113 BinOpKind::Div => ast::BinOpKind::Div,
1114 BinOpKind::Rem => ast::BinOpKind::Rem,
1115 BinOpKind::And => ast::BinOpKind::And,
1116 BinOpKind::Or => ast::BinOpKind::Or,
1117 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1118 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1119 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1120 BinOpKind::Shl => ast::BinOpKind::Shl,
1121 BinOpKind::Shr => ast::BinOpKind::Shr,
1122 BinOpKind::Eq => ast::BinOpKind::Eq,
1123 BinOpKind::Lt => ast::BinOpKind::Lt,
1124 BinOpKind::Le => ast::BinOpKind::Le,
1125 BinOpKind::Ne => ast::BinOpKind::Ne,
1126 BinOpKind::Ge => ast::BinOpKind::Ge,
1127 BinOpKind::Gt => ast::BinOpKind::Gt,
1132 pub type BinOp = Spanned<BinOpKind>;
1134 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, Hash)]
1136 /// The `*` operator (deferencing).
1138 /// The `!` operator (logical negation).
1140 /// The `-` operator (negation).
1145 pub fn as_str(self) -> &'static str {
1153 /// Returns `true` if the unary operator takes its argument by value.
1154 pub fn is_by_value(self) -> bool {
1156 UnNeg | UnNot => true,
1163 #[derive(Clone, RustcEncodable, RustcDecodable)]
1171 impl fmt::Debug for Stmt {
1172 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1173 write!(f, "stmt({}: {})", self.id,
1174 print::to_string(print::NO_ANN, |s| s.print_stmt(self)))
1178 #[derive(Clone, RustcEncodable, RustcDecodable)]
1180 /// A local (`let`) binding.
1183 /// An item binding.
1186 /// An expression without a trailing semi-colon (must have unit type).
1189 /// An expression with a trailing semi-colon (may have any type).
1194 pub fn attrs(&self) -> &[Attribute] {
1196 StmtKind::Local(ref l) => &l.attrs,
1197 StmtKind::Item(_) => &[],
1198 StmtKind::Expr(ref e) |
1199 StmtKind::Semi(ref e) => &e.attrs,
1204 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1205 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1208 pub ty: Option<P<Ty>>,
1209 /// Initializer expression to set the value, if any.
1210 pub init: Option<P<Expr>>,
1214 pub attrs: ThinVec<Attribute>,
1215 pub source: LocalSource,
1218 /// Represents a single arm of a `match` expression.
1219 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1221 pub attrs: HirVec<Attribute>,
1222 pub pats: HirVec<P<Pat>>,
1223 pub guard: Option<Guard>,
1227 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1232 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1239 pub is_shorthand: bool,
1242 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1243 pub enum BlockCheckMode {
1245 UnsafeBlock(UnsafeSource),
1246 PushUnsafeBlock(UnsafeSource),
1247 PopUnsafeBlock(UnsafeSource),
1250 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1251 pub enum UnsafeSource {
1256 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1261 /// The body of a function, closure, or constant value. In the case of
1262 /// a function, the body contains not only the function body itself
1263 /// (which is an expression), but also the argument patterns, since
1264 /// those are something that the caller doesn't really care about.
1269 /// fn foo((x, y): (u32, u32)) -> u32 {
1274 /// Here, the `Body` associated with `foo()` would contain:
1276 /// - an `arguments` array containing the `(x, y)` pattern
1277 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1278 /// - `is_generator` would be false
1280 /// All bodies have an **owner**, which can be accessed via the HIR
1281 /// map using `body_owner_def_id()`.
1282 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1284 pub arguments: HirVec<Arg>,
1286 pub is_generator: bool,
1290 pub fn id(&self) -> BodyId {
1292 hir_id: self.value.hir_id,
1297 #[derive(Copy, Clone, Debug)]
1298 pub enum BodyOwnerKind {
1299 /// Functions and methods.
1305 /// Constants and associated constants.
1308 /// Initializer of a `static` item.
1312 impl BodyOwnerKind {
1313 pub fn is_fn_or_closure(self) -> bool {
1315 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1316 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1321 /// A constant (expression) that's not an item or associated item,
1322 /// but needs its own `DefId` for type-checking, const-eval, etc.
1323 /// These are usually found nested inside types (e.g., array lengths)
1324 /// or expressions (e.g., repeat counts), and also used to define
1325 /// explicit discriminant values for enum variants.
1326 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
1327 pub struct AnonConst {
1334 #[derive(Clone, RustcEncodable, RustcDecodable)]
1339 pub attrs: ThinVec<Attribute>,
1343 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1344 #[cfg(target_arch = "x86_64")]
1345 static_assert!(MEM_SIZE_OF_EXPR: std::mem::size_of::<Expr>() == 72);
1348 pub fn precedence(&self) -> ExprPrecedence {
1350 ExprKind::Box(_) => ExprPrecedence::Box,
1351 ExprKind::Array(_) => ExprPrecedence::Array,
1352 ExprKind::Call(..) => ExprPrecedence::Call,
1353 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1354 ExprKind::Tup(_) => ExprPrecedence::Tup,
1355 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1356 ExprKind::Unary(..) => ExprPrecedence::Unary,
1357 ExprKind::Lit(_) => ExprPrecedence::Lit,
1358 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1359 ExprKind::If(..) => ExprPrecedence::If,
1360 ExprKind::While(..) => ExprPrecedence::While,
1361 ExprKind::Loop(..) => ExprPrecedence::Loop,
1362 ExprKind::Match(..) => ExprPrecedence::Match,
1363 ExprKind::Closure(..) => ExprPrecedence::Closure,
1364 ExprKind::Block(..) => ExprPrecedence::Block,
1365 ExprKind::Assign(..) => ExprPrecedence::Assign,
1366 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1367 ExprKind::Field(..) => ExprPrecedence::Field,
1368 ExprKind::Index(..) => ExprPrecedence::Index,
1369 ExprKind::Path(..) => ExprPrecedence::Path,
1370 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1371 ExprKind::Break(..) => ExprPrecedence::Break,
1372 ExprKind::Continue(..) => ExprPrecedence::Continue,
1373 ExprKind::Ret(..) => ExprPrecedence::Ret,
1374 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1375 ExprKind::Struct(..) => ExprPrecedence::Struct,
1376 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1377 ExprKind::Yield(..) => ExprPrecedence::Yield,
1378 ExprKind::Err => ExprPrecedence::Err,
1382 pub fn is_place_expr(&self) -> bool {
1384 ExprKind::Path(QPath::Resolved(_, ref path)) => {
1386 Def::Local(..) | Def::Upvar(..) | Def::Static(..) | Def::Err => true,
1391 ExprKind::Type(ref e, _) => {
1395 ExprKind::Unary(UnDeref, _) |
1396 ExprKind::Field(..) |
1397 ExprKind::Index(..) => {
1401 // Partially qualified paths in expressions can only legally
1402 // refer to associated items which are always rvalues.
1403 ExprKind::Path(QPath::TypeRelative(..)) |
1405 ExprKind::Call(..) |
1406 ExprKind::MethodCall(..) |
1407 ExprKind::Struct(..) |
1410 ExprKind::Match(..) |
1411 ExprKind::Closure(..) |
1412 ExprKind::Block(..) |
1413 ExprKind::Repeat(..) |
1414 ExprKind::Array(..) |
1415 ExprKind::Break(..) |
1416 ExprKind::Continue(..) |
1418 ExprKind::While(..) |
1419 ExprKind::Loop(..) |
1420 ExprKind::Assign(..) |
1421 ExprKind::InlineAsm(..) |
1422 ExprKind::AssignOp(..) |
1424 ExprKind::Unary(..) |
1426 ExprKind::AddrOf(..) |
1427 ExprKind::Binary(..) |
1428 ExprKind::Yield(..) |
1429 ExprKind::Cast(..) |
1437 impl fmt::Debug for Expr {
1438 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1439 write!(f, "expr({}: {})", self.id,
1440 print::to_string(print::NO_ANN, |s| s.print_expr(self)))
1444 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1446 /// A `box x` expression.
1448 /// An array (e.g., `[a, b, c, d]`).
1449 Array(HirVec<Expr>),
1450 /// A function call.
1452 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1453 /// and the second field is the list of arguments.
1454 /// This also represents calling the constructor of
1455 /// tuple-like ADTs such as tuple structs and enum variants.
1456 Call(P<Expr>, HirVec<Expr>),
1457 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1459 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1460 /// (within the angle brackets).
1461 /// The first element of the vector of `Expr`s is the expression that evaluates
1462 /// to the object on which the method is being called on (the receiver),
1463 /// and the remaining elements are the rest of the arguments.
1464 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1465 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1466 MethodCall(P<PathSegment>, Span, HirVec<Expr>),
1467 /// A tuple (e.g., `(a, b, c ,d)`).
1469 /// A binary operation (e.g., `a + b`, `a * b`).
1470 Binary(BinOp, P<Expr>, P<Expr>),
1471 /// A unary operation (e.g., `!x`, `*x`).
1472 Unary(UnOp, P<Expr>),
1473 /// A literal (e.g., `1`, `"foo"`).
1475 /// A cast (e.g., `foo as f64`).
1476 Cast(P<Expr>, P<Ty>),
1477 /// A type reference (e.g., `Foo`).
1478 Type(P<Expr>, P<Ty>),
1479 /// An `if` block, with an optional else block.
1481 /// I.e., `if <expr> { <expr> } else { <expr> }`.
1482 If(P<Expr>, P<Expr>, Option<P<Expr>>),
1483 /// A while loop, with an optional label
1485 /// I.e., `'label: while expr { <block> }`.
1486 While(P<Expr>, P<Block>, Option<Label>),
1487 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1489 /// I.e., `'label: loop { <block> }`.
1490 Loop(P<Block>, Option<Label>, LoopSource),
1491 /// A `match` block, with a source that indicates whether or not it is
1492 /// the result of a desugaring, and if so, which kind.
1493 Match(P<Expr>, HirVec<Arm>, MatchSource),
1494 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1496 /// The final span is the span of the argument block `|...|`.
1498 /// This may also be a generator literal, indicated by the final boolean,
1499 /// in that case there is an `GeneratorClause`.
1500 Closure(CaptureClause, P<FnDecl>, BodyId, Span, Option<GeneratorMovability>),
1501 /// A block (e.g., `'label: { ... }`).
1502 Block(P<Block>, Option<Label>),
1504 /// An assignment (e.g., `a = foo()`).
1505 Assign(P<Expr>, P<Expr>),
1506 /// An assignment with an operator.
1509 AssignOp(BinOp, P<Expr>, P<Expr>),
1510 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1511 Field(P<Expr>, Ident),
1512 /// An indexing operation (`foo[2]`).
1513 Index(P<Expr>, P<Expr>),
1515 /// Path to a definition, possibly containing lifetime or type parameters.
1518 /// A referencing operation (i.e., `&a` or `&mut a`).
1519 AddrOf(Mutability, P<Expr>),
1520 /// A `break`, with an optional label to break.
1521 Break(Destination, Option<P<Expr>>),
1522 /// A `continue`, with an optional label.
1523 Continue(Destination),
1524 /// A `return`, with an optional value to be returned.
1525 Ret(Option<P<Expr>>),
1527 /// Inline assembly (from `asm!`), with its outputs and inputs.
1528 InlineAsm(P<InlineAsm>, HirVec<Expr>, HirVec<Expr>),
1530 /// A struct or struct-like variant literal expression.
1532 /// For example, `Foo {x: 1, y: 2}`, or
1533 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
1534 Struct(P<QPath>, HirVec<Field>, Option<P<Expr>>),
1536 /// An array literal constructed from one repeated element.
1538 /// For example, `[1; 5]`. The first expression is the element
1539 /// to be repeated; the second is the number of times to repeat it.
1540 Repeat(P<Expr>, AnonConst),
1542 /// A suspension point for generators (i.e., `yield <expr>`).
1545 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1549 /// Optionally `Self`-qualified value/type path or associated extension.
1550 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1552 /// Path to a definition, optionally "fully-qualified" with a `Self`
1553 /// type, if the path points to an associated item in a trait.
1555 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1556 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1557 /// even though they both have the same two-segment `Clone::clone` `Path`.
1558 Resolved(Option<P<Ty>>, P<Path>),
1560 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1561 /// Will be resolved by type-checking to an associated item.
1563 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1564 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1565 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1566 TypeRelative(P<Ty>, P<PathSegment>)
1569 /// Hints at the original code for a let statement.
1570 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1571 pub enum LocalSource {
1572 /// A `match _ { .. }`.
1574 /// A desugared `for _ in _ { .. }` loop.
1578 /// Hints at the original code for a `match _ { .. }`.
1579 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1580 pub enum MatchSource {
1581 /// A `match _ { .. }`.
1583 /// An `if let _ = _ { .. }` (optionally with `else { .. }`).
1585 contains_else_clause: bool,
1587 /// A `while let _ = _ { .. }` (which was desugared to a
1588 /// `loop { match _ { .. } }`).
1590 /// A desugared `for _ in _ { .. }` loop.
1592 /// A desugared `?` operator.
1596 /// The loop type that yielded an `ExprKind::Loop`.
1597 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1598 pub enum LoopSource {
1599 /// A `loop { .. }` loop.
1601 /// A `while let _ = _ { .. }` loop.
1603 /// A `for _ in _ { .. }` loop.
1607 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1608 pub enum LoopIdError {
1610 UnlabeledCfInWhileCondition,
1614 impl fmt::Display for LoopIdError {
1615 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1616 fmt::Display::fmt(match *self {
1617 LoopIdError::OutsideLoopScope => "not inside loop scope",
1618 LoopIdError::UnlabeledCfInWhileCondition =>
1619 "unlabeled control flow (break or continue) in while condition",
1620 LoopIdError::UnresolvedLabel => "label not found",
1625 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1626 pub struct Destination {
1627 // This is `Some(_)` iff there is an explicit user-specified `label
1628 pub label: Option<Label>,
1630 // These errors are caught and then reported during the diagnostics pass in
1631 // librustc_passes/loops.rs
1632 pub target_id: Result<NodeId, LoopIdError>,
1635 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1636 pub enum GeneratorMovability {
1641 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1642 pub enum CaptureClause {
1647 // N.B., if you change this, you'll probably want to change the corresponding
1648 // type structure in middle/ty.rs as well.
1649 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1652 pub mutbl: Mutability,
1655 /// Represents a method's signature in a trait declaration or implementation.
1656 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1657 pub struct MethodSig {
1658 pub header: FnHeader,
1659 pub decl: P<FnDecl>,
1662 // The bodies for items are stored "out of line", in a separate
1663 // hashmap in the `Crate`. Here we just record the node-id of the item
1664 // so it can fetched later.
1665 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1666 pub struct TraitItemId {
1667 pub node_id: NodeId,
1670 /// Represents an item declaration within a trait declaration,
1671 /// possibly including a default implementation. A trait item is
1672 /// either required (meaning it doesn't have an implementation, just a
1673 /// signature) or provided (meaning it has a default implementation).
1674 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1675 pub struct TraitItem {
1679 pub attrs: HirVec<Attribute>,
1680 pub generics: Generics,
1681 pub node: TraitItemKind,
1685 /// A trait method's body (or just argument names).
1686 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1687 pub enum TraitMethod {
1688 /// No default body in the trait, just a signature.
1689 Required(HirVec<Ident>),
1691 /// Both signature and body are provided in the trait.
1695 /// Represents a trait method or associated constant or type
1696 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1697 pub enum TraitItemKind {
1698 /// An associated constant with an optional value (otherwise `impl`s
1699 /// must contain a value)
1700 Const(P<Ty>, Option<BodyId>),
1701 /// A method with an optional body
1702 Method(MethodSig, TraitMethod),
1703 /// An associated type with (possibly empty) bounds and optional concrete
1705 Type(GenericBounds, Option<P<Ty>>),
1708 // The bodies for items are stored "out of line", in a separate
1709 // hashmap in the `Crate`. Here we just record the node-id of the item
1710 // so it can fetched later.
1711 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1712 pub struct ImplItemId {
1713 pub node_id: NodeId,
1716 /// Represents anything within an `impl` block
1717 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1718 pub struct ImplItem {
1722 pub vis: Visibility,
1723 pub defaultness: Defaultness,
1724 pub attrs: HirVec<Attribute>,
1725 pub generics: Generics,
1726 pub node: ImplItemKind,
1730 /// Represents different contents within `impl`s
1731 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1732 pub enum ImplItemKind {
1733 /// An associated constant of the given type, set to the constant result
1734 /// of the expression
1735 Const(P<Ty>, BodyId),
1736 /// A method implementation with the given signature and body
1737 Method(MethodSig, BodyId),
1738 /// An associated type
1740 /// An associated existential type
1741 Existential(GenericBounds),
1744 // Bind a type to an associated type: `A=Foo`.
1745 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1746 pub struct TypeBinding {
1754 #[derive(Clone, RustcEncodable, RustcDecodable)]
1761 impl fmt::Debug for Ty {
1762 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1763 write!(f, "type({})",
1764 print::to_string(print::NO_ANN, |s| s.print_type(self)))
1768 /// Not represented directly in the AST; referred to by name through a `ty_path`.
1769 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1779 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1780 pub struct BareFnTy {
1781 pub unsafety: Unsafety,
1783 pub generic_params: HirVec<GenericParam>,
1784 pub decl: P<FnDecl>,
1785 pub arg_names: HirVec<Ident>,
1788 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1789 pub struct ExistTy {
1790 pub generics: Generics,
1791 pub bounds: GenericBounds,
1792 pub impl_trait_fn: Option<DefId>,
1795 /// The various kinds of types recognized by the compiler.
1796 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1798 /// A variable length slice (i.e., `[T]`).
1800 /// A fixed length array (i.e., `[T; n]`).
1801 Array(P<Ty>, AnonConst),
1802 /// A raw pointer (i.e., `*const T` or `*mut T`).
1804 /// A reference (i.e., `&'a T` or `&'a mut T`).
1805 Rptr(Lifetime, MutTy),
1806 /// A bare function (e.g., `fn(usize) -> bool`).
1807 BareFn(P<BareFnTy>),
1808 /// The never type (`!`).
1810 /// A tuple (`(A, B, C, D,...)`).
1812 /// A path to a type definition (`module::module::...::Type`), or an
1813 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
1815 /// Type parameters may be stored in each `PathSegment`.
1817 /// A type definition itself. This is currently only used for the `existential type`
1818 /// item that `impl Trait` in return position desugars to.
1820 /// The generic argument list contains the lifetimes (and in the future possibly parameters)
1821 /// that are actually bound on the `impl Trait`.
1822 Def(ItemId, HirVec<GenericArg>),
1823 /// A trait object type `Bound1 + Bound2 + Bound3`
1824 /// where `Bound` is a trait or a lifetime.
1825 TraitObject(HirVec<PolyTraitRef>, Lifetime),
1828 /// `TyKind::Infer` means the type should be inferred instead of it having been
1829 /// specified. This can appear anywhere in a type.
1831 /// Placeholder for a type that has failed to be defined.
1835 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1836 pub struct InlineAsmOutput {
1837 pub constraint: Symbol,
1839 pub is_indirect: bool,
1843 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1844 pub struct InlineAsm {
1846 pub asm_str_style: StrStyle,
1847 pub outputs: HirVec<InlineAsmOutput>,
1848 pub inputs: HirVec<Symbol>,
1849 pub clobbers: HirVec<Symbol>,
1851 pub alignstack: bool,
1852 pub dialect: AsmDialect,
1853 pub ctxt: SyntaxContext,
1856 /// Represents an argument in a function header.
1857 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1864 /// Represents the header (not the body) of a function declaration.
1865 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1867 pub inputs: HirVec<Ty>,
1868 pub output: FunctionRetTy,
1870 /// Does the function have an implicit self?
1871 pub implicit_self: ImplicitSelfKind,
1874 /// Represents what type of implicit self a function has, if any.
1875 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
1876 pub enum ImplicitSelfKind {
1877 /// Represents a `fn x(self);`.
1879 /// Represents a `fn x(mut self);`.
1881 /// Represents a `fn x(&self);`.
1883 /// Represents a `fn x(&mut self);`.
1885 /// Represents when a function does not have a self argument or
1886 /// when a function has a `self: X` argument.
1890 impl ImplicitSelfKind {
1891 /// Does this represent an implicit self?
1892 pub fn has_implicit_self(&self) -> bool {
1894 ImplicitSelfKind::None => false,
1900 /// Is the trait definition an auto trait?
1901 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1907 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1913 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1919 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1920 pub enum Constness {
1925 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1926 pub enum Defaultness {
1927 Default { has_value: bool },
1932 pub fn has_value(&self) -> bool {
1934 Defaultness::Default { has_value, .. } => has_value,
1935 Defaultness::Final => true,
1939 pub fn is_final(&self) -> bool {
1940 *self == Defaultness::Final
1943 pub fn is_default(&self) -> bool {
1945 Defaultness::Default { .. } => true,
1951 impl fmt::Display for Unsafety {
1952 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1953 fmt::Display::fmt(match *self {
1954 Unsafety::Normal => "normal",
1955 Unsafety::Unsafe => "unsafe",
1961 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
1962 pub enum ImplPolarity {
1963 /// `impl Trait for Type`
1965 /// `impl !Trait for Type`
1969 impl fmt::Debug for ImplPolarity {
1970 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1972 ImplPolarity::Positive => "positive".fmt(f),
1973 ImplPolarity::Negative => "negative".fmt(f),
1979 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1980 pub enum FunctionRetTy {
1981 /// Return type is not specified.
1983 /// Functions default to `()` and
1984 /// closures default to inference. Span points to where return
1985 /// type would be inserted.
1986 DefaultReturn(Span),
1987 /// Everything else.
1991 impl fmt::Display for FunctionRetTy {
1992 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1994 Return(ref ty) => print::to_string(print::NO_ANN, |s| s.print_type(ty)).fmt(f),
1995 DefaultReturn(_) => "()".fmt(f),
2000 impl FunctionRetTy {
2001 pub fn span(&self) -> Span {
2003 DefaultReturn(span) => span,
2004 Return(ref ty) => ty.span,
2009 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2011 /// A span from the first token past `{` to the last token until `}`.
2012 /// For `mod foo;`, the inner span ranges from the first token
2013 /// to the last token in the external file.
2015 pub item_ids: HirVec<ItemId>,
2018 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2019 pub struct ForeignMod {
2021 pub items: HirVec<ForeignItem>,
2024 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2025 pub struct GlobalAsm {
2027 pub ctxt: SyntaxContext,
2030 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2031 pub struct EnumDef {
2032 pub variants: HirVec<Variant>,
2035 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2036 pub struct VariantKind {
2038 pub attrs: HirVec<Attribute>,
2039 pub data: VariantData,
2040 /// Explicit discriminant (e.g., `Foo = 1`).
2041 pub disr_expr: Option<AnonConst>,
2044 pub type Variant = Spanned<VariantKind>;
2046 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
2048 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2049 /// Also produced for each element of a list `use`, e.g.
2050 // `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2053 /// Glob import, e.g., `use foo::*`.
2056 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2057 /// an additional `use foo::{}` for performing checks such as
2058 /// unstable feature gating. May be removed in the future.
2062 /// TraitRef's appear in impls.
2064 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
2065 /// that the ref_id is for. Note that ref_id's value is not the NodeId of the
2066 /// trait being referred to but just a unique NodeId that serves as a key
2067 /// within the DefMap.
2068 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2069 pub struct TraitRef {
2072 pub hir_ref_id: HirId,
2076 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2077 pub fn trait_def_id(&self) -> DefId {
2078 match self.path.def {
2079 Def::Trait(did) => did,
2080 Def::TraitAlias(did) => did,
2084 _ => unreachable!(),
2089 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2090 pub struct PolyTraitRef {
2091 /// The `'a` in `<'a> Foo<&'a T>`.
2092 pub bound_generic_params: HirVec<GenericParam>,
2094 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2095 pub trait_ref: TraitRef,
2100 pub type Visibility = Spanned<VisibilityKind>;
2102 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2103 pub enum VisibilityKind {
2106 Restricted { path: P<Path>, id: NodeId, hir_id: HirId },
2110 impl VisibilityKind {
2111 pub fn is_pub(&self) -> bool {
2113 VisibilityKind::Public => true,
2118 pub fn is_pub_restricted(&self) -> bool {
2120 VisibilityKind::Public |
2121 VisibilityKind::Inherited => false,
2122 VisibilityKind::Crate(..) |
2123 VisibilityKind::Restricted { .. } => true,
2127 pub fn descr(&self) -> &'static str {
2129 VisibilityKind::Public => "public",
2130 VisibilityKind::Inherited => "private",
2131 VisibilityKind::Crate(..) => "crate-visible",
2132 VisibilityKind::Restricted { .. } => "restricted",
2137 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2138 pub struct StructField {
2141 pub vis: Visibility,
2145 pub attrs: HirVec<Attribute>,
2149 // Still necessary in couple of places
2150 pub fn is_positional(&self) -> bool {
2151 let first = self.ident.as_str().as_bytes()[0];
2152 first >= b'0' && first <= b'9'
2156 /// Fields and Ids of enum variants and structs
2158 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
2159 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
2160 /// One shared Id can be successfully used for these two purposes.
2161 /// Id of the whole enum lives in `Item`.
2163 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
2164 /// used for `Struct`-structs (but still present). Structures don't have an analogue of "Id of
2165 /// the variant itself" from enum variants.
2166 /// Id of the whole struct lives in `Item`.
2167 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2168 pub enum VariantData {
2169 Struct(HirVec<StructField>, NodeId, HirId),
2170 Tuple(HirVec<StructField>, NodeId, HirId),
2171 Unit(NodeId, HirId),
2175 pub fn fields(&self) -> &[StructField] {
2177 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2181 pub fn id(&self) -> NodeId {
2183 VariantData::Struct(_, id, ..)
2184 | VariantData::Tuple(_, id, ..)
2185 | VariantData::Unit(id, ..) => id,
2188 pub fn hir_id(&self) -> HirId {
2190 VariantData::Struct(_, _, hir_id)
2191 | VariantData::Tuple(_, _, hir_id)
2192 | VariantData::Unit(_, hir_id) => hir_id,
2195 pub fn is_struct(&self) -> bool {
2196 if let VariantData::Struct(..) = *self {
2202 pub fn is_tuple(&self) -> bool {
2203 if let VariantData::Tuple(..) = *self {
2209 pub fn is_unit(&self) -> bool {
2210 if let VariantData::Unit(..) = *self {
2218 // The bodies for items are stored "out of line", in a separate
2219 // hashmap in the `Crate`. Here we just record the node-id of the item
2220 // so it can fetched later.
2221 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2228 /// The name might be a dummy name in case of anonymous items
2229 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2234 pub attrs: HirVec<Attribute>,
2236 pub vis: Visibility,
2240 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2241 pub struct FnHeader {
2242 pub unsafety: Unsafety,
2243 pub constness: Constness,
2244 pub asyncness: IsAsync,
2248 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2250 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2252 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2253 ExternCrate(Option<Name>),
2255 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2259 /// `use foo::bar::baz;` (with `as baz` implicitly on the right)
2260 Use(P<Path>, UseKind),
2263 Static(P<Ty>, Mutability, BodyId),
2265 Const(P<Ty>, BodyId),
2266 /// A function declaration
2267 Fn(P<FnDecl>, FnHeader, Generics, BodyId),
2270 /// An external module
2271 ForeignMod(ForeignMod),
2272 /// Module-level inline assembly (from global_asm!)
2273 GlobalAsm(P<GlobalAsm>),
2274 /// A type alias, e.g., `type Foo = Bar<u8>`
2275 Ty(P<Ty>, Generics),
2276 /// An existential type definition, e.g., `existential type Foo: Bar;`
2277 Existential(ExistTy),
2278 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`
2279 Enum(EnumDef, Generics),
2280 /// A struct definition, e.g., `struct Foo<A> {x: A}`
2281 Struct(VariantData, Generics),
2282 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`
2283 Union(VariantData, Generics),
2284 /// Represents a Trait Declaration
2285 Trait(IsAuto, Unsafety, Generics, GenericBounds, HirVec<TraitItemRef>),
2286 /// Represents a Trait Alias Declaration
2287 TraitAlias(Generics, GenericBounds),
2289 /// An implementation, eg `impl<A> Trait for Foo { .. }`
2294 Option<TraitRef>, // (optional) trait this impl implements
2296 HirVec<ImplItemRef>),
2300 pub fn descriptive_variant(&self) -> &str {
2302 ItemKind::ExternCrate(..) => "extern crate",
2303 ItemKind::Use(..) => "use",
2304 ItemKind::Static(..) => "static item",
2305 ItemKind::Const(..) => "constant item",
2306 ItemKind::Fn(..) => "function",
2307 ItemKind::Mod(..) => "module",
2308 ItemKind::ForeignMod(..) => "foreign module",
2309 ItemKind::GlobalAsm(..) => "global asm",
2310 ItemKind::Ty(..) => "type alias",
2311 ItemKind::Existential(..) => "existential type",
2312 ItemKind::Enum(..) => "enum",
2313 ItemKind::Struct(..) => "struct",
2314 ItemKind::Union(..) => "union",
2315 ItemKind::Trait(..) => "trait",
2316 ItemKind::TraitAlias(..) => "trait alias",
2317 ItemKind::Impl(..) => "impl",
2321 pub fn adt_kind(&self) -> Option<AdtKind> {
2323 ItemKind::Struct(..) => Some(AdtKind::Struct),
2324 ItemKind::Union(..) => Some(AdtKind::Union),
2325 ItemKind::Enum(..) => Some(AdtKind::Enum),
2330 pub fn generics(&self) -> Option<&Generics> {
2332 ItemKind::Fn(_, _, ref generics, _) |
2333 ItemKind::Ty(_, ref generics) |
2334 ItemKind::Existential(ExistTy { ref generics, impl_trait_fn: None, .. }) |
2335 ItemKind::Enum(_, ref generics) |
2336 ItemKind::Struct(_, ref generics) |
2337 ItemKind::Union(_, ref generics) |
2338 ItemKind::Trait(_, _, ref generics, _, _) |
2339 ItemKind::Impl(_, _, _, ref generics, _, _, _)=> generics,
2345 /// A reference from an trait to one of its associated items. This
2346 /// contains the item's id, naturally, but also the item's name and
2347 /// some other high-level details (like whether it is an associated
2348 /// type or method, and whether it is public). This allows other
2349 /// passes to find the impl they want without loading the ID (which
2350 /// means fewer edges in the incremental compilation graph).
2351 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2352 pub struct TraitItemRef {
2353 pub id: TraitItemId,
2355 pub kind: AssociatedItemKind,
2357 pub defaultness: Defaultness,
2360 /// A reference from an impl to one of its associated items. This
2361 /// contains the item's ID, naturally, but also the item's name and
2362 /// some other high-level details (like whether it is an associated
2363 /// type or method, and whether it is public). This allows other
2364 /// passes to find the impl they want without loading the ID (which
2365 /// means fewer edges in the incremental compilation graph).
2366 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2367 pub struct ImplItemRef {
2370 pub kind: AssociatedItemKind,
2372 pub vis: Visibility,
2373 pub defaultness: Defaultness,
2376 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
2377 pub enum AssociatedItemKind {
2379 Method { has_self: bool },
2384 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2385 pub struct ForeignItem {
2387 pub attrs: HirVec<Attribute>,
2388 pub node: ForeignItemKind,
2392 pub vis: Visibility,
2395 /// An item within an `extern` block.
2396 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2397 pub enum ForeignItemKind {
2398 /// A foreign function.
2399 Fn(P<FnDecl>, HirVec<Ident>, Generics),
2400 /// A foreign static item (`static ext: u8`), with optional mutability
2401 /// (the boolean is true when mutable).
2402 Static(P<Ty>, bool),
2407 impl ForeignItemKind {
2408 pub fn descriptive_variant(&self) -> &str {
2410 ForeignItemKind::Fn(..) => "foreign function",
2411 ForeignItemKind::Static(..) => "foreign static item",
2412 ForeignItemKind::Type => "foreign type",
2417 /// A free variable referred to in a function.
2418 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable)]
2419 pub struct Freevar {
2420 /// The variable being accessed free.
2423 // First span where it is accessed (there can be multiple).
2428 pub fn var_id(&self) -> NodeId {
2430 Def::Local(id) | Def::Upvar(id, ..) => id,
2431 _ => bug!("Freevar::var_id: bad def ({:?})", self.def)
2436 pub type FreevarMap = NodeMap<Vec<Freevar>>;
2438 pub type CaptureModeMap = NodeMap<CaptureClause>;
2440 #[derive(Clone, Debug)]
2441 pub struct TraitCandidate {
2443 pub import_id: Option<NodeId>,
2446 // Trait method resolution
2447 pub type TraitMap = NodeMap<Vec<TraitCandidate>>;
2449 // Map from the NodeId of a glob import to a list of items which are actually
2451 pub type GlobMap = NodeMap<FxHashSet<Name>>;
2454 pub fn provide(providers: &mut Providers<'_>) {
2455 check_attr::provide(providers);
2456 providers.describe_def = map::describe_def;
2459 #[derive(Clone, RustcEncodable, RustcDecodable)]
2460 pub struct CodegenFnAttrs {
2461 pub flags: CodegenFnAttrFlags,
2462 /// Parsed representation of the `#[inline]` attribute
2463 pub inline: InlineAttr,
2464 /// Parsed representation of the `#[optimize]` attribute
2465 pub optimize: OptimizeAttr,
2466 /// The `#[export_name = "..."]` attribute, indicating a custom symbol a
2467 /// function should be exported under
2468 pub export_name: Option<Symbol>,
2469 /// The `#[link_name = "..."]` attribute, indicating a custom symbol an
2470 /// imported function should be imported as. Note that `export_name`
2471 /// probably isn't set when this is set, this is for foreign items while
2472 /// `#[export_name]` is for Rust-defined functions.
2473 pub link_name: Option<Symbol>,
2474 /// The `#[target_feature(enable = "...")]` attribute and the enabled
2475 /// features (only enabled features are supported right now).
2476 pub target_features: Vec<Symbol>,
2477 /// The `#[linkage = "..."]` attribute and the value we found.
2478 pub linkage: Option<Linkage>,
2479 /// The `#[link_section = "..."]` attribute, or what executable section this
2480 /// should be placed in.
2481 pub link_section: Option<Symbol>,
2485 #[derive(RustcEncodable, RustcDecodable)]
2486 pub struct CodegenFnAttrFlags: u32 {
2487 /// `#[cold]`: a hint to LLVM that this function, when called, is never on
2489 const COLD = 1 << 0;
2490 /// `#[allocator]`: a hint to LLVM that the pointer returned from this
2491 /// function is never null.
2492 const ALLOCATOR = 1 << 1;
2493 /// `#[unwind]`: an indicator that this function may unwind despite what
2494 /// its ABI signature may otherwise imply.
2495 const UNWIND = 1 << 2;
2496 /// `#[rust_allocator_nounwind]`, an indicator that an imported FFI
2497 /// function will never unwind. Probably obsolete by recent changes with
2498 /// #[unwind], but hasn't been removed/migrated yet
2499 const RUSTC_ALLOCATOR_NOUNWIND = 1 << 3;
2500 /// `#[naked]`: an indicator to LLVM that no function prologue/epilogue
2501 /// should be generated.
2502 const NAKED = 1 << 4;
2503 /// `#[no_mangle]`: an indicator that the function's name should be the same
2505 const NO_MANGLE = 1 << 5;
2506 /// `#[rustc_std_internal_symbol]`: an indicator that this symbol is a
2507 /// "weird symbol" for the standard library in that it has slightly
2508 /// different linkage, visibility, and reachability rules.
2509 const RUSTC_STD_INTERNAL_SYMBOL = 1 << 6;
2510 /// `#[no_debug]`: an indicator that no debugging information should be
2511 /// generated for this function by LLVM.
2512 const NO_DEBUG = 1 << 7;
2513 /// `#[thread_local]`: indicates a static is actually a thread local
2515 const THREAD_LOCAL = 1 << 8;
2516 /// `#[used]`: indicates that LLVM can't eliminate this function (but the
2518 const USED = 1 << 9;
2522 impl CodegenFnAttrs {
2523 pub fn new() -> CodegenFnAttrs {
2525 flags: CodegenFnAttrFlags::empty(),
2526 inline: InlineAttr::None,
2527 optimize: OptimizeAttr::None,
2530 target_features: vec![],
2536 /// Returns `true` if `#[inline]` or `#[inline(always)]` is present.
2537 pub fn requests_inline(&self) -> bool {
2539 InlineAttr::Hint | InlineAttr::Always => true,
2540 InlineAttr::None | InlineAttr::Never => false,
2544 /// True if it looks like this symbol needs to be exported, for example:
2546 /// * `#[no_mangle]` is present
2547 /// * `#[export_name(...)]` is present
2548 /// * `#[linkage]` is present
2549 pub fn contains_extern_indicator(&self) -> bool {
2550 self.flags.contains(CodegenFnAttrFlags::NO_MANGLE) ||
2551 self.export_name.is_some() ||
2552 match self.linkage {
2553 // these are private, make sure we don't try to consider
2556 Some(Linkage::Internal) |
2557 Some(Linkage::Private) => false,
2563 #[derive(Copy, Clone, Debug)]
2564 pub enum Node<'hir> {
2566 ForeignItem(&'hir ForeignItem),
2567 TraitItem(&'hir TraitItem),
2568 ImplItem(&'hir ImplItem),
2569 Variant(&'hir Variant),
2570 Field(&'hir StructField),
2571 AnonConst(&'hir AnonConst),
2574 PathSegment(&'hir PathSegment),
2576 TraitRef(&'hir TraitRef),
2581 MacroDef(&'hir MacroDef),
2583 /// StructCtor represents a tuple struct.
2584 StructCtor(&'hir VariantData),
2586 Lifetime(&'hir Lifetime),
2587 GenericParam(&'hir GenericParam),
2588 Visibility(&'hir Visibility),