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.
350 // `id` and `def` are optional. We currently only use these in save-analysis,
351 // any path segments without these will not have save-analysis info and
352 // therefore will not have 'jump to def' in IDEs, but otherwise will not be
353 // affected. (In general, we don't bother to get the defs for synthesized
354 // segments, only for segments which have come from the AST).
355 pub id: Option<NodeId>,
356 pub def: Option<Def>,
358 /// Type/lifetime parameters attached to this path. They come in
359 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
360 /// this is more than just simple syntactic sugar; the use of
361 /// parens affects the region binding rules, so we preserve the
363 pub args: Option<P<GenericArgs>>,
365 /// Whether to infer remaining type parameters, if any.
366 /// This only applies to expression and pattern paths, and
367 /// out of those only the segments with no type parameters
368 /// to begin with, e.g. `Vec::new` is `<Vec<..>>::new::<..>`.
369 pub infer_types: bool,
373 /// Convert an identifier to the corresponding segment.
374 pub fn from_ident(ident: Ident) -> PathSegment {
396 args: if args.is_empty() {
404 // FIXME: hack required because you can't create a static
405 // GenericArgs, so you can't just return a &GenericArgs.
406 pub fn with_generic_args<F, R>(&self, f: F) -> R
407 where F: FnOnce(&GenericArgs) -> R
409 let dummy = GenericArgs::none();
410 f(if let Some(ref args) = self.args {
418 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
419 pub enum GenericArg {
425 pub fn span(&self) -> Span {
427 GenericArg::Lifetime(l) => l.span,
428 GenericArg::Type(t) => t.span,
432 pub fn id(&self) -> NodeId {
434 GenericArg::Lifetime(l) => l.id,
435 GenericArg::Type(t) => t.id,
440 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
441 pub struct GenericArgs {
442 /// The generic arguments for this path segment.
443 pub args: HirVec<GenericArg>,
444 /// Bindings (equality constraints) on associated types, if present.
445 /// E.g., `Foo<A=Bar>`.
446 pub bindings: HirVec<TypeBinding>,
447 /// Were arguments written in parenthesized form `Fn(T) -> U`?
448 /// This is required mostly for pretty-printing and diagnostics,
449 /// but also for changing lifetime elision rules to be "function-like".
450 pub parenthesized: bool,
454 pub fn none() -> Self {
457 bindings: HirVec::new(),
458 parenthesized: false,
462 pub fn is_empty(&self) -> bool {
463 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
466 pub fn inputs(&self) -> &[Ty] {
467 if self.parenthesized {
468 for arg in &self.args {
470 GenericArg::Lifetime(_) => {}
471 GenericArg::Type(ref ty) => {
472 if let TyKind::Tup(ref tys) = ty.node {
480 bug!("GenericArgs::inputs: not a `Fn(T) -> U`");
483 pub fn own_counts(&self) -> GenericParamCount {
484 // We could cache this as a property of `GenericParamCount`, but
485 // the aim is to refactor this away entirely eventually and the
486 // presence of this method will be a constant reminder.
487 let mut own_counts: GenericParamCount = Default::default();
489 for arg in &self.args {
491 GenericArg::Lifetime(_) => own_counts.lifetimes += 1,
492 GenericArg::Type(_) => own_counts.types += 1,
500 /// A modifier on a bound, currently this is only used for `?Sized`, where the
501 /// modifier is `Maybe`. Negative bounds should also be handled here.
502 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
503 pub enum TraitBoundModifier {
508 /// The AST represents all type param bounds as types.
509 /// typeck::collect::compute_bounds matches these against
510 /// the "special" built-in traits (see middle::lang_items) and
511 /// detects Copy, Send and Sync.
512 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
513 pub enum GenericBound {
514 Trait(PolyTraitRef, TraitBoundModifier),
519 pub fn span(&self) -> Span {
521 &GenericBound::Trait(ref t, ..) => t.span,
522 &GenericBound::Outlives(ref l) => l.span,
527 pub type GenericBounds = HirVec<GenericBound>;
529 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
530 pub enum LifetimeParamKind {
531 // Indicates that the lifetime definition was explicitly declared, like:
532 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`
535 // Indicates that the lifetime definition was synthetically added
536 // as a result of an in-band lifetime usage like:
537 // `fn foo(x: &'a u8) -> &'a u8 { x }`
540 // Indication that the lifetime was elided like both cases here:
541 // `fn foo(x: &u8) -> &'_ u8 { x }`
544 // Indication that the lifetime name was somehow in error.
548 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
549 pub enum GenericParamKind {
550 /// A lifetime definition, eg `'a: 'b + 'c + 'd`.
552 kind: LifetimeParamKind,
555 default: Option<P<Ty>>,
556 synthetic: Option<SyntheticTyParamKind>,
560 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
561 pub struct GenericParam {
564 pub attrs: HirVec<Attribute>,
565 pub bounds: GenericBounds,
567 pub pure_wrt_drop: bool,
569 pub kind: GenericParamKind,
573 pub struct GenericParamCount {
574 pub lifetimes: usize,
578 /// Represents lifetimes and type parameters attached to a declaration
579 /// of a function, enum, trait, etc.
580 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
581 pub struct Generics {
582 pub params: HirVec<GenericParam>,
583 pub where_clause: WhereClause,
588 pub fn empty() -> Generics {
590 params: HirVec::new(),
591 where_clause: WhereClause {
593 predicates: HirVec::new(),
599 pub fn own_counts(&self) -> GenericParamCount {
600 // We could cache this as a property of `GenericParamCount`, but
601 // the aim is to refactor this away entirely eventually and the
602 // presence of this method will be a constant reminder.
603 let mut own_counts: GenericParamCount = Default::default();
605 for param in &self.params {
607 GenericParamKind::Lifetime { .. } => own_counts.lifetimes += 1,
608 GenericParamKind::Type { .. } => own_counts.types += 1,
615 pub fn get_named(&self, name: &InternedString) -> Option<&GenericParam> {
616 for param in &self.params {
617 if *name == param.name.ident().as_interned_str() {
625 /// Synthetic Type Parameters are converted to an other form during lowering, this allows
626 /// to track the original form they had. Useful for error messages.
627 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
628 pub enum SyntheticTyParamKind {
632 /// A `where` clause in a definition
633 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
634 pub struct WhereClause {
636 pub predicates: HirVec<WherePredicate>,
640 pub fn span(&self) -> Option<Span> {
641 self.predicates.iter().map(|predicate| predicate.span())
642 .fold(None, |acc, i| match (acc, i) {
643 (None, i) => Some(i),
651 /// A single predicate in a `where` clause
652 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
653 pub enum WherePredicate {
654 /// A type binding, eg `for<'c> Foo: Send+Clone+'c`
655 BoundPredicate(WhereBoundPredicate),
656 /// A lifetime predicate, e.g. `'a: 'b+'c`
657 RegionPredicate(WhereRegionPredicate),
658 /// An equality predicate (unsupported)
659 EqPredicate(WhereEqPredicate),
662 impl WherePredicate {
663 pub fn span(&self) -> Span {
665 &WherePredicate::BoundPredicate(ref p) => p.span,
666 &WherePredicate::RegionPredicate(ref p) => p.span,
667 &WherePredicate::EqPredicate(ref p) => p.span,
672 /// A type bound, eg `for<'c> Foo: Send+Clone+'c`
673 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
674 pub struct WhereBoundPredicate {
676 /// Any generics from a `for` binding
677 pub bound_generic_params: HirVec<GenericParam>,
678 /// The type being bounded
679 pub bounded_ty: P<Ty>,
680 /// Trait and lifetime bounds (`Clone+Send+'static`)
681 pub bounds: GenericBounds,
684 /// A lifetime predicate, e.g. `'a: 'b+'c`
685 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
686 pub struct WhereRegionPredicate {
688 pub lifetime: Lifetime,
689 pub bounds: GenericBounds,
692 /// An equality predicate (unsupported), e.g. `T=int`
693 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
694 pub struct WhereEqPredicate {
701 pub type CrateConfig = HirVec<P<MetaItem>>;
703 /// The top-level data structure that stores the entire contents of
704 /// the crate currently being compiled.
706 /// For more details, see the [rustc guide].
708 /// [rustc guide]: https://rust-lang-nursery.github.io/rustc-guide/hir.html
709 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
712 pub attrs: HirVec<Attribute>,
714 pub exported_macros: HirVec<MacroDef>,
716 // NB: We use a BTreeMap here so that `visit_all_items` iterates
717 // over the ids in increasing order. In principle it should not
718 // matter what order we visit things in, but in *practice* it
719 // does, because it can affect the order in which errors are
720 // detected, which in turn can make compile-fail tests yield
721 // slightly different results.
722 pub items: BTreeMap<NodeId, Item>,
724 pub trait_items: BTreeMap<TraitItemId, TraitItem>,
725 pub impl_items: BTreeMap<ImplItemId, ImplItem>,
726 pub bodies: BTreeMap<BodyId, Body>,
727 pub trait_impls: BTreeMap<DefId, Vec<NodeId>>,
728 pub trait_auto_impl: BTreeMap<DefId, NodeId>,
730 /// A list of the body ids written out in the order in which they
731 /// appear in the crate. If you're going to process all the bodies
732 /// in the crate, you should iterate over this list rather than the keys
734 pub body_ids: Vec<BodyId>,
738 pub fn item(&self, id: NodeId) -> &Item {
742 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem {
743 &self.trait_items[&id]
746 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem {
747 &self.impl_items[&id]
750 /// Visits all items in the crate in some deterministic (but
751 /// unspecified) order. If you just need to process every item,
752 /// but don't care about nesting, this method is the best choice.
754 /// If you do care about nesting -- usually because your algorithm
755 /// follows lexical scoping rules -- then you want a different
756 /// approach. You should override `visit_nested_item` in your
757 /// visitor and then call `intravisit::walk_crate` instead.
758 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
759 where V: itemlikevisit::ItemLikeVisitor<'hir>
761 for (_, item) in &self.items {
762 visitor.visit_item(item);
765 for (_, trait_item) in &self.trait_items {
766 visitor.visit_trait_item(trait_item);
769 for (_, impl_item) in &self.impl_items {
770 visitor.visit_impl_item(impl_item);
774 /// A parallel version of visit_all_item_likes
775 pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
776 where V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send
780 par_iter(&self.items).for_each(|(_, item)| {
781 visitor.visit_item(item);
786 par_iter(&self.trait_items).for_each(|(_, trait_item)| {
787 visitor.visit_trait_item(trait_item);
792 par_iter(&self.impl_items).for_each(|(_, impl_item)| {
793 visitor.visit_impl_item(impl_item);
799 pub fn body(&self, id: BodyId) -> &Body {
804 /// A macro definition, in this crate or imported from another.
806 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
807 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
808 pub struct MacroDef {
811 pub attrs: HirVec<Attribute>,
814 pub body: TokenStream,
818 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
820 /// Statements in a block
821 pub stmts: HirVec<Stmt>,
822 /// An expression at the end of the block
823 /// without a semicolon, if any
824 pub expr: Option<P<Expr>>,
827 /// Distinguishes between `unsafe { ... }` and `{ ... }`
828 pub rules: BlockCheckMode,
830 /// If true, then there may exist `break 'a` values that aim to
831 /// break out of this block early.
832 /// Used by `'label: {}` blocks and by `catch` statements.
833 pub targeted_by_break: bool,
834 /// If true, don't emit return value type errors as the parser had
835 /// to recover from a parse error so this block will not have an
836 /// appropriate type. A parse error will have been emitted so the
837 /// compilation will never succeed if this is true.
841 #[derive(Clone, RustcEncodable, RustcDecodable)]
849 impl fmt::Debug for Pat {
850 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
851 write!(f, "pat({}: {})", self.id,
852 print::to_string(print::NO_ANN, |s| s.print_pat(self)))
857 // FIXME(#19596) this is a workaround, but there should be a better way
858 fn walk_<G>(&self, it: &mut G) -> bool
859 where G: FnMut(&Pat) -> bool
866 PatKind::Binding(.., Some(ref p)) => p.walk_(it),
867 PatKind::Struct(_, ref fields, _) => {
868 fields.iter().all(|field| field.node.pat.walk_(it))
870 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
871 s.iter().all(|p| p.walk_(it))
873 PatKind::Box(ref s) | PatKind::Ref(ref s, _) => {
876 PatKind::Slice(ref before, ref slice, ref after) => {
880 .all(|p| p.walk_(it))
885 PatKind::Binding(..) |
886 PatKind::Path(_) => {
892 pub fn walk<F>(&self, mut it: F) -> bool
893 where F: FnMut(&Pat) -> bool
899 /// A single field in a struct pattern
901 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
902 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
903 /// except is_shorthand is true
904 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
905 pub struct FieldPat {
907 /// The identifier for the field
909 /// The pattern the field is destructured to
911 pub is_shorthand: bool,
914 /// Explicit binding annotations given in the HIR for a binding. Note
915 /// that this is not the final binding *mode* that we infer after type
917 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
918 pub enum BindingAnnotation {
919 /// No binding annotation given: this means that the final binding mode
920 /// will depend on whether we have skipped through a `&` reference
921 /// when matching. For example, the `x` in `Some(x)` will have binding
922 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
923 /// ultimately be inferred to be by-reference.
925 /// Note that implicit reference skipping is not implemented yet (#42640).
928 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
931 /// Annotated as `ref`, like `ref x`
934 /// Annotated as `ref mut x`.
938 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
944 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
946 /// Represents a wildcard pattern (`_`)
949 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
950 /// The `NodeId` is the canonical ID for the variable being bound,
951 /// e.g. in `Ok(x) | Err(x)`, both `x` use the same canonical ID,
952 /// which is the pattern ID of the first `x`.
953 Binding(BindingAnnotation, NodeId, Ident, Option<P<Pat>>),
955 /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
956 /// The `bool` is `true` in the presence of a `..`.
957 Struct(QPath, HirVec<Spanned<FieldPat>>, bool),
959 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
960 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
961 /// 0 <= position <= subpats.len()
962 TupleStruct(QPath, HirVec<P<Pat>>, Option<usize>),
964 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
967 /// A tuple pattern `(a, b)`.
968 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
969 /// 0 <= position <= subpats.len()
970 Tuple(HirVec<P<Pat>>, Option<usize>),
973 /// A reference pattern, e.g. `&mut (a, b)`
974 Ref(P<Pat>, Mutability),
977 /// A range pattern, e.g. `1...2` or `1..2`
978 Range(P<Expr>, P<Expr>, RangeEnd),
979 /// `[a, b, ..i, y, z]` is represented as:
980 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
981 Slice(HirVec<P<Pat>>, Option<P<Pat>>, HirVec<P<Pat>>),
984 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
985 pub enum Mutability {
991 /// Return MutMutable only if both arguments are mutable.
992 pub fn and(self, other: Self) -> Self {
995 MutImmutable => MutImmutable,
1000 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, Hash)]
1001 pub enum BinOpKind {
1002 /// The `+` operator (addition)
1004 /// The `-` operator (subtraction)
1006 /// The `*` operator (multiplication)
1008 /// The `/` operator (division)
1010 /// The `%` operator (modulus)
1012 /// The `&&` operator (logical and)
1014 /// The `||` operator (logical or)
1016 /// The `^` operator (bitwise xor)
1018 /// The `&` operator (bitwise and)
1020 /// The `|` operator (bitwise or)
1022 /// The `<<` operator (shift left)
1024 /// The `>>` operator (shift right)
1026 /// The `==` operator (equality)
1028 /// The `<` operator (less than)
1030 /// The `<=` operator (less than or equal to)
1032 /// The `!=` operator (not equal to)
1034 /// The `>=` operator (greater than or equal to)
1036 /// The `>` operator (greater than)
1041 pub fn as_str(self) -> &'static str {
1043 BinOpKind::Add => "+",
1044 BinOpKind::Sub => "-",
1045 BinOpKind::Mul => "*",
1046 BinOpKind::Div => "/",
1047 BinOpKind::Rem => "%",
1048 BinOpKind::And => "&&",
1049 BinOpKind::Or => "||",
1050 BinOpKind::BitXor => "^",
1051 BinOpKind::BitAnd => "&",
1052 BinOpKind::BitOr => "|",
1053 BinOpKind::Shl => "<<",
1054 BinOpKind::Shr => ">>",
1055 BinOpKind::Eq => "==",
1056 BinOpKind::Lt => "<",
1057 BinOpKind::Le => "<=",
1058 BinOpKind::Ne => "!=",
1059 BinOpKind::Ge => ">=",
1060 BinOpKind::Gt => ">",
1064 pub fn is_lazy(self) -> bool {
1066 BinOpKind::And | BinOpKind::Or => true,
1071 pub fn is_shift(self) -> bool {
1073 BinOpKind::Shl | BinOpKind::Shr => true,
1078 pub fn is_comparison(self) -> bool {
1085 BinOpKind::Ge => true,
1097 BinOpKind::Shr => false,
1101 /// Returns `true` if the binary operator takes its arguments by value
1102 pub fn is_by_value(self) -> bool {
1103 !self.is_comparison()
1107 impl Into<ast::BinOpKind> for BinOpKind {
1108 fn into(self) -> ast::BinOpKind {
1110 BinOpKind::Add => ast::BinOpKind::Add,
1111 BinOpKind::Sub => ast::BinOpKind::Sub,
1112 BinOpKind::Mul => ast::BinOpKind::Mul,
1113 BinOpKind::Div => ast::BinOpKind::Div,
1114 BinOpKind::Rem => ast::BinOpKind::Rem,
1115 BinOpKind::And => ast::BinOpKind::And,
1116 BinOpKind::Or => ast::BinOpKind::Or,
1117 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1118 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1119 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1120 BinOpKind::Shl => ast::BinOpKind::Shl,
1121 BinOpKind::Shr => ast::BinOpKind::Shr,
1122 BinOpKind::Eq => ast::BinOpKind::Eq,
1123 BinOpKind::Lt => ast::BinOpKind::Lt,
1124 BinOpKind::Le => ast::BinOpKind::Le,
1125 BinOpKind::Ne => ast::BinOpKind::Ne,
1126 BinOpKind::Ge => ast::BinOpKind::Ge,
1127 BinOpKind::Gt => ast::BinOpKind::Gt,
1132 pub type BinOp = Spanned<BinOpKind>;
1134 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, Hash)]
1136 /// The `*` operator for dereferencing
1138 /// The `!` operator for logical inversion
1140 /// The `-` operator for negation
1145 pub fn as_str(self) -> &'static str {
1153 /// Returns `true` if the unary operator takes its argument by value
1154 pub fn is_by_value(self) -> bool {
1156 UnNeg | UnNot => true,
1163 pub type Stmt = Spanned<StmtKind>;
1165 impl fmt::Debug for StmtKind {
1166 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1168 let spanned = source_map::dummy_spanned(self.clone());
1172 print::to_string(print::NO_ANN, |s| s.print_stmt(&spanned)))
1176 #[derive(Clone, RustcEncodable, RustcDecodable)]
1178 /// Could be an item or a local (let) binding:
1179 Decl(P<Decl>, NodeId),
1181 /// Expr without trailing semi-colon (must have unit type):
1182 Expr(P<Expr>, NodeId),
1184 /// Expr with trailing semi-colon (may have any type):
1185 Semi(P<Expr>, NodeId),
1189 pub fn attrs(&self) -> &[Attribute] {
1191 StmtKind::Decl(ref d, _) => d.node.attrs(),
1192 StmtKind::Expr(ref e, _) |
1193 StmtKind::Semi(ref e, _) => &e.attrs,
1197 pub fn id(&self) -> NodeId {
1199 StmtKind::Decl(_, id) => id,
1200 StmtKind::Expr(_, id) => id,
1201 StmtKind::Semi(_, id) => id,
1206 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
1207 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1210 pub ty: Option<P<Ty>>,
1211 /// Initializer expression to set the value, if any
1212 pub init: Option<P<Expr>>,
1216 pub attrs: ThinVec<Attribute>,
1217 pub source: LocalSource,
1220 pub type Decl = Spanned<DeclKind>;
1222 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1224 /// A local (let) binding:
1226 /// An item binding:
1231 pub fn attrs(&self) -> &[Attribute] {
1233 DeclKind::Local(ref l) => &l.attrs,
1234 DeclKind::Item(_) => &[]
1238 pub fn is_local(&self) -> bool {
1240 DeclKind::Local(_) => true,
1246 /// represents one arm of a 'match'
1247 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1249 pub attrs: HirVec<Attribute>,
1250 pub pats: HirVec<P<Pat>>,
1251 pub guard: Option<Guard>,
1255 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1260 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1266 pub is_shorthand: bool,
1269 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1270 pub enum BlockCheckMode {
1272 UnsafeBlock(UnsafeSource),
1273 PushUnsafeBlock(UnsafeSource),
1274 PopUnsafeBlock(UnsafeSource),
1277 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1278 pub enum UnsafeSource {
1283 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1285 pub node_id: NodeId,
1288 /// The body of a function, closure, or constant value. In the case of
1289 /// a function, the body contains not only the function body itself
1290 /// (which is an expression), but also the argument patterns, since
1291 /// those are something that the caller doesn't really care about.
1296 /// fn foo((x, y): (u32, u32)) -> u32 {
1301 /// Here, the `Body` associated with `foo()` would contain:
1303 /// - an `arguments` array containing the `(x, y)` pattern
1304 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1305 /// - `is_generator` would be false
1307 /// All bodies have an **owner**, which can be accessed via the HIR
1308 /// map using `body_owner_def_id()`.
1309 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1311 pub arguments: HirVec<Arg>,
1313 pub is_generator: bool,
1317 pub fn id(&self) -> BodyId {
1319 node_id: self.value.id
1324 #[derive(Copy, Clone, Debug)]
1325 pub enum BodyOwnerKind {
1326 /// Functions and methods.
1329 /// Constants and associated constants.
1332 /// Initializer of a `static` item.
1336 /// A constant (expression) that's not an item or associated item,
1337 /// but needs its own `DefId` for type-checking, const-eval, etc.
1338 /// These are usually found nested inside types (e.g. array lengths)
1339 /// or expressions (e.g. repeat counts), and also used to define
1340 /// explicit discriminant values for enum variants.
1341 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
1342 pub struct AnonConst {
1349 #[derive(Clone, RustcEncodable, RustcDecodable)]
1354 pub attrs: ThinVec<Attribute>,
1359 pub fn precedence(&self) -> ExprPrecedence {
1361 ExprKind::Box(_) => ExprPrecedence::Box,
1362 ExprKind::Array(_) => ExprPrecedence::Array,
1363 ExprKind::Call(..) => ExprPrecedence::Call,
1364 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1365 ExprKind::Tup(_) => ExprPrecedence::Tup,
1366 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1367 ExprKind::Unary(..) => ExprPrecedence::Unary,
1368 ExprKind::Lit(_) => ExprPrecedence::Lit,
1369 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1370 ExprKind::If(..) => ExprPrecedence::If,
1371 ExprKind::While(..) => ExprPrecedence::While,
1372 ExprKind::Loop(..) => ExprPrecedence::Loop,
1373 ExprKind::Match(..) => ExprPrecedence::Match,
1374 ExprKind::Closure(..) => ExprPrecedence::Closure,
1375 ExprKind::Block(..) => ExprPrecedence::Block,
1376 ExprKind::Assign(..) => ExprPrecedence::Assign,
1377 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1378 ExprKind::Field(..) => ExprPrecedence::Field,
1379 ExprKind::Index(..) => ExprPrecedence::Index,
1380 ExprKind::Path(..) => ExprPrecedence::Path,
1381 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1382 ExprKind::Break(..) => ExprPrecedence::Break,
1383 ExprKind::Continue(..) => ExprPrecedence::Continue,
1384 ExprKind::Ret(..) => ExprPrecedence::Ret,
1385 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1386 ExprKind::Struct(..) => ExprPrecedence::Struct,
1387 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1388 ExprKind::Yield(..) => ExprPrecedence::Yield,
1392 pub fn is_place_expr(&self) -> bool {
1394 ExprKind::Path(QPath::Resolved(_, ref path)) => {
1396 Def::Local(..) | Def::Upvar(..) | Def::Static(..) | Def::Err => true,
1401 ExprKind::Type(ref e, _) => {
1405 ExprKind::Unary(UnDeref, _) |
1406 ExprKind::Field(..) |
1407 ExprKind::Index(..) => {
1411 // Partially qualified paths in expressions can only legally
1412 // refer to associated items which are always rvalues.
1413 ExprKind::Path(QPath::TypeRelative(..)) |
1415 ExprKind::Call(..) |
1416 ExprKind::MethodCall(..) |
1417 ExprKind::Struct(..) |
1420 ExprKind::Match(..) |
1421 ExprKind::Closure(..) |
1422 ExprKind::Block(..) |
1423 ExprKind::Repeat(..) |
1424 ExprKind::Array(..) |
1425 ExprKind::Break(..) |
1426 ExprKind::Continue(..) |
1428 ExprKind::While(..) |
1429 ExprKind::Loop(..) |
1430 ExprKind::Assign(..) |
1431 ExprKind::InlineAsm(..) |
1432 ExprKind::AssignOp(..) |
1434 ExprKind::Unary(..) |
1436 ExprKind::AddrOf(..) |
1437 ExprKind::Binary(..) |
1438 ExprKind::Yield(..) |
1439 ExprKind::Cast(..) => {
1446 impl fmt::Debug for Expr {
1447 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1448 write!(f, "expr({}: {})", self.id,
1449 print::to_string(print::NO_ANN, |s| s.print_expr(self)))
1453 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1455 /// A `box x` expression.
1457 /// An array (`[a, b, c, d]`)
1458 Array(HirVec<Expr>),
1461 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1462 /// and the second field is the list of arguments.
1463 /// This also represents calling the constructor of
1464 /// tuple-like ADTs such as tuple structs and enum variants.
1465 Call(P<Expr>, HirVec<Expr>),
1466 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1468 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1469 /// (within the angle brackets).
1470 /// The first element of the vector of `Expr`s is the expression that evaluates
1471 /// to the object on which the method is being called on (the receiver),
1472 /// and the remaining elements are the rest of the arguments.
1473 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1474 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1475 MethodCall(PathSegment, Span, HirVec<Expr>),
1476 /// A tuple (`(a, b, c ,d)`)
1478 /// A binary operation (For example: `a + b`, `a * b`)
1479 Binary(BinOp, P<Expr>, P<Expr>),
1480 /// A unary operation (For example: `!x`, `*x`)
1481 Unary(UnOp, P<Expr>),
1482 /// A literal (For example: `1`, `"foo"`)
1484 /// A cast (`foo as f64`)
1485 Cast(P<Expr>, P<Ty>),
1486 Type(P<Expr>, P<Ty>),
1487 /// An `if` block, with an optional else block
1489 /// `if expr { expr } else { expr }`
1490 If(P<Expr>, P<Expr>, Option<P<Expr>>),
1491 /// A while loop, with an optional label
1493 /// `'label: while expr { block }`
1494 While(P<Expr>, P<Block>, Option<Label>),
1495 /// Conditionless loop (can be exited with break, continue, or return)
1497 /// `'label: loop { block }`
1498 Loop(P<Block>, Option<Label>, LoopSource),
1499 /// A `match` block, with a source that indicates whether or not it is
1500 /// the result of a desugaring, and if so, which kind.
1501 Match(P<Expr>, HirVec<Arm>, MatchSource),
1502 /// A closure (for example, `move |a, b, c| {a + b + c}`).
1504 /// The final span is the span of the argument block `|...|`
1506 /// This may also be a generator literal, indicated by the final boolean,
1507 /// in that case there is an GeneratorClause.
1508 Closure(CaptureClause, P<FnDecl>, BodyId, Span, Option<GeneratorMovability>),
1509 /// A block (`'label: { ... }`)
1510 Block(P<Block>, Option<Label>),
1512 /// An assignment (`a = foo()`)
1513 Assign(P<Expr>, P<Expr>),
1514 /// An assignment with an operator
1516 /// For example, `a += 1`.
1517 AssignOp(BinOp, P<Expr>, P<Expr>),
1518 /// Access of a named (`obj.foo`) or unnamed (`obj.0`) struct or tuple field
1519 Field(P<Expr>, Ident),
1520 /// An indexing operation (`foo[2]`)
1521 Index(P<Expr>, P<Expr>),
1523 /// Path to a definition, possibly containing lifetime or type parameters.
1526 /// A referencing operation (`&a` or `&mut a`)
1527 AddrOf(Mutability, P<Expr>),
1528 /// A `break`, with an optional label to break
1529 Break(Destination, Option<P<Expr>>),
1530 /// A `continue`, with an optional label
1531 Continue(Destination),
1532 /// A `return`, with an optional value to be returned
1533 Ret(Option<P<Expr>>),
1535 /// Inline assembly (from `asm!`), with its outputs and inputs.
1536 InlineAsm(P<InlineAsm>, HirVec<Expr>, HirVec<Expr>),
1538 /// A struct or struct-like variant literal expression.
1540 /// For example, `Foo {x: 1, y: 2}`, or
1541 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
1542 Struct(QPath, HirVec<Field>, Option<P<Expr>>),
1544 /// An array literal constructed from one repeated element.
1546 /// For example, `[1; 5]`. The first expression is the element
1547 /// to be repeated; the second is the number of times to repeat it.
1548 Repeat(P<Expr>, AnonConst),
1550 /// A suspension point for generators. This is `yield <expr>` in Rust.
1554 /// Optionally `Self`-qualified value/type path or associated extension.
1555 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1557 /// Path to a definition, optionally "fully-qualified" with a `Self`
1558 /// type, if the path points to an associated item in a trait.
1560 /// E.g. an unqualified path like `Clone::clone` has `None` for `Self`,
1561 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1562 /// even though they both have the same two-segment `Clone::clone` `Path`.
1563 Resolved(Option<P<Ty>>, P<Path>),
1565 /// Type-related paths, e.g. `<T>::default` or `<T>::Output`.
1566 /// Will be resolved by type-checking to an associated item.
1568 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1569 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1570 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1571 TypeRelative(P<Ty>, P<PathSegment>)
1574 /// Hints at the original code for a let statement
1575 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1576 pub enum LocalSource {
1577 /// A `match _ { .. }`
1579 /// A desugared `for _ in _ { .. }` loop
1583 /// Hints at the original code for a `match _ { .. }`
1584 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1585 pub enum MatchSource {
1586 /// A `match _ { .. }`
1588 /// An `if let _ = _ { .. }` (optionally with `else { .. }`)
1590 contains_else_clause: bool,
1592 /// A `while let _ = _ { .. }` (which was desugared to a
1593 /// `loop { match _ { .. } }`)
1595 /// A desugared `for _ in _ { .. }` loop
1597 /// A desugared `?` operator
1601 /// The loop type that yielded an ExprKind::Loop
1602 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1603 pub enum LoopSource {
1604 /// A `loop { .. }` loop
1606 /// A `while let _ = _ { .. }` loop
1608 /// A `for _ in _ { .. }` loop
1612 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1613 pub enum LoopIdError {
1615 UnlabeledCfInWhileCondition,
1619 impl fmt::Display for LoopIdError {
1620 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1621 fmt::Display::fmt(match *self {
1622 LoopIdError::OutsideLoopScope => "not inside loop scope",
1623 LoopIdError::UnlabeledCfInWhileCondition =>
1624 "unlabeled control flow (break or continue) in while condition",
1625 LoopIdError::UnresolvedLabel => "label not found",
1630 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1631 pub struct Destination {
1632 // This is `Some(_)` iff there is an explicit user-specified `label
1633 pub label: Option<Label>,
1635 // These errors are caught and then reported during the diagnostics pass in
1636 // librustc_passes/loops.rs
1637 pub target_id: Result<NodeId, LoopIdError>,
1640 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1641 pub enum GeneratorMovability {
1646 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1647 pub enum CaptureClause {
1652 // NB: If you change this, you'll probably want to change the corresponding
1653 // type structure in middle/ty.rs as well.
1654 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1657 pub mutbl: Mutability,
1660 /// Represents a method's signature in a trait declaration or implementation.
1661 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1662 pub struct MethodSig {
1663 pub header: FnHeader,
1664 pub decl: P<FnDecl>,
1667 // The bodies for items are stored "out of line", in a separate
1668 // hashmap in the `Crate`. Here we just record the node-id of the item
1669 // so it can fetched later.
1670 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1671 pub struct TraitItemId {
1672 pub node_id: NodeId,
1675 /// Represents an item declaration within a trait declaration,
1676 /// possibly including a default implementation. A trait item is
1677 /// either required (meaning it doesn't have an implementation, just a
1678 /// signature) or provided (meaning it has a default implementation).
1679 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1680 pub struct TraitItem {
1684 pub attrs: HirVec<Attribute>,
1685 pub generics: Generics,
1686 pub node: TraitItemKind,
1690 /// A trait method's body (or just argument names).
1691 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1692 pub enum TraitMethod {
1693 /// No default body in the trait, just a signature.
1694 Required(HirVec<Ident>),
1696 /// Both signature and body are provided in the trait.
1700 /// Represents a trait method or associated constant or type
1701 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1702 pub enum TraitItemKind {
1703 /// An associated constant with an optional value (otherwise `impl`s
1704 /// must contain a value)
1705 Const(P<Ty>, Option<BodyId>),
1706 /// A method with an optional body
1707 Method(MethodSig, TraitMethod),
1708 /// An associated type with (possibly empty) bounds and optional concrete
1710 Type(GenericBounds, Option<P<Ty>>),
1713 // The bodies for items are stored "out of line", in a separate
1714 // hashmap in the `Crate`. Here we just record the node-id of the item
1715 // so it can fetched later.
1716 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1717 pub struct ImplItemId {
1718 pub node_id: NodeId,
1721 /// Represents anything within an `impl` block
1722 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1723 pub struct ImplItem {
1727 pub vis: Visibility,
1728 pub defaultness: Defaultness,
1729 pub attrs: HirVec<Attribute>,
1730 pub generics: Generics,
1731 pub node: ImplItemKind,
1735 /// Represents different contents within `impl`s
1736 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1737 pub enum ImplItemKind {
1738 /// An associated constant of the given type, set to the constant result
1739 /// of the expression
1740 Const(P<Ty>, BodyId),
1741 /// A method implementation with the given signature and body
1742 Method(MethodSig, BodyId),
1743 /// An associated type
1745 /// An associated existential type
1746 Existential(GenericBounds),
1749 // Bind a type to an associated type: `A=Foo`.
1750 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1751 pub struct TypeBinding {
1758 #[derive(Clone, RustcEncodable, RustcDecodable)]
1766 impl fmt::Debug for Ty {
1767 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1768 write!(f, "type({})",
1769 print::to_string(print::NO_ANN, |s| s.print_type(self)))
1773 /// Not represented directly in the AST, referred to by name through a ty_path.
1774 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1784 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1785 pub struct BareFnTy {
1786 pub unsafety: Unsafety,
1788 pub generic_params: HirVec<GenericParam>,
1789 pub decl: P<FnDecl>,
1790 pub arg_names: HirVec<Ident>,
1793 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1794 pub struct ExistTy {
1795 pub generics: Generics,
1796 pub bounds: GenericBounds,
1797 pub impl_trait_fn: Option<DefId>,
1800 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1801 /// The different kinds of types recognized by the compiler
1803 /// A variable length slice (`[T]`)
1805 /// A fixed length array (`[T; n]`)
1806 Array(P<Ty>, AnonConst),
1807 /// A raw pointer (`*const T` or `*mut T`)
1809 /// A reference (`&'a T` or `&'a mut T`)
1810 Rptr(Lifetime, MutTy),
1811 /// A bare function (e.g. `fn(usize) -> bool`)
1812 BareFn(P<BareFnTy>),
1813 /// The never type (`!`)
1815 /// A tuple (`(A, B, C, D,...)`)
1817 /// A path to a type definition (`module::module::...::Type`), or an
1818 /// associated type, e.g. `<Vec<T> as Trait>::Type` or `<T>::Target`.
1820 /// Type parameters may be stored in each `PathSegment`.
1822 /// A type definition itself. This is currently only used for the `existential type`
1823 /// item that `impl Trait` in return position desugars to.
1825 /// The generic arg list are the lifetimes (and in the future possibly parameters) that are
1826 /// actually bound on the `impl Trait`.
1827 Def(ItemId, HirVec<GenericArg>),
1828 /// A trait object type `Bound1 + Bound2 + Bound3`
1829 /// where `Bound` is a trait or a lifetime.
1830 TraitObject(HirVec<PolyTraitRef>, Lifetime),
1833 /// TyKind::Infer means the type should be inferred instead of it having been
1834 /// specified. This can appear anywhere in a type.
1836 /// Placeholder for a type that has failed to be defined.
1840 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1841 pub struct InlineAsmOutput {
1842 pub constraint: Symbol,
1844 pub is_indirect: bool,
1848 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1849 pub struct InlineAsm {
1851 pub asm_str_style: StrStyle,
1852 pub outputs: HirVec<InlineAsmOutput>,
1853 pub inputs: HirVec<Symbol>,
1854 pub clobbers: HirVec<Symbol>,
1856 pub alignstack: bool,
1857 pub dialect: AsmDialect,
1858 pub ctxt: SyntaxContext,
1861 /// represents an argument in a function header
1862 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1869 /// Represents the header (not the body) of a function declaration
1870 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1872 pub inputs: HirVec<Ty>,
1873 pub output: FunctionRetTy,
1875 /// Does the function have an implicit self?
1876 pub implicit_self: ImplicitSelfKind,
1879 /// Represents what type of implicit self a function has, if any.
1880 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
1881 pub enum ImplicitSelfKind {
1882 /// Represents a `fn x(self);`.
1884 /// Represents a `fn x(mut self);`.
1886 /// Represents a `fn x(&self);`.
1888 /// Represents a `fn x(&mut self);`.
1890 /// Represents when a function does not have a self argument or
1891 /// when a function has a `self: X` argument.
1895 impl ImplicitSelfKind {
1896 /// Does this represent an implicit self?
1897 pub fn has_implicit_self(&self) -> bool {
1899 ImplicitSelfKind::None => false,
1905 /// Is the trait definition an auto trait?
1906 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1912 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1918 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1924 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1925 pub enum Constness {
1930 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1931 pub enum Defaultness {
1932 Default { has_value: bool },
1937 pub fn has_value(&self) -> bool {
1939 Defaultness::Default { has_value, .. } => has_value,
1940 Defaultness::Final => true,
1944 pub fn is_final(&self) -> bool {
1945 *self == Defaultness::Final
1948 pub fn is_default(&self) -> bool {
1950 Defaultness::Default { .. } => true,
1956 impl fmt::Display for Unsafety {
1957 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1958 fmt::Display::fmt(match *self {
1959 Unsafety::Normal => "normal",
1960 Unsafety::Unsafe => "unsafe",
1966 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
1967 pub enum ImplPolarity {
1968 /// `impl Trait for Type`
1970 /// `impl !Trait for Type`
1974 impl fmt::Debug for ImplPolarity {
1975 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1977 ImplPolarity::Positive => "positive".fmt(f),
1978 ImplPolarity::Negative => "negative".fmt(f),
1984 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1985 pub enum FunctionRetTy {
1986 /// Return type is not specified.
1988 /// Functions default to `()` and
1989 /// closures default to inference. Span points to where return
1990 /// type would be inserted.
1991 DefaultReturn(Span),
1996 impl FunctionRetTy {
1997 pub fn span(&self) -> Span {
1999 DefaultReturn(span) => span,
2000 Return(ref ty) => ty.span,
2005 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2007 /// A span from the first token past `{` to the last token until `}`.
2008 /// For `mod foo;`, the inner span ranges from the first token
2009 /// to the last token in the external file.
2011 pub item_ids: HirVec<ItemId>,
2014 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2015 pub struct ForeignMod {
2017 pub items: HirVec<ForeignItem>,
2020 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2021 pub struct GlobalAsm {
2023 pub ctxt: SyntaxContext,
2026 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2027 pub struct EnumDef {
2028 pub variants: HirVec<Variant>,
2031 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2032 pub struct VariantKind {
2034 pub attrs: HirVec<Attribute>,
2035 pub data: VariantData,
2036 /// Explicit discriminant, eg `Foo = 1`
2037 pub disr_expr: Option<AnonConst>,
2040 pub type Variant = Spanned<VariantKind>;
2042 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
2044 /// One import, e.g. `use foo::bar` or `use foo::bar as baz`.
2045 /// Also produced for each element of a list `use`, e.g.
2046 // `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2049 /// Glob import, e.g. `use foo::*`.
2052 /// Degenerate list import, e.g. `use foo::{a, b}` produces
2053 /// an additional `use foo::{}` for performing checks such as
2054 /// unstable feature gating. May be removed in the future.
2058 /// TraitRef's appear in impls.
2060 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
2061 /// that the ref_id is for. Note that ref_id's value is not the NodeId of the
2062 /// trait being referred to but just a unique NodeId that serves as a key
2063 /// within the DefMap.
2064 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2065 pub struct TraitRef {
2068 pub hir_ref_id: HirId,
2071 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2072 pub struct PolyTraitRef {
2073 /// The `'a` in `<'a> Foo<&'a T>`
2074 pub bound_generic_params: HirVec<GenericParam>,
2076 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
2077 pub trait_ref: TraitRef,
2082 pub type Visibility = Spanned<VisibilityKind>;
2084 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2085 pub enum VisibilityKind {
2088 Restricted { path: P<Path>, id: NodeId, hir_id: HirId },
2092 impl VisibilityKind {
2093 pub fn is_pub(&self) -> bool {
2095 VisibilityKind::Public => true,
2100 pub fn is_pub_restricted(&self) -> bool {
2102 VisibilityKind::Public |
2103 VisibilityKind::Inherited => false,
2104 VisibilityKind::Crate(..) |
2105 VisibilityKind::Restricted { .. } => true,
2110 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2111 pub struct StructField {
2114 pub vis: Visibility,
2117 pub attrs: HirVec<Attribute>,
2121 // Still necessary in couple of places
2122 pub fn is_positional(&self) -> bool {
2123 let first = self.ident.as_str().as_bytes()[0];
2124 first >= b'0' && first <= b'9'
2128 /// Fields and Ids of enum variants and structs
2130 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
2131 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
2132 /// One shared Id can be successfully used for these two purposes.
2133 /// Id of the whole enum lives in `Item`.
2135 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
2136 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
2137 /// the variant itself" from enum variants.
2138 /// Id of the whole struct lives in `Item`.
2139 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2140 pub enum VariantData {
2141 Struct(HirVec<StructField>, NodeId),
2142 Tuple(HirVec<StructField>, NodeId),
2147 pub fn fields(&self) -> &[StructField] {
2149 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
2153 pub fn id(&self) -> NodeId {
2155 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id,
2158 pub fn is_struct(&self) -> bool {
2159 if let VariantData::Struct(..) = *self {
2165 pub fn is_tuple(&self) -> bool {
2166 if let VariantData::Tuple(..) = *self {
2172 pub fn is_unit(&self) -> bool {
2173 if let VariantData::Unit(..) = *self {
2181 // The bodies for items are stored "out of line", in a separate
2182 // hashmap in the `Crate`. Here we just record the node-id of the item
2183 // so it can fetched later.
2184 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2191 /// The name might be a dummy name in case of anonymous items
2192 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2197 pub attrs: HirVec<Attribute>,
2199 pub vis: Visibility,
2203 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2204 pub struct FnHeader {
2205 pub unsafety: Unsafety,
2206 pub constness: Constness,
2207 pub asyncness: IsAsync,
2211 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2213 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2215 /// E.g. `extern crate foo` or `extern crate foo_bar as foo`
2216 ExternCrate(Option<Name>),
2218 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2222 /// `use foo::bar::baz;` (with `as baz` implicitly on the right)
2223 Use(P<Path>, UseKind),
2226 Static(P<Ty>, Mutability, BodyId),
2228 Const(P<Ty>, BodyId),
2229 /// A function declaration
2230 Fn(P<FnDecl>, FnHeader, Generics, BodyId),
2233 /// An external module
2234 ForeignMod(ForeignMod),
2235 /// Module-level inline assembly (from global_asm!)
2236 GlobalAsm(P<GlobalAsm>),
2237 /// A type alias, e.g. `type Foo = Bar<u8>`
2238 Ty(P<Ty>, Generics),
2239 /// An existential type definition, e.g. `existential type Foo: Bar;`
2240 Existential(ExistTy),
2241 /// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
2242 Enum(EnumDef, Generics),
2243 /// A struct definition, e.g. `struct Foo<A> {x: A}`
2244 Struct(VariantData, Generics),
2245 /// A union definition, e.g. `union Foo<A, B> {x: A, y: B}`
2246 Union(VariantData, Generics),
2247 /// Represents a Trait Declaration
2248 Trait(IsAuto, Unsafety, Generics, GenericBounds, HirVec<TraitItemRef>),
2249 /// Represents a Trait Alias Declaration
2250 TraitAlias(Generics, GenericBounds),
2252 /// An implementation, eg `impl<A> Trait for Foo { .. }`
2257 Option<TraitRef>, // (optional) trait this impl implements
2259 HirVec<ImplItemRef>),
2263 pub fn descriptive_variant(&self) -> &str {
2265 ItemKind::ExternCrate(..) => "extern crate",
2266 ItemKind::Use(..) => "use",
2267 ItemKind::Static(..) => "static item",
2268 ItemKind::Const(..) => "constant item",
2269 ItemKind::Fn(..) => "function",
2270 ItemKind::Mod(..) => "module",
2271 ItemKind::ForeignMod(..) => "foreign module",
2272 ItemKind::GlobalAsm(..) => "global asm",
2273 ItemKind::Ty(..) => "type alias",
2274 ItemKind::Existential(..) => "existential type",
2275 ItemKind::Enum(..) => "enum",
2276 ItemKind::Struct(..) => "struct",
2277 ItemKind::Union(..) => "union",
2278 ItemKind::Trait(..) => "trait",
2279 ItemKind::TraitAlias(..) => "trait alias",
2280 ItemKind::Impl(..) => "item",
2284 pub fn adt_kind(&self) -> Option<AdtKind> {
2286 ItemKind::Struct(..) => Some(AdtKind::Struct),
2287 ItemKind::Union(..) => Some(AdtKind::Union),
2288 ItemKind::Enum(..) => Some(AdtKind::Enum),
2293 pub fn generics(&self) -> Option<&Generics> {
2295 ItemKind::Fn(_, _, ref generics, _) |
2296 ItemKind::Ty(_, ref generics) |
2297 ItemKind::Existential(ExistTy { ref generics, impl_trait_fn: None, .. }) |
2298 ItemKind::Enum(_, ref generics) |
2299 ItemKind::Struct(_, ref generics) |
2300 ItemKind::Union(_, ref generics) |
2301 ItemKind::Trait(_, _, ref generics, _, _) |
2302 ItemKind::Impl(_, _, _, ref generics, _, _, _)=> generics,
2308 /// A reference from an trait to one of its associated items. This
2309 /// contains the item's id, naturally, but also the item's name and
2310 /// some other high-level details (like whether it is an associated
2311 /// type or method, and whether it is public). This allows other
2312 /// passes to find the impl they want without loading the id (which
2313 /// means fewer edges in the incremental compilation graph).
2314 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2315 pub struct TraitItemRef {
2316 pub id: TraitItemId,
2318 pub kind: AssociatedItemKind,
2320 pub defaultness: Defaultness,
2323 /// A reference from an impl to one of its associated items. This
2324 /// contains the item's id, naturally, but also the item's name and
2325 /// some other high-level details (like whether it is an associated
2326 /// type or method, and whether it is public). This allows other
2327 /// passes to find the impl they want without loading the id (which
2328 /// means fewer edges in the incremental compilation graph).
2329 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2330 pub struct ImplItemRef {
2333 pub kind: AssociatedItemKind,
2335 pub vis: Visibility,
2336 pub defaultness: Defaultness,
2339 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
2340 pub enum AssociatedItemKind {
2342 Method { has_self: bool },
2347 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2348 pub struct ForeignItem {
2350 pub attrs: HirVec<Attribute>,
2351 pub node: ForeignItemKind,
2354 pub vis: Visibility,
2357 /// An item within an `extern` block
2358 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2359 pub enum ForeignItemKind {
2360 /// A foreign function
2361 Fn(P<FnDecl>, HirVec<Ident>, Generics),
2362 /// A foreign static item (`static ext: u8`), with optional mutability
2363 /// (the boolean is true when mutable)
2364 Static(P<Ty>, bool),
2369 impl ForeignItemKind {
2370 pub fn descriptive_variant(&self) -> &str {
2372 ForeignItemKind::Fn(..) => "foreign function",
2373 ForeignItemKind::Static(..) => "foreign static item",
2374 ForeignItemKind::Type => "foreign type",
2379 /// A free variable referred to in a function.
2380 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable)]
2381 pub struct Freevar {
2382 /// The variable being accessed free.
2385 // First span where it is accessed (there can be multiple).
2390 pub fn var_id(&self) -> NodeId {
2392 Def::Local(id) | Def::Upvar(id, ..) => id,
2393 _ => bug!("Freevar::var_id: bad def ({:?})", self.def)
2398 pub type FreevarMap = NodeMap<Vec<Freevar>>;
2400 pub type CaptureModeMap = NodeMap<CaptureClause>;
2402 #[derive(Clone, Debug)]
2403 pub struct TraitCandidate {
2405 pub import_id: Option<NodeId>,
2408 // Trait method resolution
2409 pub type TraitMap = NodeMap<Vec<TraitCandidate>>;
2411 // Map from the NodeId of a glob import to a list of items which are actually
2413 pub type GlobMap = NodeMap<FxHashSet<Name>>;
2416 pub fn provide(providers: &mut Providers<'_>) {
2417 providers.describe_def = map::describe_def;
2420 #[derive(Clone, RustcEncodable, RustcDecodable)]
2421 pub struct CodegenFnAttrs {
2422 pub flags: CodegenFnAttrFlags,
2423 /// Parsed representation of the `#[inline]` attribute
2424 pub inline: InlineAttr,
2425 /// The `#[export_name = "..."]` attribute, indicating a custom symbol a
2426 /// function should be exported under
2427 pub export_name: Option<Symbol>,
2428 /// The `#[link_name = "..."]` attribute, indicating a custom symbol an
2429 /// imported function should be imported as. Note that `export_name`
2430 /// probably isn't set when this is set, this is for foreign items while
2431 /// `#[export_name]` is for Rust-defined functions.
2432 pub link_name: Option<Symbol>,
2433 /// The `#[target_feature(enable = "...")]` attribute and the enabled
2434 /// features (only enabled features are supported right now).
2435 pub target_features: Vec<Symbol>,
2436 /// The `#[linkage = "..."]` attribute and the value we found.
2437 pub linkage: Option<Linkage>,
2438 /// The `#[link_section = "..."]` attribute, or what executable section this
2439 /// should be placed in.
2440 pub link_section: Option<Symbol>,
2444 #[derive(RustcEncodable, RustcDecodable)]
2445 pub struct CodegenFnAttrFlags: u32 {
2446 /// #[cold], a hint to LLVM that this function, when called, is never on
2448 const COLD = 1 << 0;
2449 /// #[allocator], a hint to LLVM that the pointer returned from this
2450 /// function is never null
2451 const ALLOCATOR = 1 << 1;
2452 /// #[unwind], an indicator that this function may unwind despite what
2453 /// its ABI signature may otherwise imply
2454 const UNWIND = 1 << 2;
2455 /// #[rust_allocator_nounwind], an indicator that an imported FFI
2456 /// function will never unwind. Probably obsolete by recent changes with
2457 /// #[unwind], but hasn't been removed/migrated yet
2458 const RUSTC_ALLOCATOR_NOUNWIND = 1 << 3;
2459 /// #[naked], indicates to LLVM that no function prologue/epilogue
2460 /// should be generated
2461 const NAKED = 1 << 4;
2462 /// #[no_mangle], the function's name should be the same as its symbol
2463 const NO_MANGLE = 1 << 5;
2464 /// #[rustc_std_internal_symbol], and indicator that this symbol is a
2465 /// "weird symbol" for the standard library in that it has slightly
2466 /// different linkage, visibility, and reachability rules.
2467 const RUSTC_STD_INTERNAL_SYMBOL = 1 << 6;
2468 /// #[no_debug], indicates that no debugging information should be
2469 /// generated for this function by LLVM
2470 const NO_DEBUG = 1 << 7;
2471 /// #[thread_local], indicates a static is actually a thread local
2473 const THREAD_LOCAL = 1 << 8;
2474 /// #[used], indicates that LLVM can't eliminate this function (but the
2476 const USED = 1 << 9;
2480 impl CodegenFnAttrs {
2481 pub fn new() -> CodegenFnAttrs {
2483 flags: CodegenFnAttrFlags::empty(),
2484 inline: InlineAttr::None,
2487 target_features: vec![],
2493 /// True if `#[inline]` or `#[inline(always)]` is present.
2494 pub fn requests_inline(&self) -> bool {
2496 InlineAttr::Hint | InlineAttr::Always => true,
2497 InlineAttr::None | InlineAttr::Never => false,
2501 /// True if it looks like this symbol needs to be exported, for example:
2503 /// * `#[no_mangle]` is present
2504 /// * `#[export_name(...)]` is present
2505 /// * `#[linkage]` is present
2506 pub fn contains_extern_indicator(&self) -> bool {
2507 self.flags.contains(CodegenFnAttrFlags::NO_MANGLE) ||
2508 self.export_name.is_some() ||
2509 match self.linkage {
2510 // these are private, make sure we don't try to consider
2513 Some(Linkage::Internal) |
2514 Some(Linkage::Private) => false,
2520 #[derive(Copy, Clone, Debug)]
2521 pub enum Node<'hir> {
2523 ForeignItem(&'hir ForeignItem),
2524 TraitItem(&'hir TraitItem),
2525 ImplItem(&'hir ImplItem),
2526 Variant(&'hir Variant),
2527 Field(&'hir StructField),
2528 AnonConst(&'hir AnonConst),
2531 PathSegment(&'hir PathSegment),
2533 TraitRef(&'hir TraitRef),
2538 MacroDef(&'hir MacroDef),
2540 /// StructCtor represents a tuple struct.
2541 StructCtor(&'hir VariantData),
2543 Lifetime(&'hir Lifetime),
2544 GenericParam(&'hir GenericParam),
2545 Visibility(&'hir Visibility),