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.
13 pub use self::BlockCheckMode::*;
14 pub use self::CaptureClause::*;
15 pub use self::FunctionRetTy::*;
16 pub use self::Mutability::*;
17 pub use self::PrimTy::*;
18 pub use self::UnOp::*;
19 pub use self::UnsafeSource::*;
22 use hir::def_id::{DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX};
23 use util::nodemap::{NodeMap, FxHashSet};
24 use mir::mono::Linkage;
26 use syntax_pos::{Span, DUMMY_SP, symbol::InternedString};
27 use syntax::source_map::{self, Spanned};
28 use rustc_target::spec::abi::Abi;
29 use syntax::ast::{self, CrateSugar, Ident, Name, NodeId, DUMMY_NODE_ID, AsmDialect};
30 use syntax::ast::{Attribute, Lit, StrStyle, FloatTy, IntTy, UintTy, MetaItem};
31 use syntax::attr::InlineAttr;
32 use syntax::ext::hygiene::SyntaxContext;
34 use syntax::symbol::{Symbol, keywords};
35 use syntax::tokenstream::TokenStream;
36 use syntax::util::parser::ExprPrecedence;
38 use ty::query::Providers;
40 use rustc_data_structures::indexed_vec;
41 use rustc_data_structures::sync::{ParallelIterator, par_iter, Send, Sync, scope};
42 use rustc_data_structures::thin_vec::ThinVec;
44 use serialize::{self, Encoder, Encodable, Decoder, Decodable};
45 use std::collections::BTreeMap;
48 /// HIR doesn't commit to a concrete storage type and has its own alias for a vector.
49 /// It can be `Vec`, `P<[T]>` or potentially `Box<[T]>`, or some other container with similar
50 /// behavior. Unlike AST, HIR is mostly a static structure, so we can use an owned slice instead
51 /// of `Vec` to avoid keeping extra capacity.
52 pub type HirVec<T> = P<[T]>;
54 macro_rules! hir_vec {
55 ($elem:expr; $n:expr) => (
56 $crate::hir::HirVec::from(vec![$elem; $n])
59 $crate::hir::HirVec::from(vec![$($x),*])
61 ($($x:expr,)*) => (hir_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)?;
125 /// An `ItemLocalId` uniquely identifies something within a given "item-like",
126 /// that is within a hir::Item, hir::TraitItem, or hir::ImplItem. There is no
127 /// guarantee that the numerical value of a given `ItemLocalId` corresponds to
128 /// the node's position within the owning item in any way, but there is a
129 /// guarantee that the `LocalItemId`s within an owner occupy a dense range of
130 /// integers starting at zero, so a mapping that maps all or most nodes within
131 /// an "item-like" to something else can be implement by a `Vec` instead of a
132 /// tree or hash map.
133 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug,
134 RustcEncodable, RustcDecodable)]
135 pub struct ItemLocalId(pub u32);
138 pub fn as_usize(&self) -> usize {
143 impl indexed_vec::Idx for ItemLocalId {
144 fn new(idx: usize) -> Self {
145 debug_assert!((idx as u32) as usize == idx);
146 ItemLocalId(idx as u32)
149 fn index(self) -> usize {
154 /// The `HirId` corresponding to CRATE_NODE_ID and CRATE_DEF_INDEX
155 pub const CRATE_HIR_ID: HirId = HirId {
156 owner: CRATE_DEF_INDEX,
157 local_id: ItemLocalId(0)
160 pub const DUMMY_HIR_ID: HirId = HirId {
161 owner: CRATE_DEF_INDEX,
162 local_id: DUMMY_ITEM_LOCAL_ID,
165 pub const DUMMY_ITEM_LOCAL_ID: ItemLocalId = ItemLocalId(!0);
167 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
172 impl fmt::Debug for Label {
173 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
174 write!(f, "label({:?})", self.ident)
178 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
179 pub struct Lifetime {
183 /// Either "'a", referring to a named lifetime definition,
184 /// or "" (aka keywords::Invalid), for elision placeholders.
186 /// HIR lowering inserts these placeholders in type paths that
187 /// refer to type definitions needing lifetime parameters,
188 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
189 pub name: LifetimeName,
192 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
194 /// Some user-given name like `T` or `'x`.
197 /// Synthetic name generated when user elided a lifetime in an impl header,
198 /// e.g. the lifetimes in cases like these:
200 /// impl Foo for &u32
201 /// impl Foo<'_> for u32
203 /// in that case, we rewrite to
205 /// impl<'f> Foo for &'f u32
206 /// impl<'f> Foo<'f> for u32
208 /// where `'f` is something like `Fresh(0)`. The indices are
209 /// unique per impl, but not necessarily continuous.
212 /// Indicates an illegal name was given and an error has been
213 /// repored (so we should squelch other derived errors). Occurs
214 /// when e.g. `'_` is used in the wrong place.
219 pub fn ident(&self) -> Ident {
221 ParamName::Plain(ident) => ident,
222 ParamName::Error | ParamName::Fresh(_) => keywords::UnderscoreLifetime.ident(),
226 pub fn modern(&self) -> ParamName {
228 ParamName::Plain(ident) => ParamName::Plain(ident.modern()),
229 param_name => param_name,
234 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
235 pub enum LifetimeName {
236 /// User-given names or fresh (synthetic) names.
239 /// User typed nothing. e.g. the lifetime in `&u32`.
242 /// Indicates an error during lowering (usually `'_` in wrong place)
243 /// that was already reported.
249 /// User wrote `'static`
254 pub fn ident(&self) -> Ident {
256 LifetimeName::Implicit => keywords::Invalid.ident(),
257 LifetimeName::Error => keywords::Invalid.ident(),
258 LifetimeName::Underscore => keywords::UnderscoreLifetime.ident(),
259 LifetimeName::Static => keywords::StaticLifetime.ident(),
260 LifetimeName::Param(param_name) => param_name.ident(),
264 pub fn is_elided(&self) -> bool {
266 LifetimeName::Implicit | LifetimeName::Underscore => true,
268 // It might seem surprising that `Fresh(_)` counts as
269 // *not* elided -- but this is because, as far as the code
270 // in the compiler is concerned -- `Fresh(_)` variants act
271 // equivalently to "some fresh name". They correspond to
272 // early-bound regions on an impl, in other words.
273 LifetimeName::Error | LifetimeName::Param(_) | LifetimeName::Static => false,
277 fn is_static(&self) -> bool {
278 self == &LifetimeName::Static
281 pub fn modern(&self) -> LifetimeName {
283 LifetimeName::Param(param_name) => LifetimeName::Param(param_name.modern()),
284 lifetime_name => lifetime_name,
289 impl fmt::Display for Lifetime {
290 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
291 self.name.ident().fmt(f)
295 impl fmt::Debug for Lifetime {
296 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
300 print::to_string(print::NO_ANN, |s| s.print_lifetime(self)))
305 pub fn is_elided(&self) -> bool {
306 self.name.is_elided()
309 pub fn is_static(&self) -> bool {
310 self.name.is_static()
314 /// A "Path" is essentially Rust's notion of a name; for instance:
315 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
316 /// along with a bunch of supporting information.
317 #[derive(Clone, RustcEncodable, RustcDecodable)]
320 /// The definition that the path resolved to.
322 /// The segments in the path: the things separated by `::`.
323 pub segments: HirVec<PathSegment>,
327 pub fn is_global(&self) -> bool {
328 !self.segments.is_empty() && self.segments[0].ident.name == keywords::CrateRoot.name()
332 impl fmt::Debug for Path {
333 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
334 write!(f, "path({})", print::to_string(print::NO_ANN, |s| s.print_path(self, false)))
338 impl fmt::Display for Path {
339 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
340 write!(f, "{}", print::to_string(print::NO_ANN, |s| s.print_path(self, false)))
344 /// A segment of a path: an identifier, an optional lifetime, and a set of
346 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
347 pub struct PathSegment {
348 /// The identifier portion of this path segment.
351 /// Type/lifetime parameters attached to this path. They come in
352 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
353 /// this is more than just simple syntactic sugar; the use of
354 /// parens affects the region binding rules, so we preserve the
356 pub args: Option<P<GenericArgs>>,
358 /// Whether to infer remaining type parameters, if any.
359 /// This only applies to expression and pattern paths, and
360 /// out of those only the segments with no type parameters
361 /// to begin with, e.g. `Vec::new` is `<Vec<..>>::new::<..>`.
362 pub infer_types: bool,
366 /// Convert an identifier to the corresponding segment.
367 pub fn from_ident(ident: Ident) -> PathSegment {
375 pub fn new(ident: Ident, args: GenericArgs, infer_types: bool) -> Self {
379 args: if args.is_empty() {
387 // FIXME: hack required because you can't create a static
388 // GenericArgs, so you can't just return a &GenericArgs.
389 pub fn with_generic_args<F, R>(&self, f: F) -> R
390 where F: FnOnce(&GenericArgs) -> R
392 let dummy = GenericArgs::none();
393 f(if let Some(ref args) = self.args {
401 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
402 pub enum GenericArg {
408 pub fn span(&self) -> Span {
410 GenericArg::Lifetime(l) => l.span,
411 GenericArg::Type(t) => t.span,
415 pub fn id(&self) -> NodeId {
417 GenericArg::Lifetime(l) => l.id,
418 GenericArg::Type(t) => t.id,
423 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
424 pub struct GenericArgs {
425 /// The generic arguments for this path segment.
426 pub args: HirVec<GenericArg>,
427 /// Bindings (equality constraints) on associated types, if present.
428 /// E.g., `Foo<A=Bar>`.
429 pub bindings: HirVec<TypeBinding>,
430 /// Were arguments written in parenthesized form `Fn(T) -> U`?
431 /// This is required mostly for pretty-printing and diagnostics,
432 /// but also for changing lifetime elision rules to be "function-like".
433 pub parenthesized: bool,
437 pub fn none() -> Self {
440 bindings: HirVec::new(),
441 parenthesized: false,
445 pub fn is_empty(&self) -> bool {
446 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
449 pub fn inputs(&self) -> &[Ty] {
450 if self.parenthesized {
451 for arg in &self.args {
453 GenericArg::Lifetime(_) => {}
454 GenericArg::Type(ref ty) => {
455 if let TyKind::Tup(ref tys) = ty.node {
463 bug!("GenericArgs::inputs: not a `Fn(T) -> U`");
466 pub fn own_counts(&self) -> GenericParamCount {
467 // We could cache this as a property of `GenericParamCount`, but
468 // the aim is to refactor this away entirely eventually and the
469 // presence of this method will be a constant reminder.
470 let mut own_counts: GenericParamCount = Default::default();
472 for arg in &self.args {
474 GenericArg::Lifetime(_) => own_counts.lifetimes += 1,
475 GenericArg::Type(_) => own_counts.types += 1,
483 /// A modifier on a bound, currently this is only used for `?Sized`, where the
484 /// modifier is `Maybe`. Negative bounds should also be handled here.
485 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
486 pub enum TraitBoundModifier {
491 /// The AST represents all type param bounds as types.
492 /// typeck::collect::compute_bounds matches these against
493 /// the "special" built-in traits (see middle::lang_items) and
494 /// detects Copy, Send and Sync.
495 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
496 pub enum GenericBound {
497 Trait(PolyTraitRef, TraitBoundModifier),
502 pub fn span(&self) -> Span {
504 &GenericBound::Trait(ref t, ..) => t.span,
505 &GenericBound::Outlives(ref l) => l.span,
510 pub type GenericBounds = HirVec<GenericBound>;
512 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
513 pub enum LifetimeParamKind {
514 // Indicates that the lifetime definition was explicitly declared, like:
515 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`
518 // Indicates that the lifetime definition was synthetically added
519 // as a result of an in-band lifetime usage like:
520 // `fn foo(x: &'a u8) -> &'a u8 { x }`
523 // Indication that the lifetime was elided like both cases here:
524 // `fn foo(x: &u8) -> &'_ u8 { x }`
527 // Indication that the lifetime name was somehow in error.
531 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
532 pub enum GenericParamKind {
533 /// A lifetime definition, eg `'a: 'b + 'c + 'd`.
535 kind: LifetimeParamKind,
538 default: Option<P<Ty>>,
539 synthetic: Option<SyntheticTyParamKind>,
543 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
544 pub struct GenericParam {
547 pub attrs: HirVec<Attribute>,
548 pub bounds: GenericBounds,
550 pub pure_wrt_drop: bool,
552 pub kind: GenericParamKind,
556 pub struct GenericParamCount {
557 pub lifetimes: usize,
561 /// Represents lifetimes and type parameters attached to a declaration
562 /// of a function, enum, trait, etc.
563 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
564 pub struct Generics {
565 pub params: HirVec<GenericParam>,
566 pub where_clause: WhereClause,
571 pub fn empty() -> Generics {
573 params: HirVec::new(),
574 where_clause: WhereClause {
576 predicates: HirVec::new(),
582 pub fn own_counts(&self) -> GenericParamCount {
583 // We could cache this as a property of `GenericParamCount`, but
584 // the aim is to refactor this away entirely eventually and the
585 // presence of this method will be a constant reminder.
586 let mut own_counts: GenericParamCount = Default::default();
588 for param in &self.params {
590 GenericParamKind::Lifetime { .. } => own_counts.lifetimes += 1,
591 GenericParamKind::Type { .. } => own_counts.types += 1,
598 pub fn get_named(&self, name: &InternedString) -> Option<&GenericParam> {
599 for param in &self.params {
600 if *name == param.name.ident().as_interned_str() {
608 /// Synthetic Type Parameters are converted to an other form during lowering, this allows
609 /// to track the original form they had. Useful for error messages.
610 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
611 pub enum SyntheticTyParamKind {
615 /// A `where` clause in a definition
616 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
617 pub struct WhereClause {
619 pub predicates: HirVec<WherePredicate>,
623 pub fn span(&self) -> Option<Span> {
624 self.predicates.iter().map(|predicate| predicate.span())
625 .fold(None, |acc, i| match (acc, i) {
626 (None, i) => Some(i),
634 /// A single predicate in a `where` clause
635 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
636 pub enum WherePredicate {
637 /// A type binding, eg `for<'c> Foo: Send+Clone+'c`
638 BoundPredicate(WhereBoundPredicate),
639 /// A lifetime predicate, e.g. `'a: 'b+'c`
640 RegionPredicate(WhereRegionPredicate),
641 /// An equality predicate (unsupported)
642 EqPredicate(WhereEqPredicate),
645 impl WherePredicate {
646 pub fn span(&self) -> Span {
648 &WherePredicate::BoundPredicate(ref p) => p.span,
649 &WherePredicate::RegionPredicate(ref p) => p.span,
650 &WherePredicate::EqPredicate(ref p) => p.span,
655 /// A type bound, eg `for<'c> Foo: Send+Clone+'c`
656 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
657 pub struct WhereBoundPredicate {
659 /// Any generics from a `for` binding
660 pub bound_generic_params: HirVec<GenericParam>,
661 /// The type being bounded
662 pub bounded_ty: P<Ty>,
663 /// Trait and lifetime bounds (`Clone+Send+'static`)
664 pub bounds: GenericBounds,
667 /// A lifetime predicate, e.g. `'a: 'b+'c`
668 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
669 pub struct WhereRegionPredicate {
671 pub lifetime: Lifetime,
672 pub bounds: GenericBounds,
675 /// An equality predicate (unsupported), e.g. `T=int`
676 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
677 pub struct WhereEqPredicate {
684 pub type CrateConfig = HirVec<P<MetaItem>>;
686 /// The top-level data structure that stores the entire contents of
687 /// the crate currently being compiled.
689 /// For more details, see the [rustc guide].
691 /// [rustc guide]: https://rust-lang-nursery.github.io/rustc-guide/hir.html
692 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
695 pub attrs: HirVec<Attribute>,
697 pub exported_macros: HirVec<MacroDef>,
699 // NB: We use a BTreeMap here so that `visit_all_items` iterates
700 // over the ids in increasing order. In principle it should not
701 // matter what order we visit things in, but in *practice* it
702 // does, because it can affect the order in which errors are
703 // detected, which in turn can make compile-fail tests yield
704 // slightly different results.
705 pub items: BTreeMap<NodeId, Item>,
707 pub trait_items: BTreeMap<TraitItemId, TraitItem>,
708 pub impl_items: BTreeMap<ImplItemId, ImplItem>,
709 pub bodies: BTreeMap<BodyId, Body>,
710 pub trait_impls: BTreeMap<DefId, Vec<NodeId>>,
711 pub trait_auto_impl: BTreeMap<DefId, NodeId>,
713 /// A list of the body ids written out in the order in which they
714 /// appear in the crate. If you're going to process all the bodies
715 /// in the crate, you should iterate over this list rather than the keys
717 pub body_ids: Vec<BodyId>,
721 pub fn item(&self, id: NodeId) -> &Item {
725 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem {
726 &self.trait_items[&id]
729 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem {
730 &self.impl_items[&id]
733 /// Visits all items in the crate in some deterministic (but
734 /// unspecified) order. If you just need to process every item,
735 /// but don't care about nesting, this method is the best choice.
737 /// If you do care about nesting -- usually because your algorithm
738 /// follows lexical scoping rules -- then you want a different
739 /// approach. You should override `visit_nested_item` in your
740 /// visitor and then call `intravisit::walk_crate` instead.
741 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
742 where V: itemlikevisit::ItemLikeVisitor<'hir>
744 for (_, item) in &self.items {
745 visitor.visit_item(item);
748 for (_, trait_item) in &self.trait_items {
749 visitor.visit_trait_item(trait_item);
752 for (_, impl_item) in &self.impl_items {
753 visitor.visit_impl_item(impl_item);
757 /// A parallel version of visit_all_item_likes
758 pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
759 where V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send
763 par_iter(&self.items).for_each(|(_, item)| {
764 visitor.visit_item(item);
769 par_iter(&self.trait_items).for_each(|(_, trait_item)| {
770 visitor.visit_trait_item(trait_item);
775 par_iter(&self.impl_items).for_each(|(_, impl_item)| {
776 visitor.visit_impl_item(impl_item);
782 pub fn body(&self, id: BodyId) -> &Body {
787 /// A macro definition, in this crate or imported from another.
789 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
790 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
791 pub struct MacroDef {
794 pub attrs: HirVec<Attribute>,
797 pub body: TokenStream,
801 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
803 /// Statements in a block
804 pub stmts: HirVec<Stmt>,
805 /// An expression at the end of the block
806 /// without a semicolon, if any
807 pub expr: Option<P<Expr>>,
810 /// Distinguishes between `unsafe { ... }` and `{ ... }`
811 pub rules: BlockCheckMode,
813 /// If true, then there may exist `break 'a` values that aim to
814 /// break out of this block early.
815 /// Used by `'label: {}` blocks and by `catch` statements.
816 pub targeted_by_break: bool,
817 /// If true, don't emit return value type errors as the parser had
818 /// to recover from a parse error so this block will not have an
819 /// appropriate type. A parse error will have been emitted so the
820 /// compilation will never succeed if this is true.
824 #[derive(Clone, RustcEncodable, RustcDecodable)]
832 impl fmt::Debug for Pat {
833 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
834 write!(f, "pat({}: {})", self.id,
835 print::to_string(print::NO_ANN, |s| s.print_pat(self)))
840 // FIXME(#19596) this is a workaround, but there should be a better way
841 fn walk_<G>(&self, it: &mut G) -> bool
842 where G: FnMut(&Pat) -> bool
849 PatKind::Binding(.., Some(ref p)) => p.walk_(it),
850 PatKind::Struct(_, ref fields, _) => {
851 fields.iter().all(|field| field.node.pat.walk_(it))
853 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
854 s.iter().all(|p| p.walk_(it))
856 PatKind::Box(ref s) | PatKind::Ref(ref s, _) => {
859 PatKind::Slice(ref before, ref slice, ref after) => {
863 .all(|p| p.walk_(it))
868 PatKind::Binding(..) |
869 PatKind::Path(_) => {
875 pub fn walk<F>(&self, mut it: F) -> bool
876 where F: FnMut(&Pat) -> bool
882 /// A single field in a struct pattern
884 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
885 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
886 /// except is_shorthand is true
887 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
888 pub struct FieldPat {
890 /// The identifier for the field
892 /// The pattern the field is destructured to
894 pub is_shorthand: bool,
897 /// Explicit binding annotations given in the HIR for a binding. Note
898 /// that this is not the final binding *mode* that we infer after type
900 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
901 pub enum BindingAnnotation {
902 /// No binding annotation given: this means that the final binding mode
903 /// will depend on whether we have skipped through a `&` reference
904 /// when matching. For example, the `x` in `Some(x)` will have binding
905 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
906 /// ultimately be inferred to be by-reference.
908 /// Note that implicit reference skipping is not implemented yet (#42640).
911 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
914 /// Annotated as `ref`, like `ref x`
917 /// Annotated as `ref mut x`.
921 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
927 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
929 /// Represents a wildcard pattern (`_`)
932 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
933 /// The `NodeId` is the canonical ID for the variable being bound,
934 /// e.g. in `Ok(x) | Err(x)`, both `x` use the same canonical ID,
935 /// which is the pattern ID of the first `x`.
936 Binding(BindingAnnotation, NodeId, Ident, Option<P<Pat>>),
938 /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
939 /// The `bool` is `true` in the presence of a `..`.
940 Struct(QPath, HirVec<Spanned<FieldPat>>, bool),
942 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
943 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
944 /// 0 <= position <= subpats.len()
945 TupleStruct(QPath, HirVec<P<Pat>>, Option<usize>),
947 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
950 /// A tuple pattern `(a, b)`.
951 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
952 /// 0 <= position <= subpats.len()
953 Tuple(HirVec<P<Pat>>, Option<usize>),
956 /// A reference pattern, e.g. `&mut (a, b)`
957 Ref(P<Pat>, Mutability),
960 /// A range pattern, e.g. `1...2` or `1..2`
961 Range(P<Expr>, P<Expr>, RangeEnd),
962 /// `[a, b, ..i, y, z]` is represented as:
963 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
964 Slice(HirVec<P<Pat>>, Option<P<Pat>>, HirVec<P<Pat>>),
967 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
968 pub enum Mutability {
974 /// Return MutMutable only if both arguments are mutable.
975 pub fn and(self, other: Self) -> Self {
978 MutImmutable => MutImmutable,
983 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, Hash)]
985 /// The `+` operator (addition)
987 /// The `-` operator (subtraction)
989 /// The `*` operator (multiplication)
991 /// The `/` operator (division)
993 /// The `%` operator (modulus)
995 /// The `&&` operator (logical and)
997 /// The `||` operator (logical or)
999 /// The `^` operator (bitwise xor)
1001 /// The `&` operator (bitwise and)
1003 /// The `|` operator (bitwise or)
1005 /// The `<<` operator (shift left)
1007 /// The `>>` operator (shift right)
1009 /// The `==` operator (equality)
1011 /// The `<` operator (less than)
1013 /// The `<=` operator (less than or equal to)
1015 /// The `!=` operator (not equal to)
1017 /// The `>=` operator (greater than or equal to)
1019 /// The `>` operator (greater than)
1024 pub fn as_str(self) -> &'static str {
1026 BinOpKind::Add => "+",
1027 BinOpKind::Sub => "-",
1028 BinOpKind::Mul => "*",
1029 BinOpKind::Div => "/",
1030 BinOpKind::Rem => "%",
1031 BinOpKind::And => "&&",
1032 BinOpKind::Or => "||",
1033 BinOpKind::BitXor => "^",
1034 BinOpKind::BitAnd => "&",
1035 BinOpKind::BitOr => "|",
1036 BinOpKind::Shl => "<<",
1037 BinOpKind::Shr => ">>",
1038 BinOpKind::Eq => "==",
1039 BinOpKind::Lt => "<",
1040 BinOpKind::Le => "<=",
1041 BinOpKind::Ne => "!=",
1042 BinOpKind::Ge => ">=",
1043 BinOpKind::Gt => ">",
1047 pub fn is_lazy(self) -> bool {
1049 BinOpKind::And | BinOpKind::Or => true,
1054 pub fn is_shift(self) -> bool {
1056 BinOpKind::Shl | BinOpKind::Shr => true,
1061 pub fn is_comparison(self) -> bool {
1068 BinOpKind::Ge => true,
1080 BinOpKind::Shr => false,
1084 /// Returns `true` if the binary operator takes its arguments by value
1085 pub fn is_by_value(self) -> bool {
1086 !self.is_comparison()
1090 impl Into<ast::BinOpKind> for BinOpKind {
1091 fn into(self) -> ast::BinOpKind {
1093 BinOpKind::Add => ast::BinOpKind::Add,
1094 BinOpKind::Sub => ast::BinOpKind::Sub,
1095 BinOpKind::Mul => ast::BinOpKind::Mul,
1096 BinOpKind::Div => ast::BinOpKind::Div,
1097 BinOpKind::Rem => ast::BinOpKind::Rem,
1098 BinOpKind::And => ast::BinOpKind::And,
1099 BinOpKind::Or => ast::BinOpKind::Or,
1100 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1101 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1102 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1103 BinOpKind::Shl => ast::BinOpKind::Shl,
1104 BinOpKind::Shr => ast::BinOpKind::Shr,
1105 BinOpKind::Eq => ast::BinOpKind::Eq,
1106 BinOpKind::Lt => ast::BinOpKind::Lt,
1107 BinOpKind::Le => ast::BinOpKind::Le,
1108 BinOpKind::Ne => ast::BinOpKind::Ne,
1109 BinOpKind::Ge => ast::BinOpKind::Ge,
1110 BinOpKind::Gt => ast::BinOpKind::Gt,
1115 pub type BinOp = Spanned<BinOpKind>;
1117 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, Hash)]
1119 /// The `*` operator for dereferencing
1121 /// The `!` operator for logical inversion
1123 /// The `-` operator for negation
1128 pub fn as_str(self) -> &'static str {
1136 /// Returns `true` if the unary operator takes its argument by value
1137 pub fn is_by_value(self) -> bool {
1139 UnNeg | UnNot => true,
1146 pub type Stmt = Spanned<StmtKind>;
1148 impl fmt::Debug for StmtKind {
1149 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1151 let spanned = source_map::dummy_spanned(self.clone());
1155 print::to_string(print::NO_ANN, |s| s.print_stmt(&spanned)))
1159 #[derive(Clone, RustcEncodable, RustcDecodable)]
1161 /// Could be an item or a local (let) binding:
1162 Decl(P<Decl>, NodeId),
1164 /// Expr without trailing semi-colon (must have unit type):
1165 Expr(P<Expr>, NodeId),
1167 /// Expr with trailing semi-colon (may have any type):
1168 Semi(P<Expr>, NodeId),
1172 pub fn attrs(&self) -> &[Attribute] {
1174 StmtKind::Decl(ref d, _) => d.node.attrs(),
1175 StmtKind::Expr(ref e, _) |
1176 StmtKind::Semi(ref e, _) => &e.attrs,
1180 pub fn id(&self) -> NodeId {
1182 StmtKind::Decl(_, id) => id,
1183 StmtKind::Expr(_, id) => id,
1184 StmtKind::Semi(_, id) => id,
1189 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
1190 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1193 pub ty: Option<P<Ty>>,
1194 /// Initializer expression to set the value, if any
1195 pub init: Option<P<Expr>>,
1199 pub attrs: ThinVec<Attribute>,
1200 pub source: LocalSource,
1203 pub type Decl = Spanned<DeclKind>;
1205 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1207 /// A local (let) binding:
1209 /// An item binding:
1214 pub fn attrs(&self) -> &[Attribute] {
1216 DeclKind::Local(ref l) => &l.attrs,
1217 DeclKind::Item(_) => &[]
1221 pub fn is_local(&self) -> bool {
1223 DeclKind::Local(_) => true,
1229 /// represents one arm of a 'match'
1230 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1232 pub attrs: HirVec<Attribute>,
1233 pub pats: HirVec<P<Pat>>,
1234 pub guard: Option<Guard>,
1238 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1243 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1249 pub is_shorthand: bool,
1252 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1253 pub enum BlockCheckMode {
1255 UnsafeBlock(UnsafeSource),
1256 PushUnsafeBlock(UnsafeSource),
1257 PopUnsafeBlock(UnsafeSource),
1260 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1261 pub enum UnsafeSource {
1266 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1268 pub node_id: NodeId,
1271 /// The body of a function, closure, or constant value. In the case of
1272 /// a function, the body contains not only the function body itself
1273 /// (which is an expression), but also the argument patterns, since
1274 /// those are something that the caller doesn't really care about.
1279 /// fn foo((x, y): (u32, u32)) -> u32 {
1284 /// Here, the `Body` associated with `foo()` would contain:
1286 /// - an `arguments` array containing the `(x, y)` pattern
1287 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1288 /// - `is_generator` would be false
1290 /// All bodies have an **owner**, which can be accessed via the HIR
1291 /// map using `body_owner_def_id()`.
1292 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1294 pub arguments: HirVec<Arg>,
1296 pub is_generator: bool,
1300 pub fn id(&self) -> BodyId {
1302 node_id: self.value.id
1307 #[derive(Copy, Clone, Debug)]
1308 pub enum BodyOwnerKind {
1309 /// Functions and methods.
1312 /// Constants and associated constants.
1315 /// Initializer of a `static` item.
1319 /// A constant (expression) that's not an item or associated item,
1320 /// but needs its own `DefId` for type-checking, const-eval, etc.
1321 /// These are usually found nested inside types (e.g. array lengths)
1322 /// or expressions (e.g. repeat counts), and also used to define
1323 /// explicit discriminant values for enum variants.
1324 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
1325 pub struct AnonConst {
1332 #[derive(Clone, RustcEncodable, RustcDecodable)]
1337 pub attrs: ThinVec<Attribute>,
1342 pub fn precedence(&self) -> ExprPrecedence {
1344 ExprKind::Box(_) => ExprPrecedence::Box,
1345 ExprKind::Array(_) => ExprPrecedence::Array,
1346 ExprKind::Call(..) => ExprPrecedence::Call,
1347 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1348 ExprKind::Tup(_) => ExprPrecedence::Tup,
1349 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1350 ExprKind::Unary(..) => ExprPrecedence::Unary,
1351 ExprKind::Lit(_) => ExprPrecedence::Lit,
1352 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1353 ExprKind::If(..) => ExprPrecedence::If,
1354 ExprKind::While(..) => ExprPrecedence::While,
1355 ExprKind::Loop(..) => ExprPrecedence::Loop,
1356 ExprKind::Match(..) => ExprPrecedence::Match,
1357 ExprKind::Closure(..) => ExprPrecedence::Closure,
1358 ExprKind::Block(..) => ExprPrecedence::Block,
1359 ExprKind::Assign(..) => ExprPrecedence::Assign,
1360 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1361 ExprKind::Field(..) => ExprPrecedence::Field,
1362 ExprKind::Index(..) => ExprPrecedence::Index,
1363 ExprKind::Path(..) => ExprPrecedence::Path,
1364 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1365 ExprKind::Break(..) => ExprPrecedence::Break,
1366 ExprKind::Continue(..) => ExprPrecedence::Continue,
1367 ExprKind::Ret(..) => ExprPrecedence::Ret,
1368 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1369 ExprKind::Struct(..) => ExprPrecedence::Struct,
1370 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1371 ExprKind::Yield(..) => ExprPrecedence::Yield,
1375 pub fn is_place_expr(&self) -> bool {
1377 ExprKind::Path(QPath::Resolved(_, ref path)) => {
1379 Def::Local(..) | Def::Upvar(..) | Def::Static(..) | Def::Err => true,
1384 ExprKind::Type(ref e, _) => {
1388 ExprKind::Unary(UnDeref, _) |
1389 ExprKind::Field(..) |
1390 ExprKind::Index(..) => {
1394 // Partially qualified paths in expressions can only legally
1395 // refer to associated items which are always rvalues.
1396 ExprKind::Path(QPath::TypeRelative(..)) |
1398 ExprKind::Call(..) |
1399 ExprKind::MethodCall(..) |
1400 ExprKind::Struct(..) |
1403 ExprKind::Match(..) |
1404 ExprKind::Closure(..) |
1405 ExprKind::Block(..) |
1406 ExprKind::Repeat(..) |
1407 ExprKind::Array(..) |
1408 ExprKind::Break(..) |
1409 ExprKind::Continue(..) |
1411 ExprKind::While(..) |
1412 ExprKind::Loop(..) |
1413 ExprKind::Assign(..) |
1414 ExprKind::InlineAsm(..) |
1415 ExprKind::AssignOp(..) |
1417 ExprKind::Unary(..) |
1419 ExprKind::AddrOf(..) |
1420 ExprKind::Binary(..) |
1421 ExprKind::Yield(..) |
1422 ExprKind::Cast(..) => {
1429 impl fmt::Debug for Expr {
1430 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1431 write!(f, "expr({}: {})", self.id,
1432 print::to_string(print::NO_ANN, |s| s.print_expr(self)))
1436 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1438 /// A `box x` expression.
1440 /// An array (`[a, b, c, d]`)
1441 Array(HirVec<Expr>),
1444 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1445 /// and the second field is the list of arguments.
1446 /// This also represents calling the constructor of
1447 /// tuple-like ADTs such as tuple structs and enum variants.
1448 Call(P<Expr>, HirVec<Expr>),
1449 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1451 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1452 /// (within the angle brackets).
1453 /// The first element of the vector of `Expr`s is the expression that evaluates
1454 /// to the object on which the method is being called on (the receiver),
1455 /// and the remaining elements are the rest of the arguments.
1456 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1457 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1458 MethodCall(PathSegment, Span, HirVec<Expr>),
1459 /// A tuple (`(a, b, c ,d)`)
1461 /// A binary operation (For example: `a + b`, `a * b`)
1462 Binary(BinOp, P<Expr>, P<Expr>),
1463 /// A unary operation (For example: `!x`, `*x`)
1464 Unary(UnOp, P<Expr>),
1465 /// A literal (For example: `1`, `"foo"`)
1467 /// A cast (`foo as f64`)
1468 Cast(P<Expr>, P<Ty>),
1469 Type(P<Expr>, P<Ty>),
1470 /// An `if` block, with an optional else block
1472 /// `if expr { expr } else { expr }`
1473 If(P<Expr>, P<Expr>, Option<P<Expr>>),
1474 /// A while loop, with an optional label
1476 /// `'label: while expr { block }`
1477 While(P<Expr>, P<Block>, Option<Label>),
1478 /// Conditionless loop (can be exited with break, continue, or return)
1480 /// `'label: loop { block }`
1481 Loop(P<Block>, Option<Label>, LoopSource),
1482 /// A `match` block, with a source that indicates whether or not it is
1483 /// the result of a desugaring, and if so, which kind.
1484 Match(P<Expr>, HirVec<Arm>, MatchSource),
1485 /// A closure (for example, `move |a, b, c| {a + b + c}`).
1487 /// The final span is the span of the argument block `|...|`
1489 /// This may also be a generator literal, indicated by the final boolean,
1490 /// in that case there is an GeneratorClause.
1491 Closure(CaptureClause, P<FnDecl>, BodyId, Span, Option<GeneratorMovability>),
1492 /// A block (`'label: { ... }`)
1493 Block(P<Block>, Option<Label>),
1495 /// An assignment (`a = foo()`)
1496 Assign(P<Expr>, P<Expr>),
1497 /// An assignment with an operator
1499 /// For example, `a += 1`.
1500 AssignOp(BinOp, P<Expr>, P<Expr>),
1501 /// Access of a named (`obj.foo`) or unnamed (`obj.0`) struct or tuple field
1502 Field(P<Expr>, Ident),
1503 /// An indexing operation (`foo[2]`)
1504 Index(P<Expr>, P<Expr>),
1506 /// Path to a definition, possibly containing lifetime or type parameters.
1509 /// A referencing operation (`&a` or `&mut a`)
1510 AddrOf(Mutability, P<Expr>),
1511 /// A `break`, with an optional label to break
1512 Break(Destination, Option<P<Expr>>),
1513 /// A `continue`, with an optional label
1514 Continue(Destination),
1515 /// A `return`, with an optional value to be returned
1516 Ret(Option<P<Expr>>),
1518 /// Inline assembly (from `asm!`), with its outputs and inputs.
1519 InlineAsm(P<InlineAsm>, HirVec<Expr>, HirVec<Expr>),
1521 /// A struct or struct-like variant literal expression.
1523 /// For example, `Foo {x: 1, y: 2}`, or
1524 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
1525 Struct(QPath, HirVec<Field>, Option<P<Expr>>),
1527 /// An array literal constructed from one repeated element.
1529 /// For example, `[1; 5]`. The first expression is the element
1530 /// to be repeated; the second is the number of times to repeat it.
1531 Repeat(P<Expr>, AnonConst),
1533 /// A suspension point for generators. This is `yield <expr>` in Rust.
1537 /// Optionally `Self`-qualified value/type path or associated extension.
1538 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1540 /// Path to a definition, optionally "fully-qualified" with a `Self`
1541 /// type, if the path points to an associated item in a trait.
1543 /// E.g. an unqualified path like `Clone::clone` has `None` for `Self`,
1544 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1545 /// even though they both have the same two-segment `Clone::clone` `Path`.
1546 Resolved(Option<P<Ty>>, P<Path>),
1548 /// Type-related paths, e.g. `<T>::default` or `<T>::Output`.
1549 /// Will be resolved by type-checking to an associated item.
1551 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1552 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1553 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1554 TypeRelative(P<Ty>, P<PathSegment>)
1557 /// Hints at the original code for a let statement
1558 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1559 pub enum LocalSource {
1560 /// A `match _ { .. }`
1562 /// A desugared `for _ in _ { .. }` loop
1566 /// Hints at the original code for a `match _ { .. }`
1567 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1568 pub enum MatchSource {
1569 /// A `match _ { .. }`
1571 /// An `if let _ = _ { .. }` (optionally with `else { .. }`)
1573 contains_else_clause: bool,
1575 /// A `while let _ = _ { .. }` (which was desugared to a
1576 /// `loop { match _ { .. } }`)
1578 /// A desugared `for _ in _ { .. }` loop
1580 /// A desugared `?` operator
1584 /// The loop type that yielded an ExprKind::Loop
1585 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1586 pub enum LoopSource {
1587 /// A `loop { .. }` loop
1589 /// A `while let _ = _ { .. }` loop
1591 /// A `for _ in _ { .. }` loop
1595 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1596 pub enum LoopIdError {
1598 UnlabeledCfInWhileCondition,
1602 impl fmt::Display for LoopIdError {
1603 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1604 fmt::Display::fmt(match *self {
1605 LoopIdError::OutsideLoopScope => "not inside loop scope",
1606 LoopIdError::UnlabeledCfInWhileCondition =>
1607 "unlabeled control flow (break or continue) in while condition",
1608 LoopIdError::UnresolvedLabel => "label not found",
1613 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1614 pub struct Destination {
1615 // This is `Some(_)` iff there is an explicit user-specified `label
1616 pub label: Option<Label>,
1618 // These errors are caught and then reported during the diagnostics pass in
1619 // librustc_passes/loops.rs
1620 pub target_id: Result<NodeId, LoopIdError>,
1623 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1624 pub enum GeneratorMovability {
1629 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1630 pub enum CaptureClause {
1635 // NB: If you change this, you'll probably want to change the corresponding
1636 // type structure in middle/ty.rs as well.
1637 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1640 pub mutbl: Mutability,
1643 /// Represents a method's signature in a trait declaration or implementation.
1644 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1645 pub struct MethodSig {
1646 pub header: FnHeader,
1647 pub decl: P<FnDecl>,
1650 // The bodies for items are stored "out of line", in a separate
1651 // hashmap in the `Crate`. Here we just record the node-id of the item
1652 // so it can fetched later.
1653 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1654 pub struct TraitItemId {
1655 pub node_id: NodeId,
1658 /// Represents an item declaration within a trait declaration,
1659 /// possibly including a default implementation. A trait item is
1660 /// either required (meaning it doesn't have an implementation, just a
1661 /// signature) or provided (meaning it has a default implementation).
1662 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1663 pub struct TraitItem {
1667 pub attrs: HirVec<Attribute>,
1668 pub generics: Generics,
1669 pub node: TraitItemKind,
1673 /// A trait method's body (or just argument names).
1674 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1675 pub enum TraitMethod {
1676 /// No default body in the trait, just a signature.
1677 Required(HirVec<Ident>),
1679 /// Both signature and body are provided in the trait.
1683 /// Represents a trait method or associated constant or type
1684 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1685 pub enum TraitItemKind {
1686 /// An associated constant with an optional value (otherwise `impl`s
1687 /// must contain a value)
1688 Const(P<Ty>, Option<BodyId>),
1689 /// A method with an optional body
1690 Method(MethodSig, TraitMethod),
1691 /// An associated type with (possibly empty) bounds and optional concrete
1693 Type(GenericBounds, Option<P<Ty>>),
1696 // The bodies for items are stored "out of line", in a separate
1697 // hashmap in the `Crate`. Here we just record the node-id of the item
1698 // so it can fetched later.
1699 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1700 pub struct ImplItemId {
1701 pub node_id: NodeId,
1704 /// Represents anything within an `impl` block
1705 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1706 pub struct ImplItem {
1710 pub vis: Visibility,
1711 pub defaultness: Defaultness,
1712 pub attrs: HirVec<Attribute>,
1713 pub generics: Generics,
1714 pub node: ImplItemKind,
1718 /// Represents different contents within `impl`s
1719 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1720 pub enum ImplItemKind {
1721 /// An associated constant of the given type, set to the constant result
1722 /// of the expression
1723 Const(P<Ty>, BodyId),
1724 /// A method implementation with the given signature and body
1725 Method(MethodSig, BodyId),
1726 /// An associated type
1728 /// An associated existential type
1729 Existential(GenericBounds),
1732 // Bind a type to an associated type: `A=Foo`.
1733 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1734 pub struct TypeBinding {
1741 #[derive(Clone, RustcEncodable, RustcDecodable)]
1749 impl fmt::Debug for Ty {
1750 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1751 write!(f, "type({})",
1752 print::to_string(print::NO_ANN, |s| s.print_type(self)))
1756 /// Not represented directly in the AST, referred to by name through a ty_path.
1757 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1767 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1768 pub struct BareFnTy {
1769 pub unsafety: Unsafety,
1771 pub generic_params: HirVec<GenericParam>,
1772 pub decl: P<FnDecl>,
1773 pub arg_names: HirVec<Ident>,
1776 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1777 pub struct ExistTy {
1778 pub generics: Generics,
1779 pub bounds: GenericBounds,
1780 pub impl_trait_fn: Option<DefId>,
1783 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1784 /// The different kinds of types recognized by the compiler
1786 /// A variable length slice (`[T]`)
1788 /// A fixed length array (`[T; n]`)
1789 Array(P<Ty>, AnonConst),
1790 /// A raw pointer (`*const T` or `*mut T`)
1792 /// A reference (`&'a T` or `&'a mut T`)
1793 Rptr(Lifetime, MutTy),
1794 /// A bare function (e.g. `fn(usize) -> bool`)
1795 BareFn(P<BareFnTy>),
1796 /// The never type (`!`)
1798 /// A tuple (`(A, B, C, D,...)`)
1800 /// A path to a type definition (`module::module::...::Type`), or an
1801 /// associated type, e.g. `<Vec<T> as Trait>::Type` or `<T>::Target`.
1803 /// Type parameters may be stored in each `PathSegment`.
1805 /// A type definition itself. This is currently only used for the `existential type`
1806 /// item that `impl Trait` in return position desugars to.
1808 /// The generic arg list are the lifetimes (and in the future possibly parameters) that are
1809 /// actually bound on the `impl Trait`.
1810 Def(ItemId, HirVec<GenericArg>),
1811 /// A trait object type `Bound1 + Bound2 + Bound3`
1812 /// where `Bound` is a trait or a lifetime.
1813 TraitObject(HirVec<PolyTraitRef>, Lifetime),
1816 /// TyKind::Infer means the type should be inferred instead of it having been
1817 /// specified. This can appear anywhere in a type.
1819 /// Placeholder for a type that has failed to be defined.
1823 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1824 pub struct InlineAsmOutput {
1825 pub constraint: Symbol,
1827 pub is_indirect: bool,
1831 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1832 pub struct InlineAsm {
1834 pub asm_str_style: StrStyle,
1835 pub outputs: HirVec<InlineAsmOutput>,
1836 pub inputs: HirVec<Symbol>,
1837 pub clobbers: HirVec<Symbol>,
1839 pub alignstack: bool,
1840 pub dialect: AsmDialect,
1841 pub ctxt: SyntaxContext,
1844 /// represents an argument in a function header
1845 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1852 /// Represents the header (not the body) of a function declaration
1853 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1855 pub inputs: HirVec<Ty>,
1856 pub output: FunctionRetTy,
1858 /// Does the function have an implicit self?
1859 pub implicit_self: ImplicitSelfKind,
1862 /// Represents what type of implicit self a function has, if any.
1863 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
1864 pub enum ImplicitSelfKind {
1865 /// Represents a `fn x(self);`.
1867 /// Represents a `fn x(mut self);`.
1869 /// Represents a `fn x(&self);`.
1871 /// Represents a `fn x(&mut self);`.
1873 /// Represents when a function does not have a self argument or
1874 /// when a function has a `self: X` argument.
1878 impl ImplicitSelfKind {
1879 /// Does this represent an implicit self?
1880 pub fn has_implicit_self(&self) -> bool {
1882 ImplicitSelfKind::None => false,
1888 /// Is the trait definition an auto trait?
1889 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1895 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1901 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1907 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1908 pub enum Constness {
1913 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1914 pub enum Defaultness {
1915 Default { has_value: bool },
1920 pub fn has_value(&self) -> bool {
1922 Defaultness::Default { has_value, .. } => has_value,
1923 Defaultness::Final => true,
1927 pub fn is_final(&self) -> bool {
1928 *self == Defaultness::Final
1931 pub fn is_default(&self) -> bool {
1933 Defaultness::Default { .. } => true,
1939 impl fmt::Display for Unsafety {
1940 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1941 fmt::Display::fmt(match *self {
1942 Unsafety::Normal => "normal",
1943 Unsafety::Unsafe => "unsafe",
1949 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
1950 pub enum ImplPolarity {
1951 /// `impl Trait for Type`
1953 /// `impl !Trait for Type`
1957 impl fmt::Debug for ImplPolarity {
1958 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1960 ImplPolarity::Positive => "positive".fmt(f),
1961 ImplPolarity::Negative => "negative".fmt(f),
1967 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1968 pub enum FunctionRetTy {
1969 /// Return type is not specified.
1971 /// Functions default to `()` and
1972 /// closures default to inference. Span points to where return
1973 /// type would be inserted.
1974 DefaultReturn(Span),
1979 impl FunctionRetTy {
1980 pub fn span(&self) -> Span {
1982 DefaultReturn(span) => span,
1983 Return(ref ty) => ty.span,
1988 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1990 /// A span from the first token past `{` to the last token until `}`.
1991 /// For `mod foo;`, the inner span ranges from the first token
1992 /// to the last token in the external file.
1994 pub item_ids: HirVec<ItemId>,
1997 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1998 pub struct ForeignMod {
2000 pub items: HirVec<ForeignItem>,
2003 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2004 pub struct GlobalAsm {
2006 pub ctxt: SyntaxContext,
2009 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2010 pub struct EnumDef {
2011 pub variants: HirVec<Variant>,
2014 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2015 pub struct VariantKind {
2017 pub attrs: HirVec<Attribute>,
2018 pub data: VariantData,
2019 /// Explicit discriminant, eg `Foo = 1`
2020 pub disr_expr: Option<AnonConst>,
2023 pub type Variant = Spanned<VariantKind>;
2025 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
2027 /// One import, e.g. `use foo::bar` or `use foo::bar as baz`.
2028 /// Also produced for each element of a list `use`, e.g.
2029 // `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2032 /// Glob import, e.g. `use foo::*`.
2035 /// Degenerate list import, e.g. `use foo::{a, b}` produces
2036 /// an additional `use foo::{}` for performing checks such as
2037 /// unstable feature gating. May be removed in the future.
2041 /// TraitRef's appear in impls.
2043 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
2044 /// that the ref_id is for. Note that ref_id's value is not the NodeId of the
2045 /// trait being referred to but just a unique NodeId that serves as a key
2046 /// within the DefMap.
2047 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2048 pub struct TraitRef {
2051 pub hir_ref_id: HirId,
2054 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2055 pub struct PolyTraitRef {
2056 /// The `'a` in `<'a> Foo<&'a T>`
2057 pub bound_generic_params: HirVec<GenericParam>,
2059 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
2060 pub trait_ref: TraitRef,
2065 pub type Visibility = Spanned<VisibilityKind>;
2067 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2068 pub enum VisibilityKind {
2071 Restricted { path: P<Path>, id: NodeId, hir_id: HirId },
2075 impl VisibilityKind {
2076 pub fn is_pub(&self) -> bool {
2078 VisibilityKind::Public => true,
2083 pub fn is_pub_restricted(&self) -> bool {
2085 VisibilityKind::Public |
2086 VisibilityKind::Inherited => false,
2087 VisibilityKind::Crate(..) |
2088 VisibilityKind::Restricted { .. } => true,
2093 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2094 pub struct StructField {
2097 pub vis: Visibility,
2100 pub attrs: HirVec<Attribute>,
2104 // Still necessary in couple of places
2105 pub fn is_positional(&self) -> bool {
2106 let first = self.ident.as_str().as_bytes()[0];
2107 first >= b'0' && first <= b'9'
2111 /// Fields and Ids of enum variants and structs
2113 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
2114 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
2115 /// One shared Id can be successfully used for these two purposes.
2116 /// Id of the whole enum lives in `Item`.
2118 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
2119 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
2120 /// the variant itself" from enum variants.
2121 /// Id of the whole struct lives in `Item`.
2122 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2123 pub enum VariantData {
2124 Struct(HirVec<StructField>, NodeId),
2125 Tuple(HirVec<StructField>, NodeId),
2130 pub fn fields(&self) -> &[StructField] {
2132 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
2136 pub fn id(&self) -> NodeId {
2138 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id,
2141 pub fn is_struct(&self) -> bool {
2142 if let VariantData::Struct(..) = *self {
2148 pub fn is_tuple(&self) -> bool {
2149 if let VariantData::Tuple(..) = *self {
2155 pub fn is_unit(&self) -> bool {
2156 if let VariantData::Unit(..) = *self {
2164 // The bodies for items are stored "out of line", in a separate
2165 // hashmap in the `Crate`. Here we just record the node-id of the item
2166 // so it can fetched later.
2167 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2174 /// The name might be a dummy name in case of anonymous items
2175 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2180 pub attrs: HirVec<Attribute>,
2182 pub vis: Visibility,
2186 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2187 pub struct FnHeader {
2188 pub unsafety: Unsafety,
2189 pub constness: Constness,
2190 pub asyncness: IsAsync,
2194 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2196 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2198 /// E.g. `extern crate foo` or `extern crate foo_bar as foo`
2199 ExternCrate(Option<Name>),
2201 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2205 /// `use foo::bar::baz;` (with `as baz` implicitly on the right)
2206 Use(P<Path>, UseKind),
2209 Static(P<Ty>, Mutability, BodyId),
2211 Const(P<Ty>, BodyId),
2212 /// A function declaration
2213 Fn(P<FnDecl>, FnHeader, Generics, BodyId),
2216 /// An external module
2217 ForeignMod(ForeignMod),
2218 /// Module-level inline assembly (from global_asm!)
2219 GlobalAsm(P<GlobalAsm>),
2220 /// A type alias, e.g. `type Foo = Bar<u8>`
2221 Ty(P<Ty>, Generics),
2222 /// An existential type definition, e.g. `existential type Foo: Bar;`
2223 Existential(ExistTy),
2224 /// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
2225 Enum(EnumDef, Generics),
2226 /// A struct definition, e.g. `struct Foo<A> {x: A}`
2227 Struct(VariantData, Generics),
2228 /// A union definition, e.g. `union Foo<A, B> {x: A, y: B}`
2229 Union(VariantData, Generics),
2230 /// Represents a Trait Declaration
2231 Trait(IsAuto, Unsafety, Generics, GenericBounds, HirVec<TraitItemRef>),
2232 /// Represents a Trait Alias Declaration
2233 TraitAlias(Generics, GenericBounds),
2235 /// An implementation, eg `impl<A> Trait for Foo { .. }`
2240 Option<TraitRef>, // (optional) trait this impl implements
2242 HirVec<ImplItemRef>),
2246 pub fn descriptive_variant(&self) -> &str {
2248 ItemKind::ExternCrate(..) => "extern crate",
2249 ItemKind::Use(..) => "use",
2250 ItemKind::Static(..) => "static item",
2251 ItemKind::Const(..) => "constant item",
2252 ItemKind::Fn(..) => "function",
2253 ItemKind::Mod(..) => "module",
2254 ItemKind::ForeignMod(..) => "foreign module",
2255 ItemKind::GlobalAsm(..) => "global asm",
2256 ItemKind::Ty(..) => "type alias",
2257 ItemKind::Existential(..) => "existential type",
2258 ItemKind::Enum(..) => "enum",
2259 ItemKind::Struct(..) => "struct",
2260 ItemKind::Union(..) => "union",
2261 ItemKind::Trait(..) => "trait",
2262 ItemKind::TraitAlias(..) => "trait alias",
2263 ItemKind::Impl(..) => "item",
2267 pub fn adt_kind(&self) -> Option<AdtKind> {
2269 ItemKind::Struct(..) => Some(AdtKind::Struct),
2270 ItemKind::Union(..) => Some(AdtKind::Union),
2271 ItemKind::Enum(..) => Some(AdtKind::Enum),
2276 pub fn generics(&self) -> Option<&Generics> {
2278 ItemKind::Fn(_, _, ref generics, _) |
2279 ItemKind::Ty(_, ref generics) |
2280 ItemKind::Existential(ExistTy { ref generics, impl_trait_fn: None, .. }) |
2281 ItemKind::Enum(_, ref generics) |
2282 ItemKind::Struct(_, ref generics) |
2283 ItemKind::Union(_, ref generics) |
2284 ItemKind::Trait(_, _, ref generics, _, _) |
2285 ItemKind::Impl(_, _, _, ref generics, _, _, _)=> generics,
2291 /// A reference from an trait to one of its associated items. This
2292 /// contains the item's id, naturally, but also the item's name and
2293 /// some other high-level details (like whether it is an associated
2294 /// type or method, and whether it is public). This allows other
2295 /// passes to find the impl they want without loading the id (which
2296 /// means fewer edges in the incremental compilation graph).
2297 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2298 pub struct TraitItemRef {
2299 pub id: TraitItemId,
2301 pub kind: AssociatedItemKind,
2303 pub defaultness: Defaultness,
2306 /// A reference from an impl to one of its associated items. This
2307 /// contains the item's id, naturally, but also the item's name and
2308 /// some other high-level details (like whether it is an associated
2309 /// type or method, and whether it is public). This allows other
2310 /// passes to find the impl they want without loading the id (which
2311 /// means fewer edges in the incremental compilation graph).
2312 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2313 pub struct ImplItemRef {
2316 pub kind: AssociatedItemKind,
2318 pub vis: Visibility,
2319 pub defaultness: Defaultness,
2322 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
2323 pub enum AssociatedItemKind {
2325 Method { has_self: bool },
2330 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2331 pub struct ForeignItem {
2333 pub attrs: HirVec<Attribute>,
2334 pub node: ForeignItemKind,
2337 pub vis: Visibility,
2340 /// An item within an `extern` block
2341 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2342 pub enum ForeignItemKind {
2343 /// A foreign function
2344 Fn(P<FnDecl>, HirVec<Ident>, Generics),
2345 /// A foreign static item (`static ext: u8`), with optional mutability
2346 /// (the boolean is true when mutable)
2347 Static(P<Ty>, bool),
2352 impl ForeignItemKind {
2353 pub fn descriptive_variant(&self) -> &str {
2355 ForeignItemKind::Fn(..) => "foreign function",
2356 ForeignItemKind::Static(..) => "foreign static item",
2357 ForeignItemKind::Type => "foreign type",
2362 /// A free variable referred to in a function.
2363 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable)]
2364 pub struct Freevar {
2365 /// The variable being accessed free.
2368 // First span where it is accessed (there can be multiple).
2373 pub fn var_id(&self) -> NodeId {
2375 Def::Local(id) | Def::Upvar(id, ..) => id,
2376 _ => bug!("Freevar::var_id: bad def ({:?})", self.def)
2381 pub type FreevarMap = NodeMap<Vec<Freevar>>;
2383 pub type CaptureModeMap = NodeMap<CaptureClause>;
2385 #[derive(Clone, Debug)]
2386 pub struct TraitCandidate {
2388 pub import_id: Option<NodeId>,
2391 // Trait method resolution
2392 pub type TraitMap = NodeMap<Vec<TraitCandidate>>;
2394 // Map from the NodeId of a glob import to a list of items which are actually
2396 pub type GlobMap = NodeMap<FxHashSet<Name>>;
2399 pub fn provide(providers: &mut Providers<'_>) {
2400 providers.describe_def = map::describe_def;
2403 #[derive(Clone, RustcEncodable, RustcDecodable)]
2404 pub struct CodegenFnAttrs {
2405 pub flags: CodegenFnAttrFlags,
2406 /// Parsed representation of the `#[inline]` attribute
2407 pub inline: InlineAttr,
2408 /// The `#[export_name = "..."]` attribute, indicating a custom symbol a
2409 /// function should be exported under
2410 pub export_name: Option<Symbol>,
2411 /// The `#[link_name = "..."]` attribute, indicating a custom symbol an
2412 /// imported function should be imported as. Note that `export_name`
2413 /// probably isn't set when this is set, this is for foreign items while
2414 /// `#[export_name]` is for Rust-defined functions.
2415 pub link_name: Option<Symbol>,
2416 /// The `#[target_feature(enable = "...")]` attribute and the enabled
2417 /// features (only enabled features are supported right now).
2418 pub target_features: Vec<Symbol>,
2419 /// The `#[linkage = "..."]` attribute and the value we found.
2420 pub linkage: Option<Linkage>,
2421 /// The `#[link_section = "..."]` attribute, or what executable section this
2422 /// should be placed in.
2423 pub link_section: Option<Symbol>,
2427 #[derive(RustcEncodable, RustcDecodable)]
2428 pub struct CodegenFnAttrFlags: u32 {
2429 /// #[cold], a hint to LLVM that this function, when called, is never on
2431 const COLD = 1 << 0;
2432 /// #[allocator], a hint to LLVM that the pointer returned from this
2433 /// function is never null
2434 const ALLOCATOR = 1 << 1;
2435 /// #[unwind], an indicator that this function may unwind despite what
2436 /// its ABI signature may otherwise imply
2437 const UNWIND = 1 << 2;
2438 /// #[rust_allocator_nounwind], an indicator that an imported FFI
2439 /// function will never unwind. Probably obsolete by recent changes with
2440 /// #[unwind], but hasn't been removed/migrated yet
2441 const RUSTC_ALLOCATOR_NOUNWIND = 1 << 3;
2442 /// #[naked], indicates to LLVM that no function prologue/epilogue
2443 /// should be generated
2444 const NAKED = 1 << 4;
2445 /// #[no_mangle], the function's name should be the same as its symbol
2446 const NO_MANGLE = 1 << 5;
2447 /// #[rustc_std_internal_symbol], and indicator that this symbol is a
2448 /// "weird symbol" for the standard library in that it has slightly
2449 /// different linkage, visibility, and reachability rules.
2450 const RUSTC_STD_INTERNAL_SYMBOL = 1 << 6;
2451 /// #[no_debug], indicates that no debugging information should be
2452 /// generated for this function by LLVM
2453 const NO_DEBUG = 1 << 7;
2454 /// #[thread_local], indicates a static is actually a thread local
2456 const THREAD_LOCAL = 1 << 8;
2457 /// #[used], indicates that LLVM can't eliminate this function (but the
2459 const USED = 1 << 9;
2463 impl CodegenFnAttrs {
2464 pub fn new() -> CodegenFnAttrs {
2466 flags: CodegenFnAttrFlags::empty(),
2467 inline: InlineAttr::None,
2470 target_features: vec![],
2476 /// True if `#[inline]` or `#[inline(always)]` is present.
2477 pub fn requests_inline(&self) -> bool {
2479 InlineAttr::Hint | InlineAttr::Always => true,
2480 InlineAttr::None | InlineAttr::Never => false,
2484 /// True if it looks like this symbol needs to be exported, for example:
2486 /// * `#[no_mangle]` is present
2487 /// * `#[export_name(...)]` is present
2488 /// * `#[linkage]` is present
2489 pub fn contains_extern_indicator(&self) -> bool {
2490 self.flags.contains(CodegenFnAttrFlags::NO_MANGLE) ||
2491 self.export_name.is_some() ||
2492 match self.linkage {
2493 // these are private, make sure we don't try to consider
2496 Some(Linkage::Internal) |
2497 Some(Linkage::Private) => false,
2503 #[derive(Copy, Clone, Debug)]
2504 pub enum Node<'hir> {
2506 ForeignItem(&'hir ForeignItem),
2507 TraitItem(&'hir TraitItem),
2508 ImplItem(&'hir ImplItem),
2509 Variant(&'hir Variant),
2510 Field(&'hir StructField),
2511 AnonConst(&'hir AnonConst),
2515 TraitRef(&'hir TraitRef),
2520 MacroDef(&'hir MacroDef),
2522 /// StructCtor represents a tuple struct.
2523 StructCtor(&'hir VariantData),
2525 Lifetime(&'hir Lifetime),
2526 GenericParam(&'hir GenericParam),
2527 Visibility(&'hir Visibility),