1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // HIR datatypes. See the [rustc guide] for more info.
13 //! [rustc guide]: https://rust-lang.github.io/rustc-guide/hir.html
15 pub use self::BlockCheckMode::*;
16 pub use self::CaptureClause::*;
17 pub use self::FunctionRetTy::*;
18 pub use self::Mutability::*;
19 pub use self::PrimTy::*;
20 pub use self::UnOp::*;
21 pub use self::UnsafeSource::*;
24 use hir::def_id::{DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX};
25 use util::nodemap::{NodeMap, FxHashSet};
26 use mir::mono::Linkage;
28 use syntax_pos::{Span, DUMMY_SP, symbol::InternedString};
29 use syntax::source_map::{self, Spanned};
30 use rustc_target::spec::abi::Abi;
31 use syntax::ast::{self, CrateSugar, Ident, Name, NodeId, DUMMY_NODE_ID, AsmDialect};
32 use syntax::ast::{Attribute, Lit, StrStyle, FloatTy, IntTy, UintTy};
33 use syntax::attr::InlineAttr;
34 use syntax::ext::hygiene::SyntaxContext;
36 use syntax::symbol::{Symbol, keywords};
37 use syntax::tokenstream::TokenStream;
38 use syntax::util::parser::ExprPrecedence;
40 use ty::query::Providers;
42 use rustc_data_structures::sync::{ParallelIterator, par_iter, Send, Sync, scope};
43 use rustc_data_structures::thin_vec::ThinVec;
45 use serialize::{self, Encoder, Encodable, Decoder, Decodable};
46 use std::collections::BTreeMap;
49 /// HIR doesn't commit to a concrete storage type and has its own alias for a vector.
50 /// It can be `Vec`, `P<[T]>` or potentially `Box<[T]>`, or some other container with similar
51 /// behavior. Unlike AST, HIR is mostly a static structure, so we can use an owned slice instead
52 /// of `Vec` to avoid keeping extra capacity.
53 pub type HirVec<T> = P<[T]>;
55 macro_rules! hir_vec {
56 ($elem:expr; $n:expr) => (
57 $crate::hir::HirVec::from(vec![$elem; $n])
60 $crate::hir::HirVec::from(vec![$($x),*])
68 pub mod itemlikevisit;
74 /// A HirId uniquely identifies a node in the HIR of the current crate. It is
75 /// composed of the `owner`, which is the DefIndex of the directly enclosing
76 /// hir::Item, hir::TraitItem, or hir::ImplItem (i.e., the closest "item-like"),
77 /// and the `local_id` which is unique within the given owner.
79 /// This two-level structure makes for more stable values: One can move an item
80 /// around within the source code, or add or remove stuff before it, without
81 /// the local_id part of the HirId changing, which is a very useful property in
82 /// incremental compilation where we have to persist things through changes to
84 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
87 pub local_id: ItemLocalId,
91 pub fn owner_def_id(self) -> DefId {
92 DefId::local(self.owner)
95 pub fn owner_local_def_id(self) -> LocalDefId {
96 LocalDefId::from_def_id(DefId::local(self.owner))
100 impl serialize::UseSpecializedEncodable for HirId {
101 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
112 impl serialize::UseSpecializedDecodable for HirId {
113 fn default_decode<D: Decoder>(d: &mut D) -> Result<HirId, D::Error> {
114 let owner = DefIndex::decode(d)?;
115 let local_id = ItemLocalId::decode(d)?;
124 // hack to ensure that we don't try to access the private parts of `ItemLocalId` in this module
125 mod item_local_id_inner {
126 use rustc_data_structures::indexed_vec::Idx;
127 /// An `ItemLocalId` uniquely identifies something within a given "item-like",
128 /// that is within a hir::Item, hir::TraitItem, or hir::ImplItem. There is no
129 /// guarantee that the numerical value of a given `ItemLocalId` corresponds to
130 /// the node's position within the owning item in any way, but there is a
131 /// guarantee that the `LocalItemId`s within an owner occupy a dense range of
132 /// integers starting at zero, so a mapping that maps all or most nodes within
133 /// an "item-like" to something else can be implement by a `Vec` instead of a
134 /// tree or hash map.
136 pub struct ItemLocalId { .. }
140 pub use self::item_local_id_inner::ItemLocalId;
142 /// The `HirId` corresponding to CRATE_NODE_ID and CRATE_DEF_INDEX
143 pub const CRATE_HIR_ID: HirId = HirId {
144 owner: CRATE_DEF_INDEX,
145 local_id: ItemLocalId::from_u32_const(0)
148 pub const DUMMY_HIR_ID: HirId = HirId {
149 owner: CRATE_DEF_INDEX,
150 local_id: DUMMY_ITEM_LOCAL_ID,
153 pub const DUMMY_ITEM_LOCAL_ID: ItemLocalId = ItemLocalId::MAX;
155 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
160 impl fmt::Debug for Label {
161 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162 write!(f, "label({:?})", self.ident)
166 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
167 pub struct Lifetime {
171 /// Either "'a", referring to a named lifetime definition,
172 /// or "" (aka keywords::Invalid), for elision placeholders.
174 /// HIR lowering inserts these placeholders in type paths that
175 /// refer to type definitions needing lifetime parameters,
176 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
177 pub name: LifetimeName,
180 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
182 /// Some user-given name like `T` or `'x`.
185 /// Synthetic name generated when user elided a lifetime in an impl header,
186 /// e.g., the lifetimes in cases like these:
188 /// impl Foo for &u32
189 /// impl Foo<'_> for u32
191 /// in that case, we rewrite to
193 /// impl<'f> Foo for &'f u32
194 /// impl<'f> Foo<'f> for u32
196 /// where `'f` is something like `Fresh(0)`. The indices are
197 /// unique per impl, but not necessarily continuous.
200 /// Indicates an illegal name was given and an error has been
201 /// repored (so we should squelch other derived errors). Occurs
202 /// when e.g., `'_` is used in the wrong place.
207 pub fn ident(&self) -> Ident {
209 ParamName::Plain(ident) => ident,
210 ParamName::Error | ParamName::Fresh(_) => keywords::UnderscoreLifetime.ident(),
214 pub fn modern(&self) -> ParamName {
216 ParamName::Plain(ident) => ParamName::Plain(ident.modern()),
217 param_name => param_name,
222 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
223 pub enum LifetimeName {
224 /// User-given names or fresh (synthetic) names.
227 /// User typed nothing. e.g., the lifetime in `&u32`.
230 /// Indicates an error during lowering (usually `'_` in wrong place)
231 /// that was already reported.
237 /// User wrote `'static`
242 pub fn ident(&self) -> Ident {
244 LifetimeName::Implicit => keywords::Invalid.ident(),
245 LifetimeName::Error => keywords::Invalid.ident(),
246 LifetimeName::Underscore => keywords::UnderscoreLifetime.ident(),
247 LifetimeName::Static => keywords::StaticLifetime.ident(),
248 LifetimeName::Param(param_name) => param_name.ident(),
252 pub fn is_elided(&self) -> bool {
254 LifetimeName::Implicit | LifetimeName::Underscore => true,
256 // It might seem surprising that `Fresh(_)` counts as
257 // *not* elided -- but this is because, as far as the code
258 // in the compiler is concerned -- `Fresh(_)` variants act
259 // equivalently to "some fresh name". They correspond to
260 // early-bound regions on an impl, in other words.
261 LifetimeName::Error | LifetimeName::Param(_) | LifetimeName::Static => false,
265 fn is_static(&self) -> bool {
266 self == &LifetimeName::Static
269 pub fn modern(&self) -> LifetimeName {
271 LifetimeName::Param(param_name) => LifetimeName::Param(param_name.modern()),
272 lifetime_name => lifetime_name,
277 impl fmt::Display for Lifetime {
278 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
279 self.name.ident().fmt(f)
283 impl fmt::Debug for Lifetime {
284 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
288 print::to_string(print::NO_ANN, |s| s.print_lifetime(self)))
293 pub fn is_elided(&self) -> bool {
294 self.name.is_elided()
297 pub fn is_static(&self) -> bool {
298 self.name.is_static()
302 /// A "Path" is essentially Rust's notion of a name; for instance:
303 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
304 /// along with a bunch of supporting information.
305 #[derive(Clone, RustcEncodable, RustcDecodable)]
308 /// The definition that the path resolved to.
310 /// The segments in the path: the things separated by `::`.
311 pub segments: HirVec<PathSegment>,
315 pub fn is_global(&self) -> bool {
316 !self.segments.is_empty() && self.segments[0].ident.name == keywords::PathRoot.name()
320 impl fmt::Debug for Path {
321 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
322 write!(f, "path({})", self)
326 impl fmt::Display for Path {
327 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
328 write!(f, "{}", print::to_string(print::NO_ANN, |s| s.print_path(self, false)))
332 /// A segment of a path: an identifier, an optional lifetime, and a set of
334 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
335 pub struct PathSegment {
336 /// The identifier portion of this path segment.
338 // `id` and `def` are optional. We currently only use these in save-analysis,
339 // any path segments without these will not have save-analysis info and
340 // therefore will not have 'jump to def' in IDEs, but otherwise will not be
341 // affected. (In general, we don't bother to get the defs for synthesized
342 // segments, only for segments which have come from the AST).
343 pub id: Option<NodeId>,
344 pub def: Option<Def>,
346 /// Type/lifetime parameters attached to this path. They come in
347 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
348 /// this is more than just simple syntactic sugar; the use of
349 /// parens affects the region binding rules, so we preserve the
351 pub args: Option<P<GenericArgs>>,
353 /// Whether to infer remaining type parameters, if any.
354 /// This only applies to expression and pattern paths, and
355 /// out of those only the segments with no type parameters
356 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
357 pub infer_types: bool,
361 /// Convert an identifier to the corresponding segment.
362 pub fn from_ident(ident: Ident) -> PathSegment {
384 args: if args.is_empty() {
392 // FIXME: hack required because you can't create a static
393 // `GenericArgs`, so you can't just return a `&GenericArgs`.
394 pub fn with_generic_args<F, R>(&self, f: F) -> R
395 where F: FnOnce(&GenericArgs) -> R
397 let dummy = GenericArgs::none();
398 f(if let Some(ref args) = self.args {
406 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
407 pub enum GenericArg {
413 pub fn span(&self) -> Span {
415 GenericArg::Lifetime(l) => l.span,
416 GenericArg::Type(t) => t.span,
420 pub fn id(&self) -> NodeId {
422 GenericArg::Lifetime(l) => l.id,
423 GenericArg::Type(t) => t.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 {
468 bug!("GenericArgs::inputs: not a `Fn(T) -> U`");
471 pub fn own_counts(&self) -> GenericParamCount {
472 // We could cache this as a property of `GenericParamCount`, but
473 // the aim is to refactor this away entirely eventually and the
474 // presence of this method will be a constant reminder.
475 let mut own_counts: GenericParamCount = Default::default();
477 for arg in &self.args {
479 GenericArg::Lifetime(_) => own_counts.lifetimes += 1,
480 GenericArg::Type(_) => own_counts.types += 1,
488 /// A modifier on a bound, currently this is only used for `?Sized`, where the
489 /// modifier is `Maybe`. Negative bounds should also be handled here.
490 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
491 pub enum TraitBoundModifier {
496 /// The AST represents all type param bounds as types.
497 /// `typeck::collect::compute_bounds` matches these against
498 /// the "special" built-in traits (see `middle::lang_items`) and
499 /// detects `Copy`, `Send` and `Sync`.
500 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
501 pub enum GenericBound {
502 Trait(PolyTraitRef, TraitBoundModifier),
507 pub fn span(&self) -> Span {
509 &GenericBound::Trait(ref t, ..) => t.span,
510 &GenericBound::Outlives(ref l) => l.span,
515 pub type GenericBounds = HirVec<GenericBound>;
517 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
518 pub enum LifetimeParamKind {
519 // Indicates that the lifetime definition was explicitly declared (e.g., in
520 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
523 // Indicates that the lifetime definition was synthetically added
524 // as a result of an in-band lifetime usage (e.g., in
525 // `fn foo(x: &'a u8) -> &'a u8 { x }`).
528 // Indication that the lifetime was elided (e.g., in both cases in
529 // `fn foo(x: &u8) -> &'_ u8 { x }`).
532 // Indication that the lifetime name was somehow in error.
536 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
537 pub enum GenericParamKind {
538 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
540 kind: LifetimeParamKind,
543 default: Option<P<Ty>>,
544 synthetic: Option<SyntheticTyParamKind>,
548 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
549 pub struct GenericParam {
552 pub attrs: HirVec<Attribute>,
553 pub bounds: GenericBounds,
555 pub pure_wrt_drop: bool,
557 pub kind: GenericParamKind,
561 pub struct GenericParamCount {
562 pub lifetimes: usize,
566 /// Represents lifetimes and type parameters attached to a declaration
567 /// of a function, enum, trait, etc.
568 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
569 pub struct Generics {
570 pub params: HirVec<GenericParam>,
571 pub where_clause: WhereClause,
576 pub fn empty() -> Generics {
578 params: HirVec::new(),
579 where_clause: WhereClause {
581 predicates: HirVec::new(),
587 pub fn own_counts(&self) -> GenericParamCount {
588 // We could cache this as a property of `GenericParamCount`, but
589 // the aim is to refactor this away entirely eventually and the
590 // presence of this method will be a constant reminder.
591 let mut own_counts: GenericParamCount = Default::default();
593 for param in &self.params {
595 GenericParamKind::Lifetime { .. } => own_counts.lifetimes += 1,
596 GenericParamKind::Type { .. } => own_counts.types += 1,
603 pub fn get_named(&self, name: &InternedString) -> Option<&GenericParam> {
604 for param in &self.params {
605 if *name == param.name.ident().as_interned_str() {
613 /// Synthetic Type Parameters are converted to an other form during lowering, this allows
614 /// to track the original form they had. Useful for error messages.
615 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
616 pub enum SyntheticTyParamKind {
620 /// A `where` clause in a definition
621 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
622 pub struct WhereClause {
624 pub predicates: HirVec<WherePredicate>,
628 pub fn span(&self) -> Option<Span> {
629 self.predicates.iter().map(|predicate| predicate.span())
630 .fold(None, |acc, i| match (acc, i) {
631 (None, i) => Some(i),
639 /// A single predicate in a `where` clause
640 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
641 pub enum WherePredicate {
642 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
643 BoundPredicate(WhereBoundPredicate),
644 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
645 RegionPredicate(WhereRegionPredicate),
646 /// An equality predicate (unsupported).
647 EqPredicate(WhereEqPredicate),
650 impl WherePredicate {
651 pub fn span(&self) -> Span {
653 &WherePredicate::BoundPredicate(ref p) => p.span,
654 &WherePredicate::RegionPredicate(ref p) => p.span,
655 &WherePredicate::EqPredicate(ref p) => p.span,
660 /// A type bound, eg `for<'c> Foo: Send+Clone+'c`
661 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
662 pub struct WhereBoundPredicate {
664 /// Any generics from a `for` binding
665 pub bound_generic_params: HirVec<GenericParam>,
666 /// The type being bounded
667 pub bounded_ty: P<Ty>,
668 /// Trait and lifetime bounds (`Clone+Send+'static`)
669 pub bounds: GenericBounds,
672 /// A lifetime predicate, e.g., `'a: 'b+'c`
673 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
674 pub struct WhereRegionPredicate {
676 pub lifetime: Lifetime,
677 pub bounds: GenericBounds,
680 /// An equality predicate (unsupported), e.g., `T=int`
681 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
682 pub struct WhereEqPredicate {
689 /// The top-level data structure that stores the entire contents of
690 /// the crate currently being compiled.
692 /// For more details, see the [rustc guide].
694 /// [rustc guide]: https://rust-lang.github.io/rustc-guide/hir.html
695 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
698 pub attrs: HirVec<Attribute>,
700 pub exported_macros: HirVec<MacroDef>,
702 // N.B., we use a BTreeMap here so that `visit_all_items` iterates
703 // over the ids in increasing order. In principle it should not
704 // matter what order we visit things in, but in *practice* it
705 // does, because it can affect the order in which errors are
706 // detected, which in turn can make compile-fail tests yield
707 // slightly different results.
708 pub items: BTreeMap<NodeId, Item>,
710 pub trait_items: BTreeMap<TraitItemId, TraitItem>,
711 pub impl_items: BTreeMap<ImplItemId, ImplItem>,
712 pub bodies: BTreeMap<BodyId, Body>,
713 pub trait_impls: BTreeMap<DefId, Vec<NodeId>>,
714 pub trait_auto_impl: BTreeMap<DefId, NodeId>,
716 /// A list of the body ids written out in the order in which they
717 /// appear in the crate. If you're going to process all the bodies
718 /// in the crate, you should iterate over this list rather than the keys
720 pub body_ids: Vec<BodyId>,
724 pub fn item(&self, id: NodeId) -> &Item {
728 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem {
729 &self.trait_items[&id]
732 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem {
733 &self.impl_items[&id]
736 /// Visits all items in the crate in some deterministic (but
737 /// unspecified) order. If you just need to process every item,
738 /// but don't care about nesting, this method is the best choice.
740 /// If you do care about nesting -- usually because your algorithm
741 /// follows lexical scoping rules -- then you want a different
742 /// approach. You should override `visit_nested_item` in your
743 /// visitor and then call `intravisit::walk_crate` instead.
744 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
745 where V: itemlikevisit::ItemLikeVisitor<'hir>
747 for (_, item) in &self.items {
748 visitor.visit_item(item);
751 for (_, trait_item) in &self.trait_items {
752 visitor.visit_trait_item(trait_item);
755 for (_, impl_item) in &self.impl_items {
756 visitor.visit_impl_item(impl_item);
760 /// A parallel version of visit_all_item_likes
761 pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
762 where V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send
766 par_iter(&self.items).for_each(|(_, item)| {
767 visitor.visit_item(item);
772 par_iter(&self.trait_items).for_each(|(_, trait_item)| {
773 visitor.visit_trait_item(trait_item);
778 par_iter(&self.impl_items).for_each(|(_, impl_item)| {
779 visitor.visit_impl_item(impl_item);
785 pub fn body(&self, id: BodyId) -> &Body {
790 /// A macro definition, in this crate or imported from another.
792 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
793 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
794 pub struct MacroDef {
797 pub attrs: HirVec<Attribute>,
800 pub body: TokenStream,
804 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
806 /// Statements in a block
807 pub stmts: HirVec<Stmt>,
808 /// An expression at the end of the block
809 /// without a semicolon, if any
810 pub expr: Option<P<Expr>>,
813 /// Distinguishes between `unsafe { ... }` and `{ ... }`
814 pub rules: BlockCheckMode,
816 /// If true, then there may exist `break 'a` values that aim to
817 /// break out of this block early.
818 /// Used by `'label: {}` blocks and by `catch` statements.
819 pub targeted_by_break: bool,
820 /// If true, don't emit return value type errors as the parser had
821 /// to recover from a parse error so this block will not have an
822 /// appropriate type. A parse error will have been emitted so the
823 /// compilation will never succeed if this is true.
827 #[derive(Clone, RustcEncodable, RustcDecodable)]
835 impl fmt::Debug for Pat {
836 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
837 write!(f, "pat({}: {})", self.id,
838 print::to_string(print::NO_ANN, |s| s.print_pat(self)))
843 // FIXME(#19596) this is a workaround, but there should be a better way
844 fn walk_<G>(&self, it: &mut G) -> bool
845 where G: FnMut(&Pat) -> bool
852 PatKind::Binding(.., Some(ref p)) => p.walk_(it),
853 PatKind::Struct(_, ref fields, _) => {
854 fields.iter().all(|field| field.node.pat.walk_(it))
856 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
857 s.iter().all(|p| p.walk_(it))
859 PatKind::Box(ref s) | PatKind::Ref(ref s, _) => {
862 PatKind::Slice(ref before, ref slice, ref after) => {
866 .all(|p| p.walk_(it))
871 PatKind::Binding(..) |
872 PatKind::Path(_) => {
878 pub fn walk<F>(&self, mut it: F) -> bool
879 where F: FnMut(&Pat) -> bool
885 /// A single field in a struct pattern
887 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
888 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
889 /// except is_shorthand is true
890 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
891 pub struct FieldPat {
893 /// The identifier for the field
895 /// The pattern the field is destructured to
897 pub is_shorthand: bool,
900 /// Explicit binding annotations given in the HIR for a binding. Note
901 /// that this is not the final binding *mode* that we infer after type
903 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
904 pub enum BindingAnnotation {
905 /// No binding annotation given: this means that the final binding mode
906 /// will depend on whether we have skipped through a `&` reference
907 /// when matching. For example, the `x` in `Some(x)` will have binding
908 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
909 /// ultimately be inferred to be by-reference.
911 /// Note that implicit reference skipping is not implemented yet (#42640).
914 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
917 /// Annotated as `ref`, like `ref x`
920 /// Annotated as `ref mut x`.
924 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
930 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
932 /// Represents a wildcard pattern (`_`)
935 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
936 /// The `NodeId` is the canonical ID for the variable being bound,
937 /// e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID,
938 /// which is the pattern ID of the first `x`.
939 Binding(BindingAnnotation, NodeId, Ident, Option<P<Pat>>),
941 /// A struct or struct variant pattern, e.g., `Variant {x, y, ..}`.
942 /// The `bool` is `true` in the presence of a `..`.
943 Struct(QPath, HirVec<Spanned<FieldPat>>, bool),
945 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
946 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
947 /// 0 <= position <= subpats.len()
948 TupleStruct(QPath, HirVec<P<Pat>>, Option<usize>),
950 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
953 /// A tuple pattern `(a, b)`.
954 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
955 /// 0 <= position <= subpats.len()
956 Tuple(HirVec<P<Pat>>, Option<usize>),
959 /// A reference pattern, e.g., `&mut (a, b)`
960 Ref(P<Pat>, Mutability),
963 /// A range pattern, e.g., `1...2` or `1..2`
964 Range(P<Expr>, P<Expr>, RangeEnd),
965 /// `[a, b, ..i, y, z]` is represented as:
966 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
967 Slice(HirVec<P<Pat>>, Option<P<Pat>>, HirVec<P<Pat>>),
970 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
971 pub enum Mutability {
977 /// Return MutMutable only if both arguments are mutable.
978 pub fn and(self, other: Self) -> Self {
981 MutImmutable => MutImmutable,
986 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, Hash)]
988 /// The `+` operator (addition)
990 /// The `-` operator (subtraction)
992 /// The `*` operator (multiplication)
994 /// The `/` operator (division)
996 /// The `%` operator (modulus)
998 /// The `&&` operator (logical and)
1000 /// The `||` operator (logical or)
1002 /// The `^` operator (bitwise xor)
1004 /// The `&` operator (bitwise and)
1006 /// The `|` operator (bitwise or)
1008 /// The `<<` operator (shift left)
1010 /// The `>>` operator (shift right)
1012 /// The `==` operator (equality)
1014 /// The `<` operator (less than)
1016 /// The `<=` operator (less than or equal to)
1018 /// The `!=` operator (not equal to)
1020 /// The `>=` operator (greater than or equal to)
1022 /// The `>` operator (greater than)
1027 pub fn as_str(self) -> &'static str {
1029 BinOpKind::Add => "+",
1030 BinOpKind::Sub => "-",
1031 BinOpKind::Mul => "*",
1032 BinOpKind::Div => "/",
1033 BinOpKind::Rem => "%",
1034 BinOpKind::And => "&&",
1035 BinOpKind::Or => "||",
1036 BinOpKind::BitXor => "^",
1037 BinOpKind::BitAnd => "&",
1038 BinOpKind::BitOr => "|",
1039 BinOpKind::Shl => "<<",
1040 BinOpKind::Shr => ">>",
1041 BinOpKind::Eq => "==",
1042 BinOpKind::Lt => "<",
1043 BinOpKind::Le => "<=",
1044 BinOpKind::Ne => "!=",
1045 BinOpKind::Ge => ">=",
1046 BinOpKind::Gt => ">",
1050 pub fn is_lazy(self) -> bool {
1052 BinOpKind::And | BinOpKind::Or => true,
1057 pub fn is_shift(self) -> bool {
1059 BinOpKind::Shl | BinOpKind::Shr => true,
1064 pub fn is_comparison(self) -> bool {
1071 BinOpKind::Ge => true,
1083 BinOpKind::Shr => false,
1087 /// Returns `true` if the binary operator takes its arguments by value
1088 pub fn is_by_value(self) -> bool {
1089 !self.is_comparison()
1093 impl Into<ast::BinOpKind> for BinOpKind {
1094 fn into(self) -> ast::BinOpKind {
1096 BinOpKind::Add => ast::BinOpKind::Add,
1097 BinOpKind::Sub => ast::BinOpKind::Sub,
1098 BinOpKind::Mul => ast::BinOpKind::Mul,
1099 BinOpKind::Div => ast::BinOpKind::Div,
1100 BinOpKind::Rem => ast::BinOpKind::Rem,
1101 BinOpKind::And => ast::BinOpKind::And,
1102 BinOpKind::Or => ast::BinOpKind::Or,
1103 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1104 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1105 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1106 BinOpKind::Shl => ast::BinOpKind::Shl,
1107 BinOpKind::Shr => ast::BinOpKind::Shr,
1108 BinOpKind::Eq => ast::BinOpKind::Eq,
1109 BinOpKind::Lt => ast::BinOpKind::Lt,
1110 BinOpKind::Le => ast::BinOpKind::Le,
1111 BinOpKind::Ne => ast::BinOpKind::Ne,
1112 BinOpKind::Ge => ast::BinOpKind::Ge,
1113 BinOpKind::Gt => ast::BinOpKind::Gt,
1118 pub type BinOp = Spanned<BinOpKind>;
1120 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, Hash)]
1122 /// The `*` operator for dereferencing
1124 /// The `!` operator for logical inversion
1126 /// The `-` operator for negation
1131 pub fn as_str(self) -> &'static str {
1139 /// Returns `true` if the unary operator takes its argument by value
1140 pub fn is_by_value(self) -> bool {
1142 UnNeg | UnNot => true,
1149 pub type Stmt = Spanned<StmtKind>;
1151 impl fmt::Debug for StmtKind {
1152 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1154 let spanned = source_map::dummy_spanned(self.clone());
1158 print::to_string(print::NO_ANN, |s| s.print_stmt(&spanned)))
1162 #[derive(Clone, RustcEncodable, RustcDecodable)]
1164 /// Could be an item or a local (let) binding:
1165 Decl(P<Decl>, NodeId),
1167 /// Expr without trailing semi-colon (must have unit type):
1168 Expr(P<Expr>, NodeId),
1170 /// Expr with trailing semi-colon (may have any type):
1171 Semi(P<Expr>, NodeId),
1175 pub fn attrs(&self) -> &[Attribute] {
1177 StmtKind::Decl(ref d, _) => d.node.attrs(),
1178 StmtKind::Expr(ref e, _) |
1179 StmtKind::Semi(ref e, _) => &e.attrs,
1183 pub fn id(&self) -> NodeId {
1185 StmtKind::Decl(_, id) |
1186 StmtKind::Expr(_, id) |
1187 StmtKind::Semi(_, id) => id,
1192 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
1193 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1196 pub ty: Option<P<Ty>>,
1197 /// Initializer expression to set the value, if any
1198 pub init: Option<P<Expr>>,
1202 pub attrs: ThinVec<Attribute>,
1203 pub source: LocalSource,
1206 pub type Decl = Spanned<DeclKind>;
1208 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1210 /// A local (let) binding:
1212 /// An item binding:
1217 pub fn attrs(&self) -> &[Attribute] {
1219 DeclKind::Local(ref l) => &l.attrs,
1220 DeclKind::Item(_) => &[]
1224 pub fn is_local(&self) -> bool {
1226 DeclKind::Local(_) => true,
1232 /// represents one arm of a 'match'
1233 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1235 pub attrs: HirVec<Attribute>,
1236 pub pats: HirVec<P<Pat>>,
1237 pub guard: Option<Guard>,
1241 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1246 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1252 pub is_shorthand: bool,
1255 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1256 pub enum BlockCheckMode {
1258 UnsafeBlock(UnsafeSource),
1259 PushUnsafeBlock(UnsafeSource),
1260 PopUnsafeBlock(UnsafeSource),
1263 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1264 pub enum UnsafeSource {
1269 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1271 pub node_id: NodeId,
1274 /// The body of a function, closure, or constant value. In the case of
1275 /// a function, the body contains not only the function body itself
1276 /// (which is an expression), but also the argument patterns, since
1277 /// those are something that the caller doesn't really care about.
1282 /// fn foo((x, y): (u32, u32)) -> u32 {
1287 /// Here, the `Body` associated with `foo()` would contain:
1289 /// - an `arguments` array containing the `(x, y)` pattern
1290 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1291 /// - `is_generator` would be false
1293 /// All bodies have an **owner**, which can be accessed via the HIR
1294 /// map using `body_owner_def_id()`.
1295 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1297 pub arguments: HirVec<Arg>,
1299 pub is_generator: bool,
1303 pub fn id(&self) -> BodyId {
1305 node_id: self.value.id
1310 #[derive(Copy, Clone, Debug)]
1311 pub enum BodyOwnerKind {
1312 /// Functions and methods.
1315 /// Constants and associated constants.
1318 /// Initializer of a `static` item.
1322 /// A constant (expression) that's not an item or associated item,
1323 /// but needs its own `DefId` for type-checking, const-eval, etc.
1324 /// These are usually found nested inside types (e.g., array lengths)
1325 /// or expressions (e.g., repeat counts), and also used to define
1326 /// explicit discriminant values for enum variants.
1327 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
1328 pub struct AnonConst {
1335 #[derive(Clone, RustcEncodable, RustcDecodable)]
1340 pub attrs: ThinVec<Attribute>,
1345 pub fn precedence(&self) -> ExprPrecedence {
1347 ExprKind::Box(_) => ExprPrecedence::Box,
1348 ExprKind::Array(_) => ExprPrecedence::Array,
1349 ExprKind::Call(..) => ExprPrecedence::Call,
1350 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1351 ExprKind::Tup(_) => ExprPrecedence::Tup,
1352 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1353 ExprKind::Unary(..) => ExprPrecedence::Unary,
1354 ExprKind::Lit(_) => ExprPrecedence::Lit,
1355 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1356 ExprKind::If(..) => ExprPrecedence::If,
1357 ExprKind::While(..) => ExprPrecedence::While,
1358 ExprKind::Loop(..) => ExprPrecedence::Loop,
1359 ExprKind::Match(..) => ExprPrecedence::Match,
1360 ExprKind::Closure(..) => ExprPrecedence::Closure,
1361 ExprKind::Block(..) => ExprPrecedence::Block,
1362 ExprKind::Assign(..) => ExprPrecedence::Assign,
1363 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1364 ExprKind::Field(..) => ExprPrecedence::Field,
1365 ExprKind::Index(..) => ExprPrecedence::Index,
1366 ExprKind::Path(..) => ExprPrecedence::Path,
1367 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1368 ExprKind::Break(..) => ExprPrecedence::Break,
1369 ExprKind::Continue(..) => ExprPrecedence::Continue,
1370 ExprKind::Ret(..) => ExprPrecedence::Ret,
1371 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1372 ExprKind::Struct(..) => ExprPrecedence::Struct,
1373 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1374 ExprKind::Yield(..) => ExprPrecedence::Yield,
1378 pub fn is_place_expr(&self) -> bool {
1380 ExprKind::Path(QPath::Resolved(_, ref path)) => {
1382 Def::Local(..) | Def::Upvar(..) | Def::Static(..) | Def::Err => true,
1387 ExprKind::Type(ref e, _) => {
1391 ExprKind::Unary(UnDeref, _) |
1392 ExprKind::Field(..) |
1393 ExprKind::Index(..) => {
1397 // Partially qualified paths in expressions can only legally
1398 // refer to associated items which are always rvalues.
1399 ExprKind::Path(QPath::TypeRelative(..)) |
1401 ExprKind::Call(..) |
1402 ExprKind::MethodCall(..) |
1403 ExprKind::Struct(..) |
1406 ExprKind::Match(..) |
1407 ExprKind::Closure(..) |
1408 ExprKind::Block(..) |
1409 ExprKind::Repeat(..) |
1410 ExprKind::Array(..) |
1411 ExprKind::Break(..) |
1412 ExprKind::Continue(..) |
1414 ExprKind::While(..) |
1415 ExprKind::Loop(..) |
1416 ExprKind::Assign(..) |
1417 ExprKind::InlineAsm(..) |
1418 ExprKind::AssignOp(..) |
1420 ExprKind::Unary(..) |
1422 ExprKind::AddrOf(..) |
1423 ExprKind::Binary(..) |
1424 ExprKind::Yield(..) |
1425 ExprKind::Cast(..) => {
1432 impl fmt::Debug for Expr {
1433 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1434 write!(f, "expr({}: {})", self.id,
1435 print::to_string(print::NO_ANN, |s| s.print_expr(self)))
1439 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1441 /// A `box x` expression.
1443 /// An array (`[a, b, c, d]`)
1444 Array(HirVec<Expr>),
1447 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1448 /// and the second field is the list of arguments.
1449 /// This also represents calling the constructor of
1450 /// tuple-like ADTs such as tuple structs and enum variants.
1451 Call(P<Expr>, HirVec<Expr>),
1452 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1454 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1455 /// (within the angle brackets).
1456 /// The first element of the vector of `Expr`s is the expression that evaluates
1457 /// to the object on which the method is being called on (the receiver),
1458 /// and the remaining elements are the rest of the arguments.
1459 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1460 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1461 MethodCall(PathSegment, Span, HirVec<Expr>),
1462 /// A tuple (`(a, b, c ,d)`)
1464 /// A binary operation (For example: `a + b`, `a * b`)
1465 Binary(BinOp, P<Expr>, P<Expr>),
1466 /// A unary operation (For example: `!x`, `*x`)
1467 Unary(UnOp, P<Expr>),
1468 /// A literal (For example: `1`, `"foo"`)
1470 /// A cast (`foo as f64`)
1471 Cast(P<Expr>, P<Ty>),
1472 Type(P<Expr>, P<Ty>),
1473 /// An `if` block, with an optional else block
1475 /// `if expr { expr } else { expr }`
1476 If(P<Expr>, P<Expr>, Option<P<Expr>>),
1477 /// A while loop, with an optional label
1479 /// `'label: while expr { block }`
1480 While(P<Expr>, P<Block>, Option<Label>),
1481 /// Conditionless loop (can be exited with break, continue, or return)
1483 /// `'label: loop { block }`
1484 Loop(P<Block>, Option<Label>, LoopSource),
1485 /// A `match` block, with a source that indicates whether or not it is
1486 /// the result of a desugaring, and if so, which kind.
1487 Match(P<Expr>, HirVec<Arm>, MatchSource),
1488 /// A closure (for example, `move |a, b, c| {a + b + c}`).
1490 /// The final span is the span of the argument block `|...|`
1492 /// This may also be a generator literal, indicated by the final boolean,
1493 /// in that case there is an GeneratorClause.
1494 Closure(CaptureClause, P<FnDecl>, BodyId, Span, Option<GeneratorMovability>),
1495 /// A block (`'label: { ... }`)
1496 Block(P<Block>, Option<Label>),
1498 /// An assignment (`a = foo()`)
1499 Assign(P<Expr>, P<Expr>),
1500 /// An assignment with an operator
1502 /// For example, `a += 1`.
1503 AssignOp(BinOp, P<Expr>, P<Expr>),
1504 /// Access of a named (`obj.foo`) or unnamed (`obj.0`) struct or tuple field
1505 Field(P<Expr>, Ident),
1506 /// An indexing operation (`foo[2]`)
1507 Index(P<Expr>, P<Expr>),
1509 /// Path to a definition, possibly containing lifetime or type parameters.
1512 /// A referencing operation (`&a` or `&mut a`)
1513 AddrOf(Mutability, P<Expr>),
1514 /// A `break`, with an optional label to break
1515 Break(Destination, Option<P<Expr>>),
1516 /// A `continue`, with an optional label
1517 Continue(Destination),
1518 /// A `return`, with an optional value to be returned
1519 Ret(Option<P<Expr>>),
1521 /// Inline assembly (from `asm!`), with its outputs and inputs.
1522 InlineAsm(P<InlineAsm>, HirVec<Expr>, HirVec<Expr>),
1524 /// A struct or struct-like variant literal expression.
1526 /// For example, `Foo {x: 1, y: 2}`, or
1527 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
1528 Struct(QPath, HirVec<Field>, Option<P<Expr>>),
1530 /// An array literal constructed from one repeated element.
1532 /// For example, `[1; 5]`. The first expression is the element
1533 /// to be repeated; the second is the number of times to repeat it.
1534 Repeat(P<Expr>, AnonConst),
1536 /// A suspension point for generators. This is `yield <expr>` in Rust.
1540 /// Optionally `Self`-qualified value/type path or associated extension.
1541 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1543 /// Path to a definition, optionally "fully-qualified" with a `Self`
1544 /// type, if the path points to an associated item in a trait.
1546 /// e.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1547 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1548 /// even though they both have the same two-segment `Clone::clone` `Path`.
1549 Resolved(Option<P<Ty>>, P<Path>),
1551 /// Type-related paths, e.g., `<T>::default` or `<T>::Output`.
1552 /// Will be resolved by type-checking to an associated item.
1554 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1555 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1556 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1557 TypeRelative(P<Ty>, P<PathSegment>)
1560 /// Hints at the original code for a let statement
1561 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1562 pub enum LocalSource {
1563 /// A `match _ { .. }`
1565 /// A desugared `for _ in _ { .. }` loop
1569 /// Hints at the original code for a `match _ { .. }`
1570 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1571 pub enum MatchSource {
1572 /// A `match _ { .. }`
1574 /// An `if let _ = _ { .. }` (optionally with `else { .. }`)
1576 contains_else_clause: bool,
1578 /// A `while let _ = _ { .. }` (which was desugared to a
1579 /// `loop { match _ { .. } }`)
1581 /// A desugared `for _ in _ { .. }` loop
1583 /// A desugared `?` operator
1587 /// The loop type that yielded an ExprKind::Loop
1588 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1589 pub enum LoopSource {
1590 /// A `loop { .. }` loop
1592 /// A `while let _ = _ { .. }` loop
1594 /// A `for _ in _ { .. }` loop
1598 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1599 pub enum LoopIdError {
1601 UnlabeledCfInWhileCondition,
1605 impl fmt::Display for LoopIdError {
1606 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1607 fmt::Display::fmt(match *self {
1608 LoopIdError::OutsideLoopScope => "not inside loop scope",
1609 LoopIdError::UnlabeledCfInWhileCondition =>
1610 "unlabeled control flow (break or continue) in while condition",
1611 LoopIdError::UnresolvedLabel => "label not found",
1616 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1617 pub struct Destination {
1618 // This is `Some(_)` iff there is an explicit user-specified `label
1619 pub label: Option<Label>,
1621 // These errors are caught and then reported during the diagnostics pass in
1622 // librustc_passes/loops.rs
1623 pub target_id: Result<NodeId, LoopIdError>,
1626 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1627 pub enum GeneratorMovability {
1632 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1633 pub enum CaptureClause {
1638 // N.B., if you change this, you'll probably want to change the corresponding
1639 // type structure in middle/ty.rs as well.
1640 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1643 pub mutbl: Mutability,
1646 /// Represents a method's signature in a trait declaration or implementation.
1647 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1648 pub struct MethodSig {
1649 pub header: FnHeader,
1650 pub decl: P<FnDecl>,
1653 // The bodies for items are stored "out of line", in a separate
1654 // hashmap in the `Crate`. Here we just record the node-id of the item
1655 // so it can fetched later.
1656 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1657 pub struct TraitItemId {
1658 pub node_id: NodeId,
1661 /// Represents an item declaration within a trait declaration,
1662 /// possibly including a default implementation. A trait item is
1663 /// either required (meaning it doesn't have an implementation, just a
1664 /// signature) or provided (meaning it has a default implementation).
1665 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1666 pub struct TraitItem {
1670 pub attrs: HirVec<Attribute>,
1671 pub generics: Generics,
1672 pub node: TraitItemKind,
1676 /// A trait method's body (or just argument names).
1677 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1678 pub enum TraitMethod {
1679 /// No default body in the trait, just a signature.
1680 Required(HirVec<Ident>),
1682 /// Both signature and body are provided in the trait.
1686 /// Represents a trait method or associated constant or type
1687 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1688 pub enum TraitItemKind {
1689 /// An associated constant with an optional value (otherwise `impl`s
1690 /// must contain a value)
1691 Const(P<Ty>, Option<BodyId>),
1692 /// A method with an optional body
1693 Method(MethodSig, TraitMethod),
1694 /// An associated type with (possibly empty) bounds and optional concrete
1696 Type(GenericBounds, Option<P<Ty>>),
1699 // The bodies for items are stored "out of line", in a separate
1700 // hashmap in the `Crate`. Here we just record the node-id of the item
1701 // so it can fetched later.
1702 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1703 pub struct ImplItemId {
1704 pub node_id: NodeId,
1707 /// Represents anything within an `impl` block
1708 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1709 pub struct ImplItem {
1713 pub vis: Visibility,
1714 pub defaultness: Defaultness,
1715 pub attrs: HirVec<Attribute>,
1716 pub generics: Generics,
1717 pub node: ImplItemKind,
1721 /// Represents different contents within `impl`s
1722 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1723 pub enum ImplItemKind {
1724 /// An associated constant of the given type, set to the constant result
1725 /// of the expression
1726 Const(P<Ty>, BodyId),
1727 /// A method implementation with the given signature and body
1728 Method(MethodSig, BodyId),
1729 /// An associated type
1731 /// An associated existential type
1732 Existential(GenericBounds),
1735 // Bind a type to an associated type: `A=Foo`.
1736 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1737 pub struct TypeBinding {
1744 #[derive(Clone, RustcEncodable, RustcDecodable)]
1752 impl fmt::Debug for Ty {
1753 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1754 write!(f, "type({})",
1755 print::to_string(print::NO_ANN, |s| s.print_type(self)))
1759 /// Not represented directly in the AST, referred to by name through a ty_path.
1760 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1770 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1771 pub struct BareFnTy {
1772 pub unsafety: Unsafety,
1774 pub generic_params: HirVec<GenericParam>,
1775 pub decl: P<FnDecl>,
1776 pub arg_names: HirVec<Ident>,
1779 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1780 pub struct ExistTy {
1781 pub generics: Generics,
1782 pub bounds: GenericBounds,
1783 pub impl_trait_fn: Option<DefId>,
1786 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1787 /// The different kinds of types recognized by the compiler
1789 /// A variable length slice (`[T]`)
1791 /// A fixed length array (`[T; n]`)
1792 Array(P<Ty>, AnonConst),
1793 /// A raw pointer (`*const T` or `*mut T`)
1795 /// A reference (`&'a T` or `&'a mut T`)
1796 Rptr(Lifetime, MutTy),
1797 /// A bare function (e.g., `fn(usize) -> bool`)
1798 BareFn(P<BareFnTy>),
1799 /// The never type (`!`)
1801 /// A tuple (`(A, B, C, D,...)`)
1803 /// A path to a type definition (`module::module::...::Type`), or an
1804 /// associated type, e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`.
1806 /// Type parameters may be stored in each `PathSegment`.
1808 /// A type definition itself. This is currently only used for the `existential type`
1809 /// item that `impl Trait` in return position desugars to.
1811 /// The generic arg list are the lifetimes (and in the future possibly parameters) that are
1812 /// actually bound on the `impl Trait`.
1813 Def(ItemId, HirVec<GenericArg>),
1814 /// A trait object type `Bound1 + Bound2 + Bound3`
1815 /// where `Bound` is a trait or a lifetime.
1816 TraitObject(HirVec<PolyTraitRef>, Lifetime),
1819 /// `TyKind::Infer` means the type should be inferred instead of it having been
1820 /// specified. This can appear anywhere in a type.
1822 /// Placeholder for a type that has failed to be defined.
1826 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1827 pub struct InlineAsmOutput {
1828 pub constraint: Symbol,
1830 pub is_indirect: bool,
1834 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1835 pub struct InlineAsm {
1837 pub asm_str_style: StrStyle,
1838 pub outputs: HirVec<InlineAsmOutput>,
1839 pub inputs: HirVec<Symbol>,
1840 pub clobbers: HirVec<Symbol>,
1842 pub alignstack: bool,
1843 pub dialect: AsmDialect,
1844 pub ctxt: SyntaxContext,
1847 /// represents an argument in a function header
1848 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1855 /// Represents the header (not the body) of a function declaration
1856 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1858 pub inputs: HirVec<Ty>,
1859 pub output: FunctionRetTy,
1861 /// Does the function have an implicit self?
1862 pub implicit_self: ImplicitSelfKind,
1865 /// Represents what type of implicit self a function has, if any.
1866 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
1867 pub enum ImplicitSelfKind {
1868 /// Represents a `fn x(self);`.
1870 /// Represents a `fn x(mut self);`.
1872 /// Represents a `fn x(&self);`.
1874 /// Represents a `fn x(&mut self);`.
1876 /// Represents when a function does not have a self argument or
1877 /// when a function has a `self: X` argument.
1881 impl ImplicitSelfKind {
1882 /// Does this represent an implicit self?
1883 pub fn has_implicit_self(&self) -> bool {
1885 ImplicitSelfKind::None => false,
1891 /// Is the trait definition an auto trait?
1892 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1898 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1904 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1910 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1911 pub enum Constness {
1916 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1917 pub enum Defaultness {
1918 Default { has_value: bool },
1923 pub fn has_value(&self) -> bool {
1925 Defaultness::Default { has_value, .. } => has_value,
1926 Defaultness::Final => true,
1930 pub fn is_final(&self) -> bool {
1931 *self == Defaultness::Final
1934 pub fn is_default(&self) -> bool {
1936 Defaultness::Default { .. } => true,
1942 impl fmt::Display for Unsafety {
1943 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1944 fmt::Display::fmt(match *self {
1945 Unsafety::Normal => "normal",
1946 Unsafety::Unsafe => "unsafe",
1952 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
1953 pub enum ImplPolarity {
1954 /// `impl Trait for Type`
1956 /// `impl !Trait for Type`
1960 impl fmt::Debug for ImplPolarity {
1961 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1963 ImplPolarity::Positive => "positive".fmt(f),
1964 ImplPolarity::Negative => "negative".fmt(f),
1970 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1971 pub enum FunctionRetTy {
1972 /// Return type is not specified.
1974 /// Functions default to `()` and
1975 /// closures default to inference. Span points to where return
1976 /// type would be inserted.
1977 DefaultReturn(Span),
1982 impl FunctionRetTy {
1983 pub fn span(&self) -> Span {
1985 DefaultReturn(span) => span,
1986 Return(ref ty) => ty.span,
1991 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1993 /// A span from the first token past `{` to the last token until `}`.
1994 /// For `mod foo;`, the inner span ranges from the first token
1995 /// to the last token in the external file.
1997 pub item_ids: HirVec<ItemId>,
2000 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2001 pub struct ForeignMod {
2003 pub items: HirVec<ForeignItem>,
2006 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2007 pub struct GlobalAsm {
2009 pub ctxt: SyntaxContext,
2012 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2013 pub struct EnumDef {
2014 pub variants: HirVec<Variant>,
2017 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2018 pub struct VariantKind {
2020 pub attrs: HirVec<Attribute>,
2021 pub data: VariantData,
2022 /// Explicit discriminant, e.g., `Foo = 1`
2023 pub disr_expr: Option<AnonConst>,
2026 pub type Variant = Spanned<VariantKind>;
2028 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
2030 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2031 /// Also produced for each element of a list `use`, e.g.
2032 // `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2035 /// Glob import, e.g., `use foo::*`.
2038 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2039 /// an additional `use foo::{}` for performing checks such as
2040 /// unstable feature gating. May be removed in the future.
2044 /// TraitRef's appear in impls.
2046 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
2047 /// that the ref_id is for. Note that ref_id's value is not the NodeId of the
2048 /// trait being referred to but just a unique NodeId that serves as a key
2049 /// within the DefMap.
2050 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2051 pub struct TraitRef {
2054 pub hir_ref_id: HirId,
2057 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2058 pub struct PolyTraitRef {
2059 /// The `'a` in `<'a> Foo<&'a T>`
2060 pub bound_generic_params: HirVec<GenericParam>,
2062 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
2063 pub trait_ref: TraitRef,
2068 pub type Visibility = Spanned<VisibilityKind>;
2070 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2071 pub enum VisibilityKind {
2074 Restricted { path: P<Path>, id: NodeId, hir_id: HirId },
2078 impl VisibilityKind {
2079 pub fn is_pub(&self) -> bool {
2081 VisibilityKind::Public => true,
2086 pub fn is_pub_restricted(&self) -> bool {
2088 VisibilityKind::Public |
2089 VisibilityKind::Inherited => false,
2090 VisibilityKind::Crate(..) |
2091 VisibilityKind::Restricted { .. } => true,
2096 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2097 pub struct StructField {
2100 pub vis: Visibility,
2103 pub attrs: HirVec<Attribute>,
2107 // Still necessary in couple of places
2108 pub fn is_positional(&self) -> bool {
2109 let first = self.ident.as_str().as_bytes()[0];
2110 first >= b'0' && first <= b'9'
2114 /// Fields and Ids of enum variants and structs
2116 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
2117 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
2118 /// One shared Id can be successfully used for these two purposes.
2119 /// Id of the whole enum lives in `Item`.
2121 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
2122 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
2123 /// the variant itself" from enum variants.
2124 /// Id of the whole struct lives in `Item`.
2125 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2126 pub enum VariantData {
2127 Struct(HirVec<StructField>, NodeId),
2128 Tuple(HirVec<StructField>, NodeId),
2133 pub fn fields(&self) -> &[StructField] {
2135 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
2139 pub fn id(&self) -> NodeId {
2141 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id,
2144 pub fn is_struct(&self) -> bool {
2145 if let VariantData::Struct(..) = *self {
2151 pub fn is_tuple(&self) -> bool {
2152 if let VariantData::Tuple(..) = *self {
2158 pub fn is_unit(&self) -> bool {
2159 if let VariantData::Unit(..) = *self {
2167 // The bodies for items are stored "out of line", in a separate
2168 // hashmap in the `Crate`. Here we just record the node-id of the item
2169 // so it can fetched later.
2170 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2177 /// The name might be a dummy name in case of anonymous items
2178 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2183 pub attrs: HirVec<Attribute>,
2185 pub vis: Visibility,
2189 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2190 pub struct FnHeader {
2191 pub unsafety: Unsafety,
2192 pub constness: Constness,
2193 pub asyncness: IsAsync,
2197 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2199 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2201 /// e.g., `extern crate foo` or `extern crate foo_bar as foo`
2202 ExternCrate(Option<Name>),
2204 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2208 /// `use foo::bar::baz;` (with `as baz` implicitly on the right)
2209 Use(P<Path>, UseKind),
2212 Static(P<Ty>, Mutability, BodyId),
2214 Const(P<Ty>, BodyId),
2215 /// A function declaration
2216 Fn(P<FnDecl>, FnHeader, Generics, BodyId),
2219 /// An external module
2220 ForeignMod(ForeignMod),
2221 /// Module-level inline assembly (from global_asm!)
2222 GlobalAsm(P<GlobalAsm>),
2223 /// A type alias, e.g., `type Foo = Bar<u8>`
2224 Ty(P<Ty>, Generics),
2225 /// An existential type definition, e.g., `existential type Foo: Bar;`
2226 Existential(ExistTy),
2227 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`
2228 Enum(EnumDef, Generics),
2229 /// A struct definition, e.g., `struct Foo<A> {x: A}`
2230 Struct(VariantData, Generics),
2231 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`
2232 Union(VariantData, Generics),
2233 /// Represents a Trait Declaration
2234 Trait(IsAuto, Unsafety, Generics, GenericBounds, HirVec<TraitItemRef>),
2235 /// Represents a Trait Alias Declaration
2236 TraitAlias(Generics, GenericBounds),
2238 /// An implementation, eg `impl<A> Trait for Foo { .. }`
2243 Option<TraitRef>, // (optional) trait this impl implements
2245 HirVec<ImplItemRef>),
2249 pub fn descriptive_variant(&self) -> &str {
2251 ItemKind::ExternCrate(..) => "extern crate",
2252 ItemKind::Use(..) => "use",
2253 ItemKind::Static(..) => "static item",
2254 ItemKind::Const(..) => "constant item",
2255 ItemKind::Fn(..) => "function",
2256 ItemKind::Mod(..) => "module",
2257 ItemKind::ForeignMod(..) => "foreign module",
2258 ItemKind::GlobalAsm(..) => "global asm",
2259 ItemKind::Ty(..) => "type alias",
2260 ItemKind::Existential(..) => "existential type",
2261 ItemKind::Enum(..) => "enum",
2262 ItemKind::Struct(..) => "struct",
2263 ItemKind::Union(..) => "union",
2264 ItemKind::Trait(..) => "trait",
2265 ItemKind::TraitAlias(..) => "trait alias",
2266 ItemKind::Impl(..) => "item",
2270 pub fn adt_kind(&self) -> Option<AdtKind> {
2272 ItemKind::Struct(..) => Some(AdtKind::Struct),
2273 ItemKind::Union(..) => Some(AdtKind::Union),
2274 ItemKind::Enum(..) => Some(AdtKind::Enum),
2279 pub fn generics(&self) -> Option<&Generics> {
2281 ItemKind::Fn(_, _, ref generics, _) |
2282 ItemKind::Ty(_, ref generics) |
2283 ItemKind::Existential(ExistTy { ref generics, impl_trait_fn: None, .. }) |
2284 ItemKind::Enum(_, ref generics) |
2285 ItemKind::Struct(_, ref generics) |
2286 ItemKind::Union(_, ref generics) |
2287 ItemKind::Trait(_, _, ref generics, _, _) |
2288 ItemKind::Impl(_, _, _, ref generics, _, _, _)=> generics,
2294 /// A reference from an trait to one of its associated items. This
2295 /// contains the item's id, naturally, but also the item's name and
2296 /// some other high-level details (like whether it is an associated
2297 /// type or method, and whether it is public). This allows other
2298 /// passes to find the impl they want without loading the id (which
2299 /// means fewer edges in the incremental compilation graph).
2300 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2301 pub struct TraitItemRef {
2302 pub id: TraitItemId,
2304 pub kind: AssociatedItemKind,
2306 pub defaultness: Defaultness,
2309 /// A reference from an impl to one of its associated items. This
2310 /// contains the item's id, naturally, but also the item's name and
2311 /// some other high-level details (like whether it is an associated
2312 /// type or method, and whether it is public). This allows other
2313 /// passes to find the impl they want without loading the id (which
2314 /// means fewer edges in the incremental compilation graph).
2315 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2316 pub struct ImplItemRef {
2319 pub kind: AssociatedItemKind,
2321 pub vis: Visibility,
2322 pub defaultness: Defaultness,
2325 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
2326 pub enum AssociatedItemKind {
2328 Method { has_self: bool },
2333 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2334 pub struct ForeignItem {
2336 pub attrs: HirVec<Attribute>,
2337 pub node: ForeignItemKind,
2340 pub vis: Visibility,
2343 /// An item within an `extern` block
2344 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2345 pub enum ForeignItemKind {
2346 /// A foreign function
2347 Fn(P<FnDecl>, HirVec<Ident>, Generics),
2348 /// A foreign static item (`static ext: u8`), with optional mutability
2349 /// (the boolean is true when mutable)
2350 Static(P<Ty>, bool),
2355 impl ForeignItemKind {
2356 pub fn descriptive_variant(&self) -> &str {
2358 ForeignItemKind::Fn(..) => "foreign function",
2359 ForeignItemKind::Static(..) => "foreign static item",
2360 ForeignItemKind::Type => "foreign type",
2365 /// A free variable referred to in a function.
2366 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable)]
2367 pub struct Freevar {
2368 /// The variable being accessed free.
2371 // First span where it is accessed (there can be multiple).
2376 pub fn var_id(&self) -> NodeId {
2378 Def::Local(id) | Def::Upvar(id, ..) => id,
2379 _ => bug!("Freevar::var_id: bad def ({:?})", self.def)
2384 pub type FreevarMap = NodeMap<Vec<Freevar>>;
2386 pub type CaptureModeMap = NodeMap<CaptureClause>;
2388 #[derive(Clone, Debug)]
2389 pub struct TraitCandidate {
2391 pub import_id: Option<NodeId>,
2394 // Trait method resolution
2395 pub type TraitMap = NodeMap<Vec<TraitCandidate>>;
2397 // Map from the NodeId of a glob import to a list of items which are actually
2399 pub type GlobMap = NodeMap<FxHashSet<Name>>;
2402 pub fn provide(providers: &mut Providers<'_>) {
2403 providers.describe_def = map::describe_def;
2406 #[derive(Clone, RustcEncodable, RustcDecodable)]
2407 pub struct CodegenFnAttrs {
2408 pub flags: CodegenFnAttrFlags,
2409 /// Parsed representation of the `#[inline]` attribute
2410 pub inline: InlineAttr,
2411 /// The `#[export_name = "..."]` attribute, indicating a custom symbol a
2412 /// function should be exported under
2413 pub export_name: Option<Symbol>,
2414 /// The `#[link_name = "..."]` attribute, indicating a custom symbol an
2415 /// imported function should be imported as. Note that `export_name`
2416 /// probably isn't set when this is set, this is for foreign items while
2417 /// `#[export_name]` is for Rust-defined functions.
2418 pub link_name: Option<Symbol>,
2419 /// The `#[target_feature(enable = "...")]` attribute and the enabled
2420 /// features (only enabled features are supported right now).
2421 pub target_features: Vec<Symbol>,
2422 /// The `#[linkage = "..."]` attribute and the value we found.
2423 pub linkage: Option<Linkage>,
2424 /// The `#[link_section = "..."]` attribute, or what executable section this
2425 /// should be placed in.
2426 pub link_section: Option<Symbol>,
2430 #[derive(RustcEncodable, RustcDecodable)]
2431 pub struct CodegenFnAttrFlags: u32 {
2432 /// #[cold], a hint to LLVM that this function, when called, is never on
2434 const COLD = 1 << 0;
2435 /// #[allocator], a hint to LLVM that the pointer returned from this
2436 /// function is never null
2437 const ALLOCATOR = 1 << 1;
2438 /// #[unwind], an indicator that this function may unwind despite what
2439 /// its ABI signature may otherwise imply
2440 const UNWIND = 1 << 2;
2441 /// #[rust_allocator_nounwind], an indicator that an imported FFI
2442 /// function will never unwind. Probably obsolete by recent changes with
2443 /// #[unwind], but hasn't been removed/migrated yet
2444 const RUSTC_ALLOCATOR_NOUNWIND = 1 << 3;
2445 /// #[naked], indicates to LLVM that no function prologue/epilogue
2446 /// should be generated
2447 const NAKED = 1 << 4;
2448 /// #[no_mangle], the function's name should be the same as its symbol
2449 const NO_MANGLE = 1 << 5;
2450 /// #[rustc_std_internal_symbol], and indicator that this symbol is a
2451 /// "weird symbol" for the standard library in that it has slightly
2452 /// different linkage, visibility, and reachability rules.
2453 const RUSTC_STD_INTERNAL_SYMBOL = 1 << 6;
2454 /// #[no_debug], indicates that no debugging information should be
2455 /// generated for this function by LLVM
2456 const NO_DEBUG = 1 << 7;
2457 /// #[thread_local], indicates a static is actually a thread local
2459 const THREAD_LOCAL = 1 << 8;
2460 /// #[used], indicates that LLVM can't eliminate this function (but the
2462 const USED = 1 << 9;
2466 impl CodegenFnAttrs {
2467 pub fn new() -> CodegenFnAttrs {
2469 flags: CodegenFnAttrFlags::empty(),
2470 inline: InlineAttr::None,
2473 target_features: vec![],
2479 /// True if `#[inline]` or `#[inline(always)]` is present.
2480 pub fn requests_inline(&self) -> bool {
2482 InlineAttr::Hint | InlineAttr::Always => true,
2483 InlineAttr::None | InlineAttr::Never => false,
2487 /// True if it looks like this symbol needs to be exported, for example:
2489 /// * `#[no_mangle]` is present
2490 /// * `#[export_name(...)]` is present
2491 /// * `#[linkage]` is present
2492 pub fn contains_extern_indicator(&self) -> bool {
2493 self.flags.contains(CodegenFnAttrFlags::NO_MANGLE) ||
2494 self.export_name.is_some() ||
2495 match self.linkage {
2496 // these are private, make sure we don't try to consider
2499 Some(Linkage::Internal) |
2500 Some(Linkage::Private) => false,
2506 #[derive(Copy, Clone, Debug)]
2507 pub enum Node<'hir> {
2509 ForeignItem(&'hir ForeignItem),
2510 TraitItem(&'hir TraitItem),
2511 ImplItem(&'hir ImplItem),
2512 Variant(&'hir Variant),
2513 Field(&'hir StructField),
2514 AnonConst(&'hir AnonConst),
2517 PathSegment(&'hir PathSegment),
2519 TraitRef(&'hir TraitRef),
2524 MacroDef(&'hir MacroDef),
2526 /// StructCtor represents a tuple struct.
2527 StructCtor(&'hir VariantData),
2529 Lifetime(&'hir Lifetime),
2530 GenericParam(&'hir GenericParam),
2531 Visibility(&'hir Visibility),