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::errors::FatalError;
14 use crate::hir::def::Def;
15 use crate::hir::def_id::{DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX};
16 use crate::util::nodemap::{NodeMap, FxHashSet};
17 use crate::mir::mono::Linkage;
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, DUMMY_NODE_ID, 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, scope};
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 /// A HirId 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)]
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 // hack to ensure that we don't try to access the private parts of `ItemLocalId` in this module
116 mod item_local_id_inner {
117 use rustc_data_structures::indexed_vec::Idx;
118 /// An `ItemLocalId` uniquely identifies something within a given "item-like",
119 /// that is within a hir::Item, hir::TraitItem, or hir::ImplItem. There is no
120 /// guarantee that the numerical value of a given `ItemLocalId` corresponds to
121 /// the node's position within the owning item in any way, but there is a
122 /// guarantee that the `LocalItemId`s within an owner occupy a dense range of
123 /// integers starting at zero, so a mapping that maps all or most nodes within
124 /// an "item-like" to something else can be implement by a `Vec` instead of a
125 /// tree or hash map.
127 pub struct ItemLocalId { .. }
131 pub use self::item_local_id_inner::ItemLocalId;
133 /// The `HirId` corresponding to CRATE_NODE_ID and CRATE_DEF_INDEX
134 pub const CRATE_HIR_ID: HirId = HirId {
135 owner: CRATE_DEF_INDEX,
136 local_id: ItemLocalId::from_u32_const(0)
139 pub const DUMMY_HIR_ID: HirId = HirId {
140 owner: CRATE_DEF_INDEX,
141 local_id: DUMMY_ITEM_LOCAL_ID,
144 pub const DUMMY_ITEM_LOCAL_ID: ItemLocalId = ItemLocalId::MAX;
146 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
147 pub struct Lifetime {
152 /// Either "'a", referring to a named lifetime definition,
153 /// or "" (aka keywords::Invalid), for elision placeholders.
155 /// HIR lowering inserts these placeholders in type paths that
156 /// refer to type definitions needing lifetime parameters,
157 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
158 pub name: LifetimeName,
161 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
163 /// Some user-given name like `T` or `'x`.
166 /// Synthetic name generated when user elided a lifetime in an impl header,
167 /// e.g., the lifetimes in cases like these:
169 /// impl Foo for &u32
170 /// impl Foo<'_> for u32
172 /// in that case, we rewrite to
174 /// impl<'f> Foo for &'f u32
175 /// impl<'f> Foo<'f> for u32
177 /// where `'f` is something like `Fresh(0)`. The indices are
178 /// unique per impl, but not necessarily continuous.
181 /// Indicates an illegal name was given and an error has been
182 /// repored (so we should squelch other derived errors). Occurs
183 /// when e.g., `'_` is used in the wrong place.
188 pub fn ident(&self) -> Ident {
190 ParamName::Plain(ident) => ident,
191 ParamName::Error | ParamName::Fresh(_) => keywords::UnderscoreLifetime.ident(),
195 pub fn modern(&self) -> ParamName {
197 ParamName::Plain(ident) => ParamName::Plain(ident.modern()),
198 param_name => param_name,
203 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
204 pub enum LifetimeName {
205 /// User-given names or fresh (synthetic) names.
208 /// User typed nothing. e.g., the lifetime in `&u32`.
211 /// Indicates an error during lowering (usually `'_` in wrong place)
212 /// that was already reported.
218 /// User wrote `'static`
223 pub fn ident(&self) -> Ident {
225 LifetimeName::Implicit => keywords::Invalid.ident(),
226 LifetimeName::Error => keywords::Invalid.ident(),
227 LifetimeName::Underscore => keywords::UnderscoreLifetime.ident(),
228 LifetimeName::Static => keywords::StaticLifetime.ident(),
229 LifetimeName::Param(param_name) => param_name.ident(),
233 pub fn is_elided(&self) -> bool {
235 LifetimeName::Implicit | LifetimeName::Underscore => true,
237 // It might seem surprising that `Fresh(_)` counts as
238 // *not* elided -- but this is because, as far as the code
239 // in the compiler is concerned -- `Fresh(_)` variants act
240 // equivalently to "some fresh name". They correspond to
241 // early-bound regions on an impl, in other words.
242 LifetimeName::Error | LifetimeName::Param(_) | LifetimeName::Static => false,
246 fn is_static(&self) -> bool {
247 self == &LifetimeName::Static
250 pub fn modern(&self) -> LifetimeName {
252 LifetimeName::Param(param_name) => LifetimeName::Param(param_name.modern()),
253 lifetime_name => lifetime_name,
258 impl fmt::Display for Lifetime {
259 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
260 self.name.ident().fmt(f)
264 impl fmt::Debug for Lifetime {
265 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
269 print::to_string(print::NO_ANN, |s| s.print_lifetime(self)))
274 pub fn is_elided(&self) -> bool {
275 self.name.is_elided()
278 pub fn is_static(&self) -> bool {
279 self.name.is_static()
283 /// A "Path" is essentially Rust's notion of a name; for instance:
284 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
285 /// along with a bunch of supporting information.
286 #[derive(Clone, RustcEncodable, RustcDecodable)]
289 /// The definition that the path resolved to.
291 /// The segments in the path: the things separated by `::`.
292 pub segments: HirVec<PathSegment>,
296 pub fn is_global(&self) -> bool {
297 !self.segments.is_empty() && self.segments[0].ident.name == keywords::PathRoot.name()
301 impl fmt::Debug for Path {
302 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
303 write!(f, "path({})", self)
307 impl fmt::Display for Path {
308 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
309 write!(f, "{}", print::to_string(print::NO_ANN, |s| s.print_path(self, false)))
313 /// A segment of a path: an identifier, an optional lifetime, and a set of
315 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
316 pub struct PathSegment {
317 /// The identifier portion of this path segment.
319 // `id` and `def` are optional. We currently only use these in save-analysis,
320 // any path segments without these will not have save-analysis info and
321 // therefore will not have 'jump to def' in IDEs, but otherwise will not be
322 // affected. (In general, we don't bother to get the defs for synthesized
323 // segments, only for segments which have come from the AST).
324 pub id: Option<NodeId>,
325 pub hir_id: Option<HirId>,
326 pub def: Option<Def>,
328 /// Type/lifetime parameters attached to this path. They come in
329 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
330 /// this is more than just simple syntactic sugar; the use of
331 /// parens affects the region binding rules, so we preserve the
333 pub args: Option<P<GenericArgs>>,
335 /// Whether to infer remaining type parameters, if any.
336 /// This only applies to expression and pattern paths, and
337 /// out of those only the segments with no type parameters
338 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
339 pub infer_types: bool,
343 /// Convert an identifier to the corresponding segment.
344 pub fn from_ident(ident: Ident) -> PathSegment {
358 hir_id: Option<HirId>,
369 args: if args.is_empty() {
377 // FIXME: hack required because you can't create a static
378 // `GenericArgs`, so you can't just return a `&GenericArgs`.
379 pub fn with_generic_args<F, R>(&self, f: F) -> R
380 where F: FnOnce(&GenericArgs) -> R
382 let dummy = GenericArgs::none();
383 f(if let Some(ref args) = self.args {
391 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
392 pub enum GenericArg {
398 pub fn span(&self) -> Span {
400 GenericArg::Lifetime(l) => l.span,
401 GenericArg::Type(t) => t.span,
405 pub fn id(&self) -> NodeId {
407 GenericArg::Lifetime(l) => l.id,
408 GenericArg::Type(t) => t.id,
413 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
414 pub struct GenericArgs {
415 /// The generic arguments for this path segment.
416 pub args: HirVec<GenericArg>,
417 /// Bindings (equality constraints) on associated types, if present.
418 /// E.g., `Foo<A = Bar>`.
419 pub bindings: HirVec<TypeBinding>,
420 /// Were arguments written in parenthesized form `Fn(T) -> U`?
421 /// This is required mostly for pretty-printing and diagnostics,
422 /// but also for changing lifetime elision rules to be "function-like".
423 pub parenthesized: bool,
427 pub fn none() -> Self {
430 bindings: HirVec::new(),
431 parenthesized: false,
435 pub fn is_empty(&self) -> bool {
436 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
439 pub fn inputs(&self) -> &[Ty] {
440 if self.parenthesized {
441 for arg in &self.args {
443 GenericArg::Lifetime(_) => {}
444 GenericArg::Type(ref ty) => {
445 if let TyKind::Tup(ref tys) = ty.node {
453 bug!("GenericArgs::inputs: not a `Fn(T) -> U`");
456 pub fn own_counts(&self) -> GenericParamCount {
457 // We could cache this as a property of `GenericParamCount`, but
458 // the aim is to refactor this away entirely eventually and the
459 // presence of this method will be a constant reminder.
460 let mut own_counts: GenericParamCount = Default::default();
462 for arg in &self.args {
464 GenericArg::Lifetime(_) => own_counts.lifetimes += 1,
465 GenericArg::Type(_) => own_counts.types += 1,
473 /// A modifier on a bound, currently this is only used for `?Sized`, where the
474 /// modifier is `Maybe`. Negative bounds should also be handled here.
475 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
476 pub enum TraitBoundModifier {
481 /// The AST represents all type param bounds as types.
482 /// `typeck::collect::compute_bounds` matches these against
483 /// the "special" built-in traits (see `middle::lang_items`) and
484 /// detects `Copy`, `Send` and `Sync`.
485 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
486 pub enum GenericBound {
487 Trait(PolyTraitRef, TraitBoundModifier),
492 pub fn span(&self) -> Span {
494 &GenericBound::Trait(ref t, ..) => t.span,
495 &GenericBound::Outlives(ref l) => l.span,
500 pub type GenericBounds = HirVec<GenericBound>;
502 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
503 pub enum LifetimeParamKind {
504 // Indicates that the lifetime definition was explicitly declared (e.g., in
505 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
508 // Indicates that the lifetime definition was synthetically added
509 // as a result of an in-band lifetime usage (e.g., in
510 // `fn foo(x: &'a u8) -> &'a u8 { x }`).
513 // Indication that the lifetime was elided (e.g., in both cases in
514 // `fn foo(x: &u8) -> &'_ u8 { x }`).
517 // Indication that the lifetime name was somehow in error.
521 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
522 pub enum GenericParamKind {
523 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
525 kind: LifetimeParamKind,
528 default: Option<P<Ty>>,
529 synthetic: Option<SyntheticTyParamKind>,
533 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
534 pub struct GenericParam {
538 pub attrs: HirVec<Attribute>,
539 pub bounds: GenericBounds,
541 pub pure_wrt_drop: bool,
543 pub kind: GenericParamKind,
547 pub struct GenericParamCount {
548 pub lifetimes: usize,
552 /// Represents lifetimes and type parameters attached to a declaration
553 /// of a function, enum, trait, etc.
554 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
555 pub struct Generics {
556 pub params: HirVec<GenericParam>,
557 pub where_clause: WhereClause,
562 pub fn empty() -> Generics {
564 params: HirVec::new(),
565 where_clause: WhereClause {
567 hir_id: DUMMY_HIR_ID,
568 predicates: HirVec::new(),
574 pub fn own_counts(&self) -> GenericParamCount {
575 // We could cache this as a property of `GenericParamCount`, but
576 // the aim is to refactor this away entirely eventually and the
577 // presence of this method will be a constant reminder.
578 let mut own_counts: GenericParamCount = Default::default();
580 for param in &self.params {
582 GenericParamKind::Lifetime { .. } => own_counts.lifetimes += 1,
583 GenericParamKind::Type { .. } => own_counts.types += 1,
590 pub fn get_named(&self, name: &InternedString) -> Option<&GenericParam> {
591 for param in &self.params {
592 if *name == param.name.ident().as_interned_str() {
600 /// Synthetic Type Parameters are converted to an other form during lowering, this allows
601 /// to track the original form they had. Useful for error messages.
602 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
603 pub enum SyntheticTyParamKind {
607 /// A `where` clause in a definition
608 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
609 pub struct WhereClause {
612 pub predicates: HirVec<WherePredicate>,
616 pub fn span(&self) -> Option<Span> {
617 self.predicates.iter().map(|predicate| predicate.span())
618 .fold(None, |acc, i| match (acc, i) {
619 (None, i) => Some(i),
627 /// A single predicate in a `where` clause
628 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
629 pub enum WherePredicate {
630 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
631 BoundPredicate(WhereBoundPredicate),
632 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
633 RegionPredicate(WhereRegionPredicate),
634 /// An equality predicate (unsupported).
635 EqPredicate(WhereEqPredicate),
638 impl WherePredicate {
639 pub fn span(&self) -> Span {
641 &WherePredicate::BoundPredicate(ref p) => p.span,
642 &WherePredicate::RegionPredicate(ref p) => p.span,
643 &WherePredicate::EqPredicate(ref p) => p.span,
648 /// A type bound, eg `for<'c> Foo: Send+Clone+'c`
649 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
650 pub struct WhereBoundPredicate {
652 /// Any generics from a `for` binding
653 pub bound_generic_params: HirVec<GenericParam>,
654 /// The type being bounded
655 pub bounded_ty: P<Ty>,
656 /// Trait and lifetime bounds (`Clone+Send+'static`)
657 pub bounds: GenericBounds,
660 /// A lifetime predicate, e.g., `'a: 'b+'c`
661 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
662 pub struct WhereRegionPredicate {
664 pub lifetime: Lifetime,
665 pub bounds: GenericBounds,
668 /// An equality predicate (unsupported), e.g., `T=int`
669 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
670 pub struct WhereEqPredicate {
678 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
679 pub struct ModuleItems {
680 // Use BTreeSets here so items are in the same order as in the
681 // list of all items in Crate
682 pub items: BTreeSet<NodeId>,
683 pub trait_items: BTreeSet<TraitItemId>,
684 pub impl_items: BTreeSet<ImplItemId>,
687 /// The top-level data structure that stores the entire contents of
688 /// the crate currently being compiled.
690 /// For more details, see the [rustc guide].
692 /// [rustc guide]: https://rust-lang.github.io/rustc-guide/hir.html
693 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
696 pub attrs: HirVec<Attribute>,
698 pub exported_macros: HirVec<MacroDef>,
700 // N.B., we use a BTreeMap here so that `visit_all_items` iterates
701 // over the ids in increasing order. In principle it should not
702 // matter what order we visit things in, but in *practice* it
703 // does, because it can affect the order in which errors are
704 // detected, which in turn can make compile-fail tests yield
705 // slightly different results.
706 pub items: BTreeMap<NodeId, Item>,
708 pub trait_items: BTreeMap<TraitItemId, TraitItem>,
709 pub impl_items: BTreeMap<ImplItemId, ImplItem>,
710 pub bodies: BTreeMap<BodyId, Body>,
711 pub trait_impls: BTreeMap<DefId, Vec<NodeId>>,
712 pub trait_auto_impl: BTreeMap<DefId, NodeId>,
714 /// A list of the body ids written out in the order in which they
715 /// appear in the crate. If you're going to process all the bodies
716 /// in the crate, you should iterate over this list rather than the keys
718 pub body_ids: Vec<BodyId>,
720 /// A list of modules written out in the order in which they
721 /// appear in the crate. This includes the main crate module.
722 pub modules: BTreeMap<NodeId, ModuleItems>,
726 pub fn item(&self, id: NodeId) -> &Item {
730 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem {
731 &self.trait_items[&id]
734 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem {
735 &self.impl_items[&id]
738 /// Visits all items in the crate in some deterministic (but
739 /// unspecified) order. If you just need to process every item,
740 /// but don't care about nesting, this method is the best choice.
742 /// If you do care about nesting -- usually because your algorithm
743 /// follows lexical scoping rules -- then you want a different
744 /// approach. You should override `visit_nested_item` in your
745 /// visitor and then call `intravisit::walk_crate` instead.
746 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
747 where V: itemlikevisit::ItemLikeVisitor<'hir>
749 for (_, item) in &self.items {
750 visitor.visit_item(item);
753 for (_, trait_item) in &self.trait_items {
754 visitor.visit_trait_item(trait_item);
757 for (_, impl_item) in &self.impl_items {
758 visitor.visit_impl_item(impl_item);
762 /// A parallel version of visit_all_item_likes
763 pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
764 where V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send
768 par_iter(&self.items).for_each(|(_, item)| {
769 visitor.visit_item(item);
774 par_iter(&self.trait_items).for_each(|(_, trait_item)| {
775 visitor.visit_trait_item(trait_item);
780 par_iter(&self.impl_items).for_each(|(_, impl_item)| {
781 visitor.visit_impl_item(impl_item);
787 pub fn body(&self, id: BodyId) -> &Body {
792 /// A macro definition, in this crate or imported from another.
794 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
795 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
796 pub struct MacroDef {
799 pub attrs: HirVec<Attribute>,
803 pub body: TokenStream,
807 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
809 /// Statements in a block
810 pub stmts: HirVec<Stmt>,
811 /// An expression at the end of the block
812 /// without a semicolon, if any
813 pub expr: Option<P<Expr>>,
816 /// Distinguishes between `unsafe { ... }` and `{ ... }`
817 pub rules: BlockCheckMode,
819 /// If true, then there may exist `break 'a` values that aim to
820 /// break out of this block early.
821 /// Used by `'label: {}` blocks and by `catch` statements.
822 pub targeted_by_break: bool,
825 #[derive(Clone, RustcEncodable, RustcDecodable)]
833 impl fmt::Debug for Pat {
834 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
835 write!(f, "pat({}: {})", self.id,
836 print::to_string(print::NO_ANN, |s| s.print_pat(self)))
841 // FIXME(#19596) this is a workaround, but there should be a better way
842 fn walk_<G>(&self, it: &mut G) -> bool
843 where G: FnMut(&Pat) -> bool
850 PatKind::Binding(.., Some(ref p)) => p.walk_(it),
851 PatKind::Struct(_, ref fields, _) => {
852 fields.iter().all(|field| field.node.pat.walk_(it))
854 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
855 s.iter().all(|p| p.walk_(it))
857 PatKind::Box(ref s) | PatKind::Ref(ref s, _) => {
860 PatKind::Slice(ref before, ref slice, ref after) => {
864 .all(|p| p.walk_(it))
869 PatKind::Binding(..) |
870 PatKind::Path(_) => {
876 pub fn walk<F>(&self, mut it: F) -> bool
877 where F: FnMut(&Pat) -> bool
883 /// A single field in a struct pattern
885 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
886 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
887 /// except is_shorthand is true
888 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
889 pub struct FieldPat {
892 /// The identifier for the field
894 /// The pattern the field is destructured to
896 pub is_shorthand: bool,
899 /// Explicit binding annotations given in the HIR for a binding. Note
900 /// that this is not the final binding *mode* that we infer after type
902 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
903 pub enum BindingAnnotation {
904 /// No binding annotation given: this means that the final binding mode
905 /// will depend on whether we have skipped through a `&` reference
906 /// when matching. For example, the `x` in `Some(x)` will have binding
907 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
908 /// ultimately be inferred to be by-reference.
910 /// Note that implicit reference skipping is not implemented yet (#42640).
913 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
916 /// Annotated as `ref`, like `ref x`
919 /// Annotated as `ref mut x`.
923 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
929 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
931 /// Represents a wildcard pattern (`_`)
934 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
935 /// The `NodeId` is the canonical ID for the variable being bound,
936 /// e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID,
937 /// which is the pattern ID of the first `x`.
938 Binding(BindingAnnotation, NodeId, HirId, Ident, Option<P<Pat>>),
940 /// A struct or struct variant pattern, e.g., `Variant {x, y, ..}`.
941 /// The `bool` is `true` in the presence of a `..`.
942 Struct(QPath, HirVec<Spanned<FieldPat>>, bool),
944 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
945 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
946 /// 0 <= position <= subpats.len()
947 TupleStruct(QPath, HirVec<P<Pat>>, Option<usize>),
949 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
952 /// A tuple pattern `(a, b)`.
953 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
954 /// 0 <= position <= subpats.len()
955 Tuple(HirVec<P<Pat>>, Option<usize>),
958 /// A reference pattern, e.g., `&mut (a, b)`
959 Ref(P<Pat>, Mutability),
962 /// A range pattern, e.g., `1...2` or `1..2`
963 Range(P<Expr>, P<Expr>, RangeEnd),
964 /// `[a, b, ..i, y, z]` is represented as:
965 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
966 Slice(HirVec<P<Pat>>, Option<P<Pat>>, HirVec<P<Pat>>),
969 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
970 pub enum Mutability {
976 /// Return MutMutable only if both arguments are mutable.
977 pub fn and(self, other: Self) -> Self {
980 MutImmutable => MutImmutable,
985 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, Hash)]
987 /// The `+` operator (addition)
989 /// The `-` operator (subtraction)
991 /// The `*` operator (multiplication)
993 /// The `/` operator (division)
995 /// The `%` operator (modulus)
997 /// The `&&` operator (logical and)
999 /// The `||` operator (logical or)
1001 /// The `^` operator (bitwise xor)
1003 /// The `&` operator (bitwise and)
1005 /// The `|` operator (bitwise or)
1007 /// The `<<` operator (shift left)
1009 /// The `>>` operator (shift right)
1011 /// The `==` operator (equality)
1013 /// The `<` operator (less than)
1015 /// The `<=` operator (less than or equal to)
1017 /// The `!=` operator (not equal to)
1019 /// The `>=` operator (greater than or equal to)
1021 /// The `>` operator (greater than)
1026 pub fn as_str(self) -> &'static str {
1028 BinOpKind::Add => "+",
1029 BinOpKind::Sub => "-",
1030 BinOpKind::Mul => "*",
1031 BinOpKind::Div => "/",
1032 BinOpKind::Rem => "%",
1033 BinOpKind::And => "&&",
1034 BinOpKind::Or => "||",
1035 BinOpKind::BitXor => "^",
1036 BinOpKind::BitAnd => "&",
1037 BinOpKind::BitOr => "|",
1038 BinOpKind::Shl => "<<",
1039 BinOpKind::Shr => ">>",
1040 BinOpKind::Eq => "==",
1041 BinOpKind::Lt => "<",
1042 BinOpKind::Le => "<=",
1043 BinOpKind::Ne => "!=",
1044 BinOpKind::Ge => ">=",
1045 BinOpKind::Gt => ">",
1049 pub fn is_lazy(self) -> bool {
1051 BinOpKind::And | BinOpKind::Or => true,
1056 pub fn is_shift(self) -> bool {
1058 BinOpKind::Shl | BinOpKind::Shr => true,
1063 pub fn is_comparison(self) -> bool {
1070 BinOpKind::Ge => true,
1082 BinOpKind::Shr => false,
1086 /// Returns `true` if the binary operator takes its arguments by value
1087 pub fn is_by_value(self) -> bool {
1088 !self.is_comparison()
1092 impl Into<ast::BinOpKind> for BinOpKind {
1093 fn into(self) -> ast::BinOpKind {
1095 BinOpKind::Add => ast::BinOpKind::Add,
1096 BinOpKind::Sub => ast::BinOpKind::Sub,
1097 BinOpKind::Mul => ast::BinOpKind::Mul,
1098 BinOpKind::Div => ast::BinOpKind::Div,
1099 BinOpKind::Rem => ast::BinOpKind::Rem,
1100 BinOpKind::And => ast::BinOpKind::And,
1101 BinOpKind::Or => ast::BinOpKind::Or,
1102 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1103 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1104 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1105 BinOpKind::Shl => ast::BinOpKind::Shl,
1106 BinOpKind::Shr => ast::BinOpKind::Shr,
1107 BinOpKind::Eq => ast::BinOpKind::Eq,
1108 BinOpKind::Lt => ast::BinOpKind::Lt,
1109 BinOpKind::Le => ast::BinOpKind::Le,
1110 BinOpKind::Ne => ast::BinOpKind::Ne,
1111 BinOpKind::Ge => ast::BinOpKind::Ge,
1112 BinOpKind::Gt => ast::BinOpKind::Gt,
1117 pub type BinOp = Spanned<BinOpKind>;
1119 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, Hash)]
1121 /// The `*` operator for dereferencing
1123 /// The `!` operator for logical inversion
1125 /// The `-` operator for negation
1130 pub fn as_str(self) -> &'static str {
1138 /// Returns `true` if the unary operator takes its argument by value
1139 pub fn is_by_value(self) -> bool {
1141 UnNeg | UnNot => true,
1148 #[derive(Clone, RustcEncodable, RustcDecodable)]
1156 impl fmt::Debug for Stmt {
1157 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1158 write!(f, "stmt({}: {})", self.id,
1159 print::to_string(print::NO_ANN, |s| s.print_stmt(self)))
1163 #[derive(Clone, RustcEncodable, RustcDecodable)]
1165 /// A local (let) binding:
1167 /// An item binding:
1170 /// Expr without trailing semi-colon (must have unit type):
1173 /// Expr with trailing semi-colon (may have any type):
1178 pub fn attrs(&self) -> &[Attribute] {
1180 StmtKind::Local(ref l) => &l.attrs,
1181 StmtKind::Item(_) => &[],
1182 StmtKind::Expr(ref e) |
1183 StmtKind::Semi(ref e) => &e.attrs,
1188 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
1189 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1192 pub ty: Option<P<Ty>>,
1193 /// Initializer expression to set the value, if any
1194 pub init: Option<P<Expr>>,
1198 pub attrs: ThinVec<Attribute>,
1199 pub source: LocalSource,
1202 /// represents one arm of a 'match'
1203 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1205 pub attrs: HirVec<Attribute>,
1206 pub pats: HirVec<P<Pat>>,
1207 pub guard: Option<Guard>,
1211 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1216 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1223 pub is_shorthand: bool,
1226 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1227 pub enum BlockCheckMode {
1229 UnsafeBlock(UnsafeSource),
1230 PushUnsafeBlock(UnsafeSource),
1231 PopUnsafeBlock(UnsafeSource),
1234 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1235 pub enum UnsafeSource {
1240 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1242 pub node_id: NodeId,
1245 /// The body of a function, closure, or constant value. In the case of
1246 /// a function, the body contains not only the function body itself
1247 /// (which is an expression), but also the argument patterns, since
1248 /// those are something that the caller doesn't really care about.
1253 /// fn foo((x, y): (u32, u32)) -> u32 {
1258 /// Here, the `Body` associated with `foo()` would contain:
1260 /// - an `arguments` array containing the `(x, y)` pattern
1261 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1262 /// - `is_generator` would be false
1264 /// All bodies have an **owner**, which can be accessed via the HIR
1265 /// map using `body_owner_def_id()`.
1266 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1268 pub arguments: HirVec<Arg>,
1270 pub is_generator: bool,
1274 pub fn id(&self) -> BodyId {
1276 node_id: self.value.id
1281 #[derive(Copy, Clone, Debug)]
1282 pub enum BodyOwnerKind {
1283 /// Functions and methods.
1289 /// Constants and associated constants.
1292 /// Initializer of a `static` item.
1296 impl BodyOwnerKind {
1297 pub fn is_fn_or_closure(self) -> bool {
1299 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1300 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1305 /// A constant (expression) that's not an item or associated item,
1306 /// but needs its own `DefId` for type-checking, const-eval, etc.
1307 /// These are usually found nested inside types (e.g., array lengths)
1308 /// or expressions (e.g., repeat counts), and also used to define
1309 /// explicit discriminant values for enum variants.
1310 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
1311 pub struct AnonConst {
1318 #[derive(Clone, RustcEncodable, RustcDecodable)]
1323 pub attrs: ThinVec<Attribute>,
1328 pub fn precedence(&self) -> ExprPrecedence {
1330 ExprKind::Box(_) => ExprPrecedence::Box,
1331 ExprKind::Array(_) => ExprPrecedence::Array,
1332 ExprKind::Call(..) => ExprPrecedence::Call,
1333 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1334 ExprKind::Tup(_) => ExprPrecedence::Tup,
1335 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1336 ExprKind::Unary(..) => ExprPrecedence::Unary,
1337 ExprKind::Lit(_) => ExprPrecedence::Lit,
1338 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1339 ExprKind::If(..) => ExprPrecedence::If,
1340 ExprKind::While(..) => ExprPrecedence::While,
1341 ExprKind::Loop(..) => ExprPrecedence::Loop,
1342 ExprKind::Match(..) => ExprPrecedence::Match,
1343 ExprKind::Closure(..) => ExprPrecedence::Closure,
1344 ExprKind::Block(..) => ExprPrecedence::Block,
1345 ExprKind::Assign(..) => ExprPrecedence::Assign,
1346 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1347 ExprKind::Field(..) => ExprPrecedence::Field,
1348 ExprKind::Index(..) => ExprPrecedence::Index,
1349 ExprKind::Path(..) => ExprPrecedence::Path,
1350 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1351 ExprKind::Break(..) => ExprPrecedence::Break,
1352 ExprKind::Continue(..) => ExprPrecedence::Continue,
1353 ExprKind::Ret(..) => ExprPrecedence::Ret,
1354 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1355 ExprKind::Struct(..) => ExprPrecedence::Struct,
1356 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1357 ExprKind::Yield(..) => ExprPrecedence::Yield,
1358 ExprKind::Err => ExprPrecedence::Err,
1362 pub fn is_place_expr(&self) -> bool {
1364 ExprKind::Path(QPath::Resolved(_, ref path)) => {
1366 Def::Local(..) | Def::Upvar(..) | Def::Static(..) | Def::Err => true,
1371 ExprKind::Type(ref e, _) => {
1375 ExprKind::Unary(UnDeref, _) |
1376 ExprKind::Field(..) |
1377 ExprKind::Index(..) => {
1381 // Partially qualified paths in expressions can only legally
1382 // refer to associated items which are always rvalues.
1383 ExprKind::Path(QPath::TypeRelative(..)) |
1385 ExprKind::Call(..) |
1386 ExprKind::MethodCall(..) |
1387 ExprKind::Struct(..) |
1390 ExprKind::Match(..) |
1391 ExprKind::Closure(..) |
1392 ExprKind::Block(..) |
1393 ExprKind::Repeat(..) |
1394 ExprKind::Array(..) |
1395 ExprKind::Break(..) |
1396 ExprKind::Continue(..) |
1398 ExprKind::While(..) |
1399 ExprKind::Loop(..) |
1400 ExprKind::Assign(..) |
1401 ExprKind::InlineAsm(..) |
1402 ExprKind::AssignOp(..) |
1404 ExprKind::Unary(..) |
1406 ExprKind::AddrOf(..) |
1407 ExprKind::Binary(..) |
1408 ExprKind::Yield(..) |
1409 ExprKind::Cast(..) |
1417 impl fmt::Debug for Expr {
1418 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1419 write!(f, "expr({}: {})", self.id,
1420 print::to_string(print::NO_ANN, |s| s.print_expr(self)))
1424 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1426 /// A `box x` expression.
1428 /// An array (`[a, b, c, d]`)
1429 Array(HirVec<Expr>),
1432 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1433 /// and the second field is the list of arguments.
1434 /// This also represents calling the constructor of
1435 /// tuple-like ADTs such as tuple structs and enum variants.
1436 Call(P<Expr>, HirVec<Expr>),
1437 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1439 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1440 /// (within the angle brackets).
1441 /// The first element of the vector of `Expr`s is the expression that evaluates
1442 /// to the object on which the method is being called on (the receiver),
1443 /// and the remaining elements are the rest of the arguments.
1444 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1445 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1446 MethodCall(PathSegment, Span, HirVec<Expr>),
1447 /// A tuple (`(a, b, c ,d)`)
1449 /// A binary operation (For example: `a + b`, `a * b`)
1450 Binary(BinOp, P<Expr>, P<Expr>),
1451 /// A unary operation (For example: `!x`, `*x`)
1452 Unary(UnOp, P<Expr>),
1453 /// A literal (For example: `1`, `"foo"`)
1455 /// A cast (`foo as f64`)
1456 Cast(P<Expr>, P<Ty>),
1457 Type(P<Expr>, P<Ty>),
1458 /// An `if` block, with an optional else block
1460 /// `if expr { expr } else { expr }`
1461 If(P<Expr>, P<Expr>, Option<P<Expr>>),
1462 /// A while loop, with an optional label
1464 /// `'label: while expr { block }`
1465 While(P<Expr>, P<Block>, Option<Label>),
1466 /// Conditionless loop (can be exited with break, continue, or return)
1468 /// `'label: loop { block }`
1469 Loop(P<Block>, Option<Label>, LoopSource),
1470 /// A `match` block, with a source that indicates whether or not it is
1471 /// the result of a desugaring, and if so, which kind.
1472 Match(P<Expr>, HirVec<Arm>, MatchSource),
1473 /// A closure (for example, `move |a, b, c| {a + b + c}`).
1475 /// The final span is the span of the argument block `|...|`
1477 /// This may also be a generator literal, indicated by the final boolean,
1478 /// in that case there is an GeneratorClause.
1479 Closure(CaptureClause, P<FnDecl>, BodyId, Span, Option<GeneratorMovability>),
1480 /// A block (`'label: { ... }`)
1481 Block(P<Block>, Option<Label>),
1483 /// An assignment (`a = foo()`)
1484 Assign(P<Expr>, P<Expr>),
1485 /// An assignment with an operator
1487 /// For example, `a += 1`.
1488 AssignOp(BinOp, P<Expr>, P<Expr>),
1489 /// Access of a named (`obj.foo`) or unnamed (`obj.0`) struct or tuple field
1490 Field(P<Expr>, Ident),
1491 /// An indexing operation (`foo[2]`)
1492 Index(P<Expr>, P<Expr>),
1494 /// Path to a definition, possibly containing lifetime or type parameters.
1497 /// A referencing operation (`&a` or `&mut a`)
1498 AddrOf(Mutability, P<Expr>),
1499 /// A `break`, with an optional label to break
1500 Break(Destination, Option<P<Expr>>),
1501 /// A `continue`, with an optional label
1502 Continue(Destination),
1503 /// A `return`, with an optional value to be returned
1504 Ret(Option<P<Expr>>),
1506 /// Inline assembly (from `asm!`), with its outputs and inputs.
1507 InlineAsm(P<InlineAsm>, HirVec<Expr>, HirVec<Expr>),
1509 /// A struct or struct-like variant literal expression.
1511 /// For example, `Foo {x: 1, y: 2}`, or
1512 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
1513 Struct(QPath, HirVec<Field>, Option<P<Expr>>),
1515 /// An array literal constructed from one repeated element.
1517 /// For example, `[1; 5]`. The first expression is the element
1518 /// to be repeated; the second is the number of times to repeat it.
1519 Repeat(P<Expr>, AnonConst),
1521 /// A suspension point for generators. This is `yield <expr>` in Rust.
1524 /// Placeholder for an expression that wasn't syntactically well formed in some way.
1528 /// Optionally `Self`-qualified value/type path or associated extension.
1529 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1531 /// Path to a definition, optionally "fully-qualified" with a `Self`
1532 /// type, if the path points to an associated item in a trait.
1534 /// e.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1535 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1536 /// even though they both have the same two-segment `Clone::clone` `Path`.
1537 Resolved(Option<P<Ty>>, P<Path>),
1539 /// Type-related paths, e.g., `<T>::default` or `<T>::Output`.
1540 /// Will be resolved by type-checking to an associated item.
1542 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1543 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1544 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1545 TypeRelative(P<Ty>, P<PathSegment>)
1548 /// Hints at the original code for a let statement
1549 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1550 pub enum LocalSource {
1551 /// A `match _ { .. }`
1553 /// A desugared `for _ in _ { .. }` loop
1557 /// Hints at the original code for a `match _ { .. }`
1558 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1559 pub enum MatchSource {
1560 /// A `match _ { .. }`
1562 /// An `if let _ = _ { .. }` (optionally with `else { .. }`)
1564 contains_else_clause: bool,
1566 /// A `while let _ = _ { .. }` (which was desugared to a
1567 /// `loop { match _ { .. } }`)
1569 /// A desugared `for _ in _ { .. }` loop
1571 /// A desugared `?` operator
1575 /// The loop type that yielded an ExprKind::Loop
1576 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1577 pub enum LoopSource {
1578 /// A `loop { .. }` loop
1580 /// A `while let _ = _ { .. }` loop
1582 /// A `for _ in _ { .. }` loop
1586 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1587 pub enum LoopIdError {
1589 UnlabeledCfInWhileCondition,
1593 impl fmt::Display for LoopIdError {
1594 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1595 fmt::Display::fmt(match *self {
1596 LoopIdError::OutsideLoopScope => "not inside loop scope",
1597 LoopIdError::UnlabeledCfInWhileCondition =>
1598 "unlabeled control flow (break or continue) in while condition",
1599 LoopIdError::UnresolvedLabel => "label not found",
1604 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1605 pub struct Destination {
1606 // This is `Some(_)` iff there is an explicit user-specified `label
1607 pub label: Option<Label>,
1609 // These errors are caught and then reported during the diagnostics pass in
1610 // librustc_passes/loops.rs
1611 pub target_id: Result<NodeId, LoopIdError>,
1614 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1615 pub enum GeneratorMovability {
1620 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1621 pub enum CaptureClause {
1626 // N.B., if you change this, you'll probably want to change the corresponding
1627 // type structure in middle/ty.rs as well.
1628 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1631 pub mutbl: Mutability,
1634 /// Represents a method's signature in a trait declaration or implementation.
1635 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1636 pub struct MethodSig {
1637 pub header: FnHeader,
1638 pub decl: P<FnDecl>,
1641 // The bodies for items are stored "out of line", in a separate
1642 // hashmap in the `Crate`. Here we just record the node-id of the item
1643 // so it can fetched later.
1644 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1645 pub struct TraitItemId {
1646 pub node_id: NodeId,
1649 /// Represents an item declaration within a trait declaration,
1650 /// possibly including a default implementation. A trait item is
1651 /// either required (meaning it doesn't have an implementation, just a
1652 /// signature) or provided (meaning it has a default implementation).
1653 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1654 pub struct TraitItem {
1658 pub attrs: HirVec<Attribute>,
1659 pub generics: Generics,
1660 pub node: TraitItemKind,
1664 /// A trait method's body (or just argument names).
1665 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1666 pub enum TraitMethod {
1667 /// No default body in the trait, just a signature.
1668 Required(HirVec<Ident>),
1670 /// Both signature and body are provided in the trait.
1674 /// Represents a trait method or associated constant or type
1675 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1676 pub enum TraitItemKind {
1677 /// An associated constant with an optional value (otherwise `impl`s
1678 /// must contain a value)
1679 Const(P<Ty>, Option<BodyId>),
1680 /// A method with an optional body
1681 Method(MethodSig, TraitMethod),
1682 /// An associated type with (possibly empty) bounds and optional concrete
1684 Type(GenericBounds, Option<P<Ty>>),
1687 // The bodies for items are stored "out of line", in a separate
1688 // hashmap in the `Crate`. Here we just record the node-id of the item
1689 // so it can fetched later.
1690 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1691 pub struct ImplItemId {
1692 pub node_id: NodeId,
1695 /// Represents anything within an `impl` block
1696 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1697 pub struct ImplItem {
1701 pub vis: Visibility,
1702 pub defaultness: Defaultness,
1703 pub attrs: HirVec<Attribute>,
1704 pub generics: Generics,
1705 pub node: ImplItemKind,
1709 /// Represents different contents within `impl`s
1710 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1711 pub enum ImplItemKind {
1712 /// An associated constant of the given type, set to the constant result
1713 /// of the expression
1714 Const(P<Ty>, BodyId),
1715 /// A method implementation with the given signature and body
1716 Method(MethodSig, BodyId),
1717 /// An associated type
1719 /// An associated existential type
1720 Existential(GenericBounds),
1723 // Bind a type to an associated type: `A=Foo`.
1724 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1725 pub struct TypeBinding {
1733 #[derive(Clone, RustcEncodable, RustcDecodable)]
1741 impl fmt::Debug for Ty {
1742 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1743 write!(f, "type({})",
1744 print::to_string(print::NO_ANN, |s| s.print_type(self)))
1748 /// Not represented directly in the AST, referred to by name through a ty_path.
1749 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1759 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1760 pub struct BareFnTy {
1761 pub unsafety: Unsafety,
1763 pub generic_params: HirVec<GenericParam>,
1764 pub decl: P<FnDecl>,
1765 pub arg_names: HirVec<Ident>,
1768 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1769 pub struct ExistTy {
1770 pub generics: Generics,
1771 pub bounds: GenericBounds,
1772 pub impl_trait_fn: Option<DefId>,
1775 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1776 /// The different kinds of types recognized by the compiler
1778 /// A variable length slice (`[T]`)
1780 /// A fixed length array (`[T; n]`)
1781 Array(P<Ty>, AnonConst),
1782 /// A raw pointer (`*const T` or `*mut T`)
1784 /// A reference (`&'a T` or `&'a mut T`)
1785 Rptr(Lifetime, MutTy),
1786 /// A bare function (e.g., `fn(usize) -> bool`)
1787 BareFn(P<BareFnTy>),
1788 /// The never type (`!`)
1790 /// A tuple (`(A, B, C, D,...)`)
1792 /// A path to a type definition (`module::module::...::Type`), or an
1793 /// associated type, e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`.
1795 /// Type parameters may be stored in each `PathSegment`.
1797 /// A type definition itself. This is currently only used for the `existential type`
1798 /// item that `impl Trait` in return position desugars to.
1800 /// The generic arg list are the lifetimes (and in the future possibly parameters) that are
1801 /// actually bound on the `impl Trait`.
1802 Def(ItemId, HirVec<GenericArg>),
1803 /// A trait object type `Bound1 + Bound2 + Bound3`
1804 /// where `Bound` is a trait or a lifetime.
1805 TraitObject(HirVec<PolyTraitRef>, Lifetime),
1808 /// `TyKind::Infer` means the type should be inferred instead of it having been
1809 /// specified. This can appear anywhere in a type.
1811 /// Placeholder for a type that has failed to be defined.
1815 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1816 pub struct InlineAsmOutput {
1817 pub constraint: Symbol,
1819 pub is_indirect: bool,
1823 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1824 pub struct InlineAsm {
1826 pub asm_str_style: StrStyle,
1827 pub outputs: HirVec<InlineAsmOutput>,
1828 pub inputs: HirVec<Symbol>,
1829 pub clobbers: HirVec<Symbol>,
1831 pub alignstack: bool,
1832 pub dialect: AsmDialect,
1833 pub ctxt: SyntaxContext,
1836 /// represents an argument in a function header
1837 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1844 /// Represents the header (not the body) of a function declaration
1845 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1847 pub inputs: HirVec<Ty>,
1848 pub output: FunctionRetTy,
1850 /// Does the function have an implicit self?
1851 pub implicit_self: ImplicitSelfKind,
1854 /// Represents what type of implicit self a function has, if any.
1855 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
1856 pub enum ImplicitSelfKind {
1857 /// Represents a `fn x(self);`.
1859 /// Represents a `fn x(mut self);`.
1861 /// Represents a `fn x(&self);`.
1863 /// Represents a `fn x(&mut self);`.
1865 /// Represents when a function does not have a self argument or
1866 /// when a function has a `self: X` argument.
1870 impl ImplicitSelfKind {
1871 /// Does this represent an implicit self?
1872 pub fn has_implicit_self(&self) -> bool {
1874 ImplicitSelfKind::None => false,
1880 /// Is the trait definition an auto trait?
1881 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1887 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1893 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1899 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1900 pub enum Constness {
1905 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1906 pub enum Defaultness {
1907 Default { has_value: bool },
1912 pub fn has_value(&self) -> bool {
1914 Defaultness::Default { has_value, .. } => has_value,
1915 Defaultness::Final => true,
1919 pub fn is_final(&self) -> bool {
1920 *self == Defaultness::Final
1923 pub fn is_default(&self) -> bool {
1925 Defaultness::Default { .. } => true,
1931 impl fmt::Display for Unsafety {
1932 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1933 fmt::Display::fmt(match *self {
1934 Unsafety::Normal => "normal",
1935 Unsafety::Unsafe => "unsafe",
1941 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
1942 pub enum ImplPolarity {
1943 /// `impl Trait for Type`
1945 /// `impl !Trait for Type`
1949 impl fmt::Debug for ImplPolarity {
1950 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1952 ImplPolarity::Positive => "positive".fmt(f),
1953 ImplPolarity::Negative => "negative".fmt(f),
1959 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1960 pub enum FunctionRetTy {
1961 /// Return type is not specified.
1963 /// Functions default to `()` and
1964 /// closures default to inference. Span points to where return
1965 /// type would be inserted.
1966 DefaultReturn(Span),
1971 impl fmt::Display for FunctionRetTy {
1972 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1974 Return(ref ty) => print::to_string(print::NO_ANN, |s| s.print_type(ty)).fmt(f),
1975 DefaultReturn(_) => "()".fmt(f),
1980 impl FunctionRetTy {
1981 pub fn span(&self) -> Span {
1983 DefaultReturn(span) => span,
1984 Return(ref ty) => ty.span,
1989 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1991 /// A span from the first token past `{` to the last token until `}`.
1992 /// For `mod foo;`, the inner span ranges from the first token
1993 /// to the last token in the external file.
1995 pub item_ids: HirVec<ItemId>,
1998 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1999 pub struct ForeignMod {
2001 pub items: HirVec<ForeignItem>,
2004 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2005 pub struct GlobalAsm {
2007 pub ctxt: SyntaxContext,
2010 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2011 pub struct EnumDef {
2012 pub variants: HirVec<Variant>,
2015 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2016 pub struct VariantKind {
2018 pub attrs: HirVec<Attribute>,
2019 pub data: VariantData,
2020 /// Explicit discriminant, e.g., `Foo = 1`
2021 pub disr_expr: Option<AnonConst>,
2024 pub type Variant = Spanned<VariantKind>;
2026 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
2028 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2029 /// Also produced for each element of a list `use`, e.g.
2030 // `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2033 /// Glob import, e.g., `use foo::*`.
2036 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2037 /// an additional `use foo::{}` for performing checks such as
2038 /// unstable feature gating. May be removed in the future.
2042 /// TraitRef's appear in impls.
2044 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
2045 /// that the ref_id is for. Note that ref_id's value is not the NodeId of the
2046 /// trait being referred to but just a unique NodeId that serves as a key
2047 /// within the DefMap.
2048 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2049 pub struct TraitRef {
2052 pub hir_ref_id: HirId,
2056 /// Get the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2057 pub fn trait_def_id(&self) -> DefId {
2058 match self.path.def {
2059 Def::Trait(did) => did,
2060 Def::TraitAlias(did) => did,
2064 _ => unreachable!(),
2069 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2070 pub struct PolyTraitRef {
2071 /// The `'a` in `<'a> Foo<&'a T>`
2072 pub bound_generic_params: HirVec<GenericParam>,
2074 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
2075 pub trait_ref: TraitRef,
2080 pub type Visibility = Spanned<VisibilityKind>;
2082 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2083 pub enum VisibilityKind {
2086 Restricted { path: P<Path>, id: NodeId, hir_id: HirId },
2090 impl VisibilityKind {
2091 pub fn is_pub(&self) -> bool {
2093 VisibilityKind::Public => true,
2098 pub fn is_pub_restricted(&self) -> bool {
2100 VisibilityKind::Public |
2101 VisibilityKind::Inherited => false,
2102 VisibilityKind::Crate(..) |
2103 VisibilityKind::Restricted { .. } => true,
2107 pub fn descr(&self) -> &'static str {
2109 VisibilityKind::Public => "public",
2110 VisibilityKind::Inherited => "private",
2111 VisibilityKind::Crate(..) => "crate-visible",
2112 VisibilityKind::Restricted { .. } => "restricted",
2117 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2118 pub struct StructField {
2121 pub vis: Visibility,
2125 pub attrs: HirVec<Attribute>,
2129 // Still necessary in couple of places
2130 pub fn is_positional(&self) -> bool {
2131 let first = self.ident.as_str().as_bytes()[0];
2132 first >= b'0' && first <= b'9'
2136 /// Fields and Ids of enum variants and structs
2138 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
2139 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
2140 /// One shared Id can be successfully used for these two purposes.
2141 /// Id of the whole enum lives in `Item`.
2143 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
2144 /// used for `Struct`-structs (but still present). Structures don't have an analogue of "Id of
2145 /// the variant itself" from enum variants.
2146 /// Id of the whole struct lives in `Item`.
2147 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2148 pub enum VariantData {
2149 Struct(HirVec<StructField>, NodeId, HirId),
2150 Tuple(HirVec<StructField>, NodeId, HirId),
2151 Unit(NodeId, HirId),
2155 pub fn fields(&self) -> &[StructField] {
2157 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2161 pub fn id(&self) -> NodeId {
2163 VariantData::Struct(_, id, ..)
2164 | VariantData::Tuple(_, id, ..)
2165 | VariantData::Unit(id, ..) => id,
2168 pub fn hir_id(&self) -> HirId {
2170 VariantData::Struct(_, _, hir_id)
2171 | VariantData::Tuple(_, _, hir_id)
2172 | VariantData::Unit(_, hir_id) => hir_id,
2175 pub fn is_struct(&self) -> bool {
2176 if let VariantData::Struct(..) = *self {
2182 pub fn is_tuple(&self) -> bool {
2183 if let VariantData::Tuple(..) = *self {
2189 pub fn is_unit(&self) -> bool {
2190 if let VariantData::Unit(..) = *self {
2198 // The bodies for items are stored "out of line", in a separate
2199 // hashmap in the `Crate`. Here we just record the node-id of the item
2200 // so it can fetched later.
2201 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2208 /// The name might be a dummy name in case of anonymous items
2209 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2214 pub attrs: HirVec<Attribute>,
2216 pub vis: Visibility,
2220 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2221 pub struct FnHeader {
2222 pub unsafety: Unsafety,
2223 pub constness: Constness,
2224 pub asyncness: IsAsync,
2228 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2230 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2232 /// e.g., `extern crate foo` or `extern crate foo_bar as foo`
2233 ExternCrate(Option<Name>),
2235 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2239 /// `use foo::bar::baz;` (with `as baz` implicitly on the right)
2240 Use(P<Path>, UseKind),
2243 Static(P<Ty>, Mutability, BodyId),
2245 Const(P<Ty>, BodyId),
2246 /// A function declaration
2247 Fn(P<FnDecl>, FnHeader, Generics, BodyId),
2250 /// An external module
2251 ForeignMod(ForeignMod),
2252 /// Module-level inline assembly (from global_asm!)
2253 GlobalAsm(P<GlobalAsm>),
2254 /// A type alias, e.g., `type Foo = Bar<u8>`
2255 Ty(P<Ty>, Generics),
2256 /// An existential type definition, e.g., `existential type Foo: Bar;`
2257 Existential(ExistTy),
2258 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`
2259 Enum(EnumDef, Generics),
2260 /// A struct definition, e.g., `struct Foo<A> {x: A}`
2261 Struct(VariantData, Generics),
2262 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`
2263 Union(VariantData, Generics),
2264 /// Represents a Trait Declaration
2265 Trait(IsAuto, Unsafety, Generics, GenericBounds, HirVec<TraitItemRef>),
2266 /// Represents a Trait Alias Declaration
2267 TraitAlias(Generics, GenericBounds),
2269 /// An implementation, eg `impl<A> Trait for Foo { .. }`
2274 Option<TraitRef>, // (optional) trait this impl implements
2276 HirVec<ImplItemRef>),
2280 pub fn descriptive_variant(&self) -> &str {
2282 ItemKind::ExternCrate(..) => "extern crate",
2283 ItemKind::Use(..) => "use",
2284 ItemKind::Static(..) => "static item",
2285 ItemKind::Const(..) => "constant item",
2286 ItemKind::Fn(..) => "function",
2287 ItemKind::Mod(..) => "module",
2288 ItemKind::ForeignMod(..) => "foreign module",
2289 ItemKind::GlobalAsm(..) => "global asm",
2290 ItemKind::Ty(..) => "type alias",
2291 ItemKind::Existential(..) => "existential type",
2292 ItemKind::Enum(..) => "enum",
2293 ItemKind::Struct(..) => "struct",
2294 ItemKind::Union(..) => "union",
2295 ItemKind::Trait(..) => "trait",
2296 ItemKind::TraitAlias(..) => "trait alias",
2297 ItemKind::Impl(..) => "item",
2301 pub fn adt_kind(&self) -> Option<AdtKind> {
2303 ItemKind::Struct(..) => Some(AdtKind::Struct),
2304 ItemKind::Union(..) => Some(AdtKind::Union),
2305 ItemKind::Enum(..) => Some(AdtKind::Enum),
2310 pub fn generics(&self) -> Option<&Generics> {
2312 ItemKind::Fn(_, _, ref generics, _) |
2313 ItemKind::Ty(_, ref generics) |
2314 ItemKind::Existential(ExistTy { ref generics, impl_trait_fn: None, .. }) |
2315 ItemKind::Enum(_, ref generics) |
2316 ItemKind::Struct(_, ref generics) |
2317 ItemKind::Union(_, ref generics) |
2318 ItemKind::Trait(_, _, ref generics, _, _) |
2319 ItemKind::Impl(_, _, _, ref generics, _, _, _)=> generics,
2325 /// A reference from an trait to one of its associated items. This
2326 /// contains the item's id, naturally, but also the item's name and
2327 /// some other high-level details (like whether it is an associated
2328 /// type or method, and whether it is public). This allows other
2329 /// passes to find the impl they want without loading the id (which
2330 /// means fewer edges in the incremental compilation graph).
2331 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2332 pub struct TraitItemRef {
2333 pub id: TraitItemId,
2335 pub kind: AssociatedItemKind,
2337 pub defaultness: Defaultness,
2340 /// A reference from an impl to one of its associated items. This
2341 /// contains the item's id, naturally, but also the item's name and
2342 /// some other high-level details (like whether it is an associated
2343 /// type or method, and whether it is public). This allows other
2344 /// passes to find the impl they want without loading the id (which
2345 /// means fewer edges in the incremental compilation graph).
2346 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2347 pub struct ImplItemRef {
2350 pub kind: AssociatedItemKind,
2352 pub vis: Visibility,
2353 pub defaultness: Defaultness,
2356 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
2357 pub enum AssociatedItemKind {
2359 Method { has_self: bool },
2364 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2365 pub struct ForeignItem {
2367 pub attrs: HirVec<Attribute>,
2368 pub node: ForeignItemKind,
2372 pub vis: Visibility,
2375 /// An item within an `extern` block
2376 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2377 pub enum ForeignItemKind {
2378 /// A foreign function
2379 Fn(P<FnDecl>, HirVec<Ident>, Generics),
2380 /// A foreign static item (`static ext: u8`), with optional mutability
2381 /// (the boolean is true when mutable)
2382 Static(P<Ty>, bool),
2387 impl ForeignItemKind {
2388 pub fn descriptive_variant(&self) -> &str {
2390 ForeignItemKind::Fn(..) => "foreign function",
2391 ForeignItemKind::Static(..) => "foreign static item",
2392 ForeignItemKind::Type => "foreign type",
2397 /// A free variable referred to in a function.
2398 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable)]
2399 pub struct Freevar {
2400 /// The variable being accessed free.
2403 // First span where it is accessed (there can be multiple).
2408 pub fn var_id(&self) -> NodeId {
2410 Def::Local(id) | Def::Upvar(id, ..) => id,
2411 _ => bug!("Freevar::var_id: bad def ({:?})", self.def)
2416 pub type FreevarMap = NodeMap<Vec<Freevar>>;
2418 pub type CaptureModeMap = NodeMap<CaptureClause>;
2420 #[derive(Clone, Debug)]
2421 pub struct TraitCandidate {
2423 pub import_id: Option<NodeId>,
2426 // Trait method resolution
2427 pub type TraitMap = NodeMap<Vec<TraitCandidate>>;
2429 // Map from the NodeId of a glob import to a list of items which are actually
2431 pub type GlobMap = NodeMap<FxHashSet<Name>>;
2434 pub fn provide(providers: &mut Providers<'_>) {
2435 check_attr::provide(providers);
2436 providers.describe_def = map::describe_def;
2439 #[derive(Clone, RustcEncodable, RustcDecodable)]
2440 pub struct CodegenFnAttrs {
2441 pub flags: CodegenFnAttrFlags,
2442 /// Parsed representation of the `#[inline]` attribute
2443 pub inline: InlineAttr,
2444 /// Parsed representation of the `#[optimize]` attribute
2445 pub optimize: OptimizeAttr,
2446 /// The `#[export_name = "..."]` attribute, indicating a custom symbol a
2447 /// function should be exported under
2448 pub export_name: Option<Symbol>,
2449 /// The `#[link_name = "..."]` attribute, indicating a custom symbol an
2450 /// imported function should be imported as. Note that `export_name`
2451 /// probably isn't set when this is set, this is for foreign items while
2452 /// `#[export_name]` is for Rust-defined functions.
2453 pub link_name: Option<Symbol>,
2454 /// The `#[target_feature(enable = "...")]` attribute and the enabled
2455 /// features (only enabled features are supported right now).
2456 pub target_features: Vec<Symbol>,
2457 /// The `#[linkage = "..."]` attribute and the value we found.
2458 pub linkage: Option<Linkage>,
2459 /// The `#[link_section = "..."]` attribute, or what executable section this
2460 /// should be placed in.
2461 pub link_section: Option<Symbol>,
2465 #[derive(RustcEncodable, RustcDecodable)]
2466 pub struct CodegenFnAttrFlags: u32 {
2467 /// #[cold], a hint to LLVM that this function, when called, is never on
2469 const COLD = 1 << 0;
2470 /// #[allocator], a hint to LLVM that the pointer returned from this
2471 /// function is never null
2472 const ALLOCATOR = 1 << 1;
2473 /// #[unwind], an indicator that this function may unwind despite what
2474 /// its ABI signature may otherwise imply
2475 const UNWIND = 1 << 2;
2476 /// #[rust_allocator_nounwind], an indicator that an imported FFI
2477 /// function will never unwind. Probably obsolete by recent changes with
2478 /// #[unwind], but hasn't been removed/migrated yet
2479 const RUSTC_ALLOCATOR_NOUNWIND = 1 << 3;
2480 /// #[naked], indicates to LLVM that no function prologue/epilogue
2481 /// should be generated
2482 const NAKED = 1 << 4;
2483 /// #[no_mangle], the function's name should be the same as its symbol
2484 const NO_MANGLE = 1 << 5;
2485 /// #[rustc_std_internal_symbol], and indicator that this symbol is a
2486 /// "weird symbol" for the standard library in that it has slightly
2487 /// different linkage, visibility, and reachability rules.
2488 const RUSTC_STD_INTERNAL_SYMBOL = 1 << 6;
2489 /// #[no_debug], indicates that no debugging information should be
2490 /// generated for this function by LLVM
2491 const NO_DEBUG = 1 << 7;
2492 /// #[thread_local], indicates a static is actually a thread local
2494 const THREAD_LOCAL = 1 << 8;
2495 /// #[used], indicates that LLVM can't eliminate this function (but the
2497 const USED = 1 << 9;
2501 impl CodegenFnAttrs {
2502 pub fn new() -> CodegenFnAttrs {
2504 flags: CodegenFnAttrFlags::empty(),
2505 inline: InlineAttr::None,
2506 optimize: OptimizeAttr::None,
2509 target_features: vec![],
2515 /// True if `#[inline]` or `#[inline(always)]` is present.
2516 pub fn requests_inline(&self) -> bool {
2518 InlineAttr::Hint | InlineAttr::Always => true,
2519 InlineAttr::None | InlineAttr::Never => false,
2523 /// True if it looks like this symbol needs to be exported, for example:
2525 /// * `#[no_mangle]` is present
2526 /// * `#[export_name(...)]` is present
2527 /// * `#[linkage]` is present
2528 pub fn contains_extern_indicator(&self) -> bool {
2529 self.flags.contains(CodegenFnAttrFlags::NO_MANGLE) ||
2530 self.export_name.is_some() ||
2531 match self.linkage {
2532 // these are private, make sure we don't try to consider
2535 Some(Linkage::Internal) |
2536 Some(Linkage::Private) => false,
2542 #[derive(Copy, Clone, Debug)]
2543 pub enum Node<'hir> {
2545 ForeignItem(&'hir ForeignItem),
2546 TraitItem(&'hir TraitItem),
2547 ImplItem(&'hir ImplItem),
2548 Variant(&'hir Variant),
2549 Field(&'hir StructField),
2550 AnonConst(&'hir AnonConst),
2553 PathSegment(&'hir PathSegment),
2555 TraitRef(&'hir TraitRef),
2560 MacroDef(&'hir MacroDef),
2562 /// StructCtor represents a tuple struct.
2563 StructCtor(&'hir VariantData),
2565 Lifetime(&'hir Lifetime),
2566 GenericParam(&'hir GenericParam),
2567 Visibility(&'hir Visibility),