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};
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::sync::{ParallelIterator, par_iter, Send, Sync, scope};
41 use rustc_data_structures::thin_vec::ThinVec;
43 use serialize::{self, Encoder, Encodable, Decoder, Decodable};
44 use std::collections::BTreeMap;
47 /// HIR doesn't commit to a concrete storage type and has its own alias for a vector.
48 /// It can be `Vec`, `P<[T]>` or potentially `Box<[T]>`, or some other container with similar
49 /// behavior. Unlike AST, HIR is mostly a static structure, so we can use an owned slice instead
50 /// of `Vec` to avoid keeping extra capacity.
51 pub type HirVec<T> = P<[T]>;
53 macro_rules! hir_vec {
54 ($elem:expr; $n:expr) => (
55 $crate::hir::HirVec::from(vec![$elem; $n])
58 $crate::hir::HirVec::from(vec![$($x),*])
66 pub mod itemlikevisit;
72 /// A HirId uniquely identifies a node in the HIR of the current crate. It is
73 /// composed of the `owner`, which is the DefIndex of the directly enclosing
74 /// hir::Item, hir::TraitItem, or hir::ImplItem (i.e. the closest "item-like"),
75 /// and the `local_id` which is unique within the given owner.
77 /// This two-level structure makes for more stable values: One can move an item
78 /// around within the source code, or add or remove stuff before it, without
79 /// the local_id part of the HirId changing, which is a very useful property in
80 /// incremental compilation where we have to persist things through changes to
82 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
85 pub local_id: ItemLocalId,
89 pub fn owner_def_id(self) -> DefId {
90 DefId::local(self.owner)
93 pub fn owner_local_def_id(self) -> LocalDefId {
94 LocalDefId::from_def_id(DefId::local(self.owner))
98 impl serialize::UseSpecializedEncodable for HirId {
99 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
110 impl serialize::UseSpecializedDecodable for HirId {
111 fn default_decode<D: Decoder>(d: &mut D) -> Result<HirId, D::Error> {
112 let owner = DefIndex::decode(d)?;
113 let local_id = ItemLocalId::decode(d)?;
122 // hack to ensure that we don't try to access the private parts of `ItemLocalId` in this module
123 mod item_local_id_inner {
124 use rustc_data_structures::indexed_vec::Idx;
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.
134 pub struct ItemLocalId { .. }
138 pub use self::item_local_id_inner::ItemLocalId;
140 /// The `HirId` corresponding to CRATE_NODE_ID and CRATE_DEF_INDEX
141 pub const CRATE_HIR_ID: HirId = HirId {
142 owner: CRATE_DEF_INDEX,
143 local_id: ItemLocalId::from_u32_const(0)
146 pub const DUMMY_HIR_ID: HirId = HirId {
147 owner: CRATE_DEF_INDEX,
148 local_id: DUMMY_ITEM_LOCAL_ID,
151 pub const DUMMY_ITEM_LOCAL_ID: ItemLocalId = ItemLocalId::MAX;
153 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
158 impl fmt::Debug for Label {
159 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160 write!(f, "label({:?})", self.ident)
164 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
165 pub struct Lifetime {
169 /// Either "'a", referring to a named lifetime definition,
170 /// or "" (aka keywords::Invalid), for elision placeholders.
172 /// HIR lowering inserts these placeholders in type paths that
173 /// refer to type definitions needing lifetime parameters,
174 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
175 pub name: LifetimeName,
178 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
180 /// Some user-given name like `T` or `'x`.
183 /// Synthetic name generated when user elided a lifetime in an impl header,
184 /// e.g. the lifetimes in cases like these:
186 /// impl Foo for &u32
187 /// impl Foo<'_> for u32
189 /// in that case, we rewrite to
191 /// impl<'f> Foo for &'f u32
192 /// impl<'f> Foo<'f> for u32
194 /// where `'f` is something like `Fresh(0)`. The indices are
195 /// unique per impl, but not necessarily continuous.
198 /// Indicates an illegal name was given and an error has been
199 /// repored (so we should squelch other derived errors). Occurs
200 /// when e.g. `'_` is used in the wrong place.
205 pub fn ident(&self) -> Ident {
207 ParamName::Plain(ident) => ident,
208 ParamName::Error | ParamName::Fresh(_) => keywords::UnderscoreLifetime.ident(),
212 pub fn modern(&self) -> ParamName {
214 ParamName::Plain(ident) => ParamName::Plain(ident.modern()),
215 param_name => param_name,
220 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
221 pub enum LifetimeName {
222 /// User-given names or fresh (synthetic) names.
225 /// User typed nothing. e.g. the lifetime in `&u32`.
228 /// Indicates an error during lowering (usually `'_` in wrong place)
229 /// that was already reported.
235 /// User wrote `'static`
240 pub fn ident(&self) -> Ident {
242 LifetimeName::Implicit => keywords::Invalid.ident(),
243 LifetimeName::Error => keywords::Invalid.ident(),
244 LifetimeName::Underscore => keywords::UnderscoreLifetime.ident(),
245 LifetimeName::Static => keywords::StaticLifetime.ident(),
246 LifetimeName::Param(param_name) => param_name.ident(),
250 pub fn is_elided(&self) -> bool {
252 LifetimeName::Implicit | LifetimeName::Underscore => true,
254 // It might seem surprising that `Fresh(_)` counts as
255 // *not* elided -- but this is because, as far as the code
256 // in the compiler is concerned -- `Fresh(_)` variants act
257 // equivalently to "some fresh name". They correspond to
258 // early-bound regions on an impl, in other words.
259 LifetimeName::Error | LifetimeName::Param(_) | LifetimeName::Static => false,
263 fn is_static(&self) -> bool {
264 self == &LifetimeName::Static
267 pub fn modern(&self) -> LifetimeName {
269 LifetimeName::Param(param_name) => LifetimeName::Param(param_name.modern()),
270 lifetime_name => lifetime_name,
275 impl fmt::Display for Lifetime {
276 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
277 self.name.ident().fmt(f)
281 impl fmt::Debug for Lifetime {
282 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
286 print::to_string(print::NO_ANN, |s| s.print_lifetime(self)))
291 pub fn is_elided(&self) -> bool {
292 self.name.is_elided()
295 pub fn is_static(&self) -> bool {
296 self.name.is_static()
300 /// A "Path" is essentially Rust's notion of a name; for instance:
301 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
302 /// along with a bunch of supporting information.
303 #[derive(Clone, RustcEncodable, RustcDecodable)]
306 /// The definition that the path resolved to.
308 /// The segments in the path: the things separated by `::`.
309 pub segments: HirVec<PathSegment>,
313 pub fn is_global(&self) -> bool {
314 !self.segments.is_empty() && self.segments[0].ident.name == keywords::PathRoot.name()
318 impl fmt::Debug for Path {
319 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
320 write!(f, "path({})", self)
324 impl fmt::Display for Path {
325 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
326 write!(f, "{}", print::to_string(print::NO_ANN, |s| s.print_path(self, false)))
330 /// A segment of a path: an identifier, an optional lifetime, and a set of
332 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
333 pub struct PathSegment {
334 /// The identifier portion of this path segment.
336 // `id` and `def` are optional. We currently only use these in save-analysis,
337 // any path segments without these will not have save-analysis info and
338 // therefore will not have 'jump to def' in IDEs, but otherwise will not be
339 // affected. (In general, we don't bother to get the defs for synthesized
340 // segments, only for segments which have come from the AST).
341 pub id: Option<NodeId>,
342 pub def: Option<Def>,
344 /// Type/lifetime parameters attached to this path. They come in
345 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
346 /// this is more than just simple syntactic sugar; the use of
347 /// parens affects the region binding rules, so we preserve the
349 pub args: Option<P<GenericArgs>>,
351 /// Whether to infer remaining type parameters, if any.
352 /// This only applies to expression and pattern paths, and
353 /// out of those only the segments with no type parameters
354 /// to begin with, e.g. `Vec::new` is `<Vec<..>>::new::<..>`.
355 pub infer_types: bool,
359 /// Convert an identifier to the corresponding segment.
360 pub fn from_ident(ident: Ident) -> PathSegment {
382 args: if args.is_empty() {
390 // FIXME: hack required because you can't create a static
391 // GenericArgs, so you can't just return a &GenericArgs.
392 pub fn with_generic_args<F, R>(&self, f: F) -> R
393 where F: FnOnce(&GenericArgs) -> R
395 let dummy = GenericArgs::none();
396 f(if let Some(ref args) = self.args {
404 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
405 pub enum GenericArg {
411 pub fn span(&self) -> Span {
413 GenericArg::Lifetime(l) => l.span,
414 GenericArg::Type(t) => t.span,
418 pub fn id(&self) -> NodeId {
420 GenericArg::Lifetime(l) => l.id,
421 GenericArg::Type(t) => t.id,
426 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
427 pub struct GenericArgs {
428 /// The generic arguments for this path segment.
429 pub args: HirVec<GenericArg>,
430 /// Bindings (equality constraints) on associated types, if present.
431 /// E.g., `Foo<A=Bar>`.
432 pub bindings: HirVec<TypeBinding>,
433 /// Were arguments written in parenthesized form `Fn(T) -> U`?
434 /// This is required mostly for pretty-printing and diagnostics,
435 /// but also for changing lifetime elision rules to be "function-like".
436 pub parenthesized: bool,
440 pub fn none() -> Self {
443 bindings: HirVec::new(),
444 parenthesized: false,
448 pub fn is_empty(&self) -> bool {
449 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
452 pub fn inputs(&self) -> &[Ty] {
453 if self.parenthesized {
454 for arg in &self.args {
456 GenericArg::Lifetime(_) => {}
457 GenericArg::Type(ref ty) => {
458 if let TyKind::Tup(ref tys) = ty.node {
466 bug!("GenericArgs::inputs: not a `Fn(T) -> U`");
469 pub fn own_counts(&self) -> GenericParamCount {
470 // We could cache this as a property of `GenericParamCount`, but
471 // the aim is to refactor this away entirely eventually and the
472 // presence of this method will be a constant reminder.
473 let mut own_counts: GenericParamCount = Default::default();
475 for arg in &self.args {
477 GenericArg::Lifetime(_) => own_counts.lifetimes += 1,
478 GenericArg::Type(_) => own_counts.types += 1,
486 /// A modifier on a bound, currently this is only used for `?Sized`, where the
487 /// modifier is `Maybe`. Negative bounds should also be handled here.
488 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
489 pub enum TraitBoundModifier {
494 /// The AST represents all type param bounds as types.
495 /// `typeck::collect::compute_bounds` matches these against
496 /// the "special" built-in traits (see `middle::lang_items`) and
497 /// detects `Copy`, `Send` and `Sync`.
498 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
499 pub enum GenericBound {
500 Trait(PolyTraitRef, TraitBoundModifier),
505 pub fn span(&self) -> Span {
507 &GenericBound::Trait(ref t, ..) => t.span,
508 &GenericBound::Outlives(ref l) => l.span,
513 pub type GenericBounds = HirVec<GenericBound>;
515 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
516 pub enum LifetimeParamKind {
517 // Indicates that the lifetime definition was explicitly declared, like:
518 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`
521 // Indicates that the lifetime definition was synthetically added
522 // as a result of an in-band lifetime usage like:
523 // `fn foo(x: &'a u8) -> &'a u8 { x }`
526 // Indication that the lifetime was elided like both cases here:
527 // `fn foo(x: &u8) -> &'_ u8 { x }`
530 // Indication that the lifetime name was somehow in error.
534 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
535 pub enum GenericParamKind {
536 /// A lifetime definition, eg `'a: 'b + 'c + 'd`.
538 kind: LifetimeParamKind,
541 default: Option<P<Ty>>,
542 synthetic: Option<SyntheticTyParamKind>,
546 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
547 pub struct GenericParam {
550 pub attrs: HirVec<Attribute>,
551 pub bounds: GenericBounds,
553 pub pure_wrt_drop: bool,
555 pub kind: GenericParamKind,
559 pub struct GenericParamCount {
560 pub lifetimes: usize,
564 /// Represents lifetimes and type parameters attached to a declaration
565 /// of a function, enum, trait, etc.
566 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
567 pub struct Generics {
568 pub params: HirVec<GenericParam>,
569 pub where_clause: WhereClause,
574 pub fn empty() -> Generics {
576 params: HirVec::new(),
577 where_clause: WhereClause {
579 predicates: HirVec::new(),
585 pub fn own_counts(&self) -> GenericParamCount {
586 // We could cache this as a property of `GenericParamCount`, but
587 // the aim is to refactor this away entirely eventually and the
588 // presence of this method will be a constant reminder.
589 let mut own_counts: GenericParamCount = Default::default();
591 for param in &self.params {
593 GenericParamKind::Lifetime { .. } => own_counts.lifetimes += 1,
594 GenericParamKind::Type { .. } => own_counts.types += 1,
601 pub fn get_named(&self, name: &InternedString) -> Option<&GenericParam> {
602 for param in &self.params {
603 if *name == param.name.ident().as_interned_str() {
611 /// Synthetic Type Parameters are converted to an other form during lowering, this allows
612 /// to track the original form they had. Useful for error messages.
613 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
614 pub enum SyntheticTyParamKind {
618 /// A `where` clause in a definition
619 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
620 pub struct WhereClause {
622 pub predicates: HirVec<WherePredicate>,
626 pub fn span(&self) -> Option<Span> {
627 self.predicates.iter().map(|predicate| predicate.span())
628 .fold(None, |acc, i| match (acc, i) {
629 (None, i) => Some(i),
637 /// A single predicate in a `where` clause
638 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
639 pub enum WherePredicate {
640 /// A type binding, eg `for<'c> Foo: Send+Clone+'c`
641 BoundPredicate(WhereBoundPredicate),
642 /// A lifetime predicate, e.g. `'a: 'b+'c`
643 RegionPredicate(WhereRegionPredicate),
644 /// An equality predicate (unsupported)
645 EqPredicate(WhereEqPredicate),
648 impl WherePredicate {
649 pub fn span(&self) -> Span {
651 &WherePredicate::BoundPredicate(ref p) => p.span,
652 &WherePredicate::RegionPredicate(ref p) => p.span,
653 &WherePredicate::EqPredicate(ref p) => p.span,
658 /// A type bound, eg `for<'c> Foo: Send+Clone+'c`
659 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
660 pub struct WhereBoundPredicate {
662 /// Any generics from a `for` binding
663 pub bound_generic_params: HirVec<GenericParam>,
664 /// The type being bounded
665 pub bounded_ty: P<Ty>,
666 /// Trait and lifetime bounds (`Clone+Send+'static`)
667 pub bounds: GenericBounds,
670 /// A lifetime predicate, e.g. `'a: 'b+'c`
671 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
672 pub struct WhereRegionPredicate {
674 pub lifetime: Lifetime,
675 pub bounds: GenericBounds,
678 /// An equality predicate (unsupported), e.g. `T=int`
679 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
680 pub struct WhereEqPredicate {
687 /// The top-level data structure that stores the entire contents of
688 /// the crate currently being compiled.
690 /// For more details, see the [rustc guide].
692 /// [rustc guide]: https://rust-lang.github.io/rustc-guide/hir.html
693 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
696 pub attrs: HirVec<Attribute>,
698 pub exported_macros: HirVec<MacroDef>,
700 // NB: We use a BTreeMap here so that `visit_all_items` iterates
701 // over the ids in increasing order. In principle it should not
702 // matter what order we visit things in, but in *practice* it
703 // does, because it can affect the order in which errors are
704 // detected, which in turn can make compile-fail tests yield
705 // slightly different results.
706 pub items: BTreeMap<NodeId, Item>,
708 pub trait_items: BTreeMap<TraitItemId, TraitItem>,
709 pub impl_items: BTreeMap<ImplItemId, ImplItem>,
710 pub bodies: BTreeMap<BodyId, Body>,
711 pub trait_impls: BTreeMap<DefId, Vec<NodeId>>,
712 pub trait_auto_impl: BTreeMap<DefId, NodeId>,
714 /// A list of the body ids written out in the order in which they
715 /// appear in the crate. If you're going to process all the bodies
716 /// in the crate, you should iterate over this list rather than the keys
718 pub body_ids: Vec<BodyId>,
722 pub fn item(&self, id: NodeId) -> &Item {
726 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem {
727 &self.trait_items[&id]
730 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem {
731 &self.impl_items[&id]
734 /// Visits all items in the crate in some deterministic (but
735 /// unspecified) order. If you just need to process every item,
736 /// but don't care about nesting, this method is the best choice.
738 /// If you do care about nesting -- usually because your algorithm
739 /// follows lexical scoping rules -- then you want a different
740 /// approach. You should override `visit_nested_item` in your
741 /// visitor and then call `intravisit::walk_crate` instead.
742 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
743 where V: itemlikevisit::ItemLikeVisitor<'hir>
745 for (_, item) in &self.items {
746 visitor.visit_item(item);
749 for (_, trait_item) in &self.trait_items {
750 visitor.visit_trait_item(trait_item);
753 for (_, impl_item) in &self.impl_items {
754 visitor.visit_impl_item(impl_item);
758 /// A parallel version of visit_all_item_likes
759 pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
760 where V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send
764 par_iter(&self.items).for_each(|(_, item)| {
765 visitor.visit_item(item);
770 par_iter(&self.trait_items).for_each(|(_, trait_item)| {
771 visitor.visit_trait_item(trait_item);
776 par_iter(&self.impl_items).for_each(|(_, impl_item)| {
777 visitor.visit_impl_item(impl_item);
783 pub fn body(&self, id: BodyId) -> &Body {
788 /// A macro definition, in this crate or imported from another.
790 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
791 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
792 pub struct MacroDef {
795 pub attrs: HirVec<Attribute>,
798 pub body: TokenStream,
802 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
804 /// Statements in a block
805 pub stmts: HirVec<Stmt>,
806 /// An expression at the end of the block
807 /// without a semicolon, if any
808 pub expr: Option<P<Expr>>,
811 /// Distinguishes between `unsafe { ... }` and `{ ... }`
812 pub rules: BlockCheckMode,
814 /// If true, then there may exist `break 'a` values that aim to
815 /// break out of this block early.
816 /// Used by `'label: {}` blocks and by `catch` statements.
817 pub targeted_by_break: bool,
818 /// If true, don't emit return value type errors as the parser had
819 /// to recover from a parse error so this block will not have an
820 /// appropriate type. A parse error will have been emitted so the
821 /// compilation will never succeed if this is true.
825 #[derive(Clone, RustcEncodable, RustcDecodable)]
833 impl fmt::Debug for Pat {
834 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
835 write!(f, "pat({}: {})", self.id,
836 print::to_string(print::NO_ANN, |s| s.print_pat(self)))
841 // FIXME(#19596) this is a workaround, but there should be a better way
842 fn walk_<G>(&self, it: &mut G) -> bool
843 where G: FnMut(&Pat) -> bool
850 PatKind::Binding(.., Some(ref p)) => p.walk_(it),
851 PatKind::Struct(_, ref fields, _) => {
852 fields.iter().all(|field| field.node.pat.walk_(it))
854 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
855 s.iter().all(|p| p.walk_(it))
857 PatKind::Box(ref s) | PatKind::Ref(ref s, _) => {
860 PatKind::Slice(ref before, ref slice, ref after) => {
864 .all(|p| p.walk_(it))
869 PatKind::Binding(..) |
870 PatKind::Path(_) => {
876 pub fn walk<F>(&self, mut it: F) -> bool
877 where F: FnMut(&Pat) -> bool
883 /// A single field in a struct pattern
885 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
886 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
887 /// except is_shorthand is true
888 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
889 pub struct FieldPat {
891 /// The identifier for the field
893 /// The pattern the field is destructured to
895 pub is_shorthand: bool,
898 /// Explicit binding annotations given in the HIR for a binding. Note
899 /// that this is not the final binding *mode* that we infer after type
901 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
902 pub enum BindingAnnotation {
903 /// No binding annotation given: this means that the final binding mode
904 /// will depend on whether we have skipped through a `&` reference
905 /// when matching. For example, the `x` in `Some(x)` will have binding
906 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
907 /// ultimately be inferred to be by-reference.
909 /// Note that implicit reference skipping is not implemented yet (#42640).
912 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
915 /// Annotated as `ref`, like `ref x`
918 /// Annotated as `ref mut x`.
922 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
928 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
930 /// Represents a wildcard pattern (`_`)
933 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
934 /// The `NodeId` is the canonical ID for the variable being bound,
935 /// e.g. in `Ok(x) | Err(x)`, both `x` use the same canonical ID,
936 /// which is the pattern ID of the first `x`.
937 Binding(BindingAnnotation, NodeId, Ident, Option<P<Pat>>),
939 /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
940 /// The `bool` is `true` in the presence of a `..`.
941 Struct(QPath, HirVec<Spanned<FieldPat>>, bool),
943 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
944 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
945 /// 0 <= position <= subpats.len()
946 TupleStruct(QPath, HirVec<P<Pat>>, Option<usize>),
948 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
951 /// A tuple pattern `(a, b)`.
952 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
953 /// 0 <= position <= subpats.len()
954 Tuple(HirVec<P<Pat>>, Option<usize>),
957 /// A reference pattern, e.g. `&mut (a, b)`
958 Ref(P<Pat>, Mutability),
961 /// A range pattern, e.g. `1...2` or `1..2`
962 Range(P<Expr>, P<Expr>, RangeEnd),
963 /// `[a, b, ..i, y, z]` is represented as:
964 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
965 Slice(HirVec<P<Pat>>, Option<P<Pat>>, HirVec<P<Pat>>),
968 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
969 pub enum Mutability {
975 /// Return MutMutable only if both arguments are mutable.
976 pub fn and(self, other: Self) -> Self {
979 MutImmutable => MutImmutable,
984 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, Hash)]
986 /// The `+` operator (addition)
988 /// The `-` operator (subtraction)
990 /// The `*` operator (multiplication)
992 /// The `/` operator (division)
994 /// The `%` operator (modulus)
996 /// The `&&` operator (logical and)
998 /// The `||` operator (logical or)
1000 /// The `^` operator (bitwise xor)
1002 /// The `&` operator (bitwise and)
1004 /// The `|` operator (bitwise or)
1006 /// The `<<` operator (shift left)
1008 /// The `>>` operator (shift right)
1010 /// The `==` operator (equality)
1012 /// The `<` operator (less than)
1014 /// The `<=` operator (less than or equal to)
1016 /// The `!=` operator (not equal to)
1018 /// The `>=` operator (greater than or equal to)
1020 /// The `>` operator (greater than)
1025 pub fn as_str(self) -> &'static str {
1027 BinOpKind::Add => "+",
1028 BinOpKind::Sub => "-",
1029 BinOpKind::Mul => "*",
1030 BinOpKind::Div => "/",
1031 BinOpKind::Rem => "%",
1032 BinOpKind::And => "&&",
1033 BinOpKind::Or => "||",
1034 BinOpKind::BitXor => "^",
1035 BinOpKind::BitAnd => "&",
1036 BinOpKind::BitOr => "|",
1037 BinOpKind::Shl => "<<",
1038 BinOpKind::Shr => ">>",
1039 BinOpKind::Eq => "==",
1040 BinOpKind::Lt => "<",
1041 BinOpKind::Le => "<=",
1042 BinOpKind::Ne => "!=",
1043 BinOpKind::Ge => ">=",
1044 BinOpKind::Gt => ">",
1048 pub fn is_lazy(self) -> bool {
1050 BinOpKind::And | BinOpKind::Or => true,
1055 pub fn is_shift(self) -> bool {
1057 BinOpKind::Shl | BinOpKind::Shr => true,
1062 pub fn is_comparison(self) -> bool {
1069 BinOpKind::Ge => true,
1081 BinOpKind::Shr => false,
1085 /// Returns `true` if the binary operator takes its arguments by value
1086 pub fn is_by_value(self) -> bool {
1087 !self.is_comparison()
1091 impl Into<ast::BinOpKind> for BinOpKind {
1092 fn into(self) -> ast::BinOpKind {
1094 BinOpKind::Add => ast::BinOpKind::Add,
1095 BinOpKind::Sub => ast::BinOpKind::Sub,
1096 BinOpKind::Mul => ast::BinOpKind::Mul,
1097 BinOpKind::Div => ast::BinOpKind::Div,
1098 BinOpKind::Rem => ast::BinOpKind::Rem,
1099 BinOpKind::And => ast::BinOpKind::And,
1100 BinOpKind::Or => ast::BinOpKind::Or,
1101 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1102 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1103 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1104 BinOpKind::Shl => ast::BinOpKind::Shl,
1105 BinOpKind::Shr => ast::BinOpKind::Shr,
1106 BinOpKind::Eq => ast::BinOpKind::Eq,
1107 BinOpKind::Lt => ast::BinOpKind::Lt,
1108 BinOpKind::Le => ast::BinOpKind::Le,
1109 BinOpKind::Ne => ast::BinOpKind::Ne,
1110 BinOpKind::Ge => ast::BinOpKind::Ge,
1111 BinOpKind::Gt => ast::BinOpKind::Gt,
1116 pub type BinOp = Spanned<BinOpKind>;
1118 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, Hash)]
1120 /// The `*` operator for dereferencing
1122 /// The `!` operator for logical inversion
1124 /// The `-` operator for negation
1129 pub fn as_str(self) -> &'static str {
1137 /// Returns `true` if the unary operator takes its argument by value
1138 pub fn is_by_value(self) -> bool {
1140 UnNeg | UnNot => true,
1147 pub type Stmt = Spanned<StmtKind>;
1149 impl fmt::Debug for StmtKind {
1150 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1152 let spanned = source_map::dummy_spanned(self.clone());
1156 print::to_string(print::NO_ANN, |s| s.print_stmt(&spanned)))
1160 #[derive(Clone, RustcEncodable, RustcDecodable)]
1162 /// Could be an item or a local (let) binding:
1163 Decl(P<Decl>, NodeId),
1165 /// Expr without trailing semi-colon (must have unit type):
1166 Expr(P<Expr>, NodeId),
1168 /// Expr with trailing semi-colon (may have any type):
1169 Semi(P<Expr>, NodeId),
1173 pub fn attrs(&self) -> &[Attribute] {
1175 StmtKind::Decl(ref d, _) => d.node.attrs(),
1176 StmtKind::Expr(ref e, _) |
1177 StmtKind::Semi(ref e, _) => &e.attrs,
1181 pub fn id(&self) -> NodeId {
1183 StmtKind::Decl(_, id) |
1184 StmtKind::Expr(_, id) |
1185 StmtKind::Semi(_, id) => id,
1190 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
1191 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1194 pub ty: Option<P<Ty>>,
1195 /// Initializer expression to set the value, if any
1196 pub init: Option<P<Expr>>,
1200 pub attrs: ThinVec<Attribute>,
1201 pub source: LocalSource,
1204 pub type Decl = Spanned<DeclKind>;
1206 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1208 /// A local (let) binding:
1210 /// An item binding:
1215 pub fn attrs(&self) -> &[Attribute] {
1217 DeclKind::Local(ref l) => &l.attrs,
1218 DeclKind::Item(_) => &[]
1222 pub fn is_local(&self) -> bool {
1224 DeclKind::Local(_) => true,
1230 /// represents one arm of a 'match'
1231 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1233 pub attrs: HirVec<Attribute>,
1234 pub pats: HirVec<P<Pat>>,
1235 pub guard: Option<Guard>,
1239 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1244 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1250 pub is_shorthand: bool,
1253 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1254 pub enum BlockCheckMode {
1256 UnsafeBlock(UnsafeSource),
1257 PushUnsafeBlock(UnsafeSource),
1258 PopUnsafeBlock(UnsafeSource),
1261 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1262 pub enum UnsafeSource {
1267 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1269 pub node_id: NodeId,
1272 /// The body of a function, closure, or constant value. In the case of
1273 /// a function, the body contains not only the function body itself
1274 /// (which is an expression), but also the argument patterns, since
1275 /// those are something that the caller doesn't really care about.
1280 /// fn foo((x, y): (u32, u32)) -> u32 {
1285 /// Here, the `Body` associated with `foo()` would contain:
1287 /// - an `arguments` array containing the `(x, y)` pattern
1288 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1289 /// - `is_generator` would be false
1291 /// All bodies have an **owner**, which can be accessed via the HIR
1292 /// map using `body_owner_def_id()`.
1293 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1295 pub arguments: HirVec<Arg>,
1297 pub is_generator: bool,
1301 pub fn id(&self) -> BodyId {
1303 node_id: self.value.id
1308 #[derive(Copy, Clone, Debug)]
1309 pub enum BodyOwnerKind {
1310 /// Functions and methods.
1313 /// Constants and associated constants.
1316 /// Initializer of a `static` item.
1320 /// A constant (expression) that's not an item or associated item,
1321 /// but needs its own `DefId` for type-checking, const-eval, etc.
1322 /// These are usually found nested inside types (e.g. array lengths)
1323 /// or expressions (e.g. repeat counts), and also used to define
1324 /// explicit discriminant values for enum variants.
1325 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
1326 pub struct AnonConst {
1333 #[derive(Clone, RustcEncodable, RustcDecodable)]
1338 pub attrs: ThinVec<Attribute>,
1343 pub fn precedence(&self) -> ExprPrecedence {
1345 ExprKind::Box(_) => ExprPrecedence::Box,
1346 ExprKind::Array(_) => ExprPrecedence::Array,
1347 ExprKind::Call(..) => ExprPrecedence::Call,
1348 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1349 ExprKind::Tup(_) => ExprPrecedence::Tup,
1350 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1351 ExprKind::Unary(..) => ExprPrecedence::Unary,
1352 ExprKind::Lit(_) => ExprPrecedence::Lit,
1353 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1354 ExprKind::If(..) => ExprPrecedence::If,
1355 ExprKind::While(..) => ExprPrecedence::While,
1356 ExprKind::Loop(..) => ExprPrecedence::Loop,
1357 ExprKind::Match(..) => ExprPrecedence::Match,
1358 ExprKind::Closure(..) => ExprPrecedence::Closure,
1359 ExprKind::Block(..) => ExprPrecedence::Block,
1360 ExprKind::Assign(..) => ExprPrecedence::Assign,
1361 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1362 ExprKind::Field(..) => ExprPrecedence::Field,
1363 ExprKind::Index(..) => ExprPrecedence::Index,
1364 ExprKind::Path(..) => ExprPrecedence::Path,
1365 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1366 ExprKind::Break(..) => ExprPrecedence::Break,
1367 ExprKind::Continue(..) => ExprPrecedence::Continue,
1368 ExprKind::Ret(..) => ExprPrecedence::Ret,
1369 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1370 ExprKind::Struct(..) => ExprPrecedence::Struct,
1371 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1372 ExprKind::Yield(..) => ExprPrecedence::Yield,
1376 pub fn is_place_expr(&self) -> bool {
1378 ExprKind::Path(QPath::Resolved(_, ref path)) => {
1380 Def::Local(..) | Def::Upvar(..) | Def::Static(..) | Def::Err => true,
1385 ExprKind::Type(ref e, _) => {
1389 ExprKind::Unary(UnDeref, _) |
1390 ExprKind::Field(..) |
1391 ExprKind::Index(..) => {
1395 // Partially qualified paths in expressions can only legally
1396 // refer to associated items which are always rvalues.
1397 ExprKind::Path(QPath::TypeRelative(..)) |
1399 ExprKind::Call(..) |
1400 ExprKind::MethodCall(..) |
1401 ExprKind::Struct(..) |
1404 ExprKind::Match(..) |
1405 ExprKind::Closure(..) |
1406 ExprKind::Block(..) |
1407 ExprKind::Repeat(..) |
1408 ExprKind::Array(..) |
1409 ExprKind::Break(..) |
1410 ExprKind::Continue(..) |
1412 ExprKind::While(..) |
1413 ExprKind::Loop(..) |
1414 ExprKind::Assign(..) |
1415 ExprKind::InlineAsm(..) |
1416 ExprKind::AssignOp(..) |
1418 ExprKind::Unary(..) |
1420 ExprKind::AddrOf(..) |
1421 ExprKind::Binary(..) |
1422 ExprKind::Yield(..) |
1423 ExprKind::Cast(..) => {
1430 impl fmt::Debug for Expr {
1431 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1432 write!(f, "expr({}: {})", self.id,
1433 print::to_string(print::NO_ANN, |s| s.print_expr(self)))
1437 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1439 /// A `box x` expression.
1441 /// An array (`[a, b, c, d]`)
1442 Array(HirVec<Expr>),
1445 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1446 /// and the second field is the list of arguments.
1447 /// This also represents calling the constructor of
1448 /// tuple-like ADTs such as tuple structs and enum variants.
1449 Call(P<Expr>, HirVec<Expr>),
1450 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1452 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1453 /// (within the angle brackets).
1454 /// The first element of the vector of `Expr`s is the expression that evaluates
1455 /// to the object on which the method is being called on (the receiver),
1456 /// and the remaining elements are the rest of the arguments.
1457 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1458 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1459 MethodCall(PathSegment, Span, HirVec<Expr>),
1460 /// A tuple (`(a, b, c ,d)`)
1462 /// A binary operation (For example: `a + b`, `a * b`)
1463 Binary(BinOp, P<Expr>, P<Expr>),
1464 /// A unary operation (For example: `!x`, `*x`)
1465 Unary(UnOp, P<Expr>),
1466 /// A literal (For example: `1`, `"foo"`)
1468 /// A cast (`foo as f64`)
1469 Cast(P<Expr>, P<Ty>),
1470 Type(P<Expr>, P<Ty>),
1471 /// An `if` block, with an optional else block
1473 /// `if expr { expr } else { expr }`
1474 If(P<Expr>, P<Expr>, Option<P<Expr>>),
1475 /// A while loop, with an optional label
1477 /// `'label: while expr { block }`
1478 While(P<Expr>, P<Block>, Option<Label>),
1479 /// Conditionless loop (can be exited with break, continue, or return)
1481 /// `'label: loop { block }`
1482 Loop(P<Block>, Option<Label>, LoopSource),
1483 /// A `match` block, with a source that indicates whether or not it is
1484 /// the result of a desugaring, and if so, which kind.
1485 Match(P<Expr>, HirVec<Arm>, MatchSource),
1486 /// A closure (for example, `move |a, b, c| {a + b + c}`).
1488 /// The final span is the span of the argument block `|...|`
1490 /// This may also be a generator literal, indicated by the final boolean,
1491 /// in that case there is an GeneratorClause.
1492 Closure(CaptureClause, P<FnDecl>, BodyId, Span, Option<GeneratorMovability>),
1493 /// A block (`'label: { ... }`)
1494 Block(P<Block>, Option<Label>),
1496 /// An assignment (`a = foo()`)
1497 Assign(P<Expr>, P<Expr>),
1498 /// An assignment with an operator
1500 /// For example, `a += 1`.
1501 AssignOp(BinOp, P<Expr>, P<Expr>),
1502 /// Access of a named (`obj.foo`) or unnamed (`obj.0`) struct or tuple field
1503 Field(P<Expr>, Ident),
1504 /// An indexing operation (`foo[2]`)
1505 Index(P<Expr>, P<Expr>),
1507 /// Path to a definition, possibly containing lifetime or type parameters.
1510 /// A referencing operation (`&a` or `&mut a`)
1511 AddrOf(Mutability, P<Expr>),
1512 /// A `break`, with an optional label to break
1513 Break(Destination, Option<P<Expr>>),
1514 /// A `continue`, with an optional label
1515 Continue(Destination),
1516 /// A `return`, with an optional value to be returned
1517 Ret(Option<P<Expr>>),
1519 /// Inline assembly (from `asm!`), with its outputs and inputs.
1520 InlineAsm(P<InlineAsm>, HirVec<Expr>, HirVec<Expr>),
1522 /// A struct or struct-like variant literal expression.
1524 /// For example, `Foo {x: 1, y: 2}`, or
1525 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
1526 Struct(QPath, HirVec<Field>, Option<P<Expr>>),
1528 /// An array literal constructed from one repeated element.
1530 /// For example, `[1; 5]`. The first expression is the element
1531 /// to be repeated; the second is the number of times to repeat it.
1532 Repeat(P<Expr>, AnonConst),
1534 /// A suspension point for generators. This is `yield <expr>` in Rust.
1538 /// Optionally `Self`-qualified value/type path or associated extension.
1539 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1541 /// Path to a definition, optionally "fully-qualified" with a `Self`
1542 /// type, if the path points to an associated item in a trait.
1544 /// E.g. an unqualified path like `Clone::clone` has `None` for `Self`,
1545 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1546 /// even though they both have the same two-segment `Clone::clone` `Path`.
1547 Resolved(Option<P<Ty>>, P<Path>),
1549 /// Type-related paths, e.g. `<T>::default` or `<T>::Output`.
1550 /// Will be resolved by type-checking to an associated item.
1552 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1553 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1554 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1555 TypeRelative(P<Ty>, P<PathSegment>)
1558 /// Hints at the original code for a let statement
1559 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1560 pub enum LocalSource {
1561 /// A `match _ { .. }`
1563 /// A desugared `for _ in _ { .. }` loop
1567 /// Hints at the original code for a `match _ { .. }`
1568 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1569 pub enum MatchSource {
1570 /// A `match _ { .. }`
1572 /// An `if let _ = _ { .. }` (optionally with `else { .. }`)
1574 contains_else_clause: bool,
1576 /// A `while let _ = _ { .. }` (which was desugared to a
1577 /// `loop { match _ { .. } }`)
1579 /// A desugared `for _ in _ { .. }` loop
1581 /// A desugared `?` operator
1585 /// The loop type that yielded an ExprKind::Loop
1586 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1587 pub enum LoopSource {
1588 /// A `loop { .. }` loop
1590 /// A `while let _ = _ { .. }` loop
1592 /// A `for _ in _ { .. }` loop
1596 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1597 pub enum LoopIdError {
1599 UnlabeledCfInWhileCondition,
1603 impl fmt::Display for LoopIdError {
1604 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1605 fmt::Display::fmt(match *self {
1606 LoopIdError::OutsideLoopScope => "not inside loop scope",
1607 LoopIdError::UnlabeledCfInWhileCondition =>
1608 "unlabeled control flow (break or continue) in while condition",
1609 LoopIdError::UnresolvedLabel => "label not found",
1614 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1615 pub struct Destination {
1616 // This is `Some(_)` iff there is an explicit user-specified `label
1617 pub label: Option<Label>,
1619 // These errors are caught and then reported during the diagnostics pass in
1620 // librustc_passes/loops.rs
1621 pub target_id: Result<NodeId, LoopIdError>,
1624 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1625 pub enum GeneratorMovability {
1630 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1631 pub enum CaptureClause {
1636 // NB: If you change this, you'll probably want to change the corresponding
1637 // type structure in middle/ty.rs as well.
1638 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1641 pub mutbl: Mutability,
1644 /// Represents a method's signature in a trait declaration or implementation.
1645 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1646 pub struct MethodSig {
1647 pub header: FnHeader,
1648 pub decl: P<FnDecl>,
1651 // The bodies for items are stored "out of line", in a separate
1652 // hashmap in the `Crate`. Here we just record the node-id of the item
1653 // so it can fetched later.
1654 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1655 pub struct TraitItemId {
1656 pub node_id: NodeId,
1659 /// Represents an item declaration within a trait declaration,
1660 /// possibly including a default implementation. A trait item is
1661 /// either required (meaning it doesn't have an implementation, just a
1662 /// signature) or provided (meaning it has a default implementation).
1663 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1664 pub struct TraitItem {
1668 pub attrs: HirVec<Attribute>,
1669 pub generics: Generics,
1670 pub node: TraitItemKind,
1674 /// A trait method's body (or just argument names).
1675 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1676 pub enum TraitMethod {
1677 /// No default body in the trait, just a signature.
1678 Required(HirVec<Ident>),
1680 /// Both signature and body are provided in the trait.
1684 /// Represents a trait method or associated constant or type
1685 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1686 pub enum TraitItemKind {
1687 /// An associated constant with an optional value (otherwise `impl`s
1688 /// must contain a value)
1689 Const(P<Ty>, Option<BodyId>),
1690 /// A method with an optional body
1691 Method(MethodSig, TraitMethod),
1692 /// An associated type with (possibly empty) bounds and optional concrete
1694 Type(GenericBounds, Option<P<Ty>>),
1697 // The bodies for items are stored "out of line", in a separate
1698 // hashmap in the `Crate`. Here we just record the node-id of the item
1699 // so it can fetched later.
1700 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1701 pub struct ImplItemId {
1702 pub node_id: NodeId,
1705 /// Represents anything within an `impl` block
1706 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1707 pub struct ImplItem {
1711 pub vis: Visibility,
1712 pub defaultness: Defaultness,
1713 pub attrs: HirVec<Attribute>,
1714 pub generics: Generics,
1715 pub node: ImplItemKind,
1719 /// Represents different contents within `impl`s
1720 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1721 pub enum ImplItemKind {
1722 /// An associated constant of the given type, set to the constant result
1723 /// of the expression
1724 Const(P<Ty>, BodyId),
1725 /// A method implementation with the given signature and body
1726 Method(MethodSig, BodyId),
1727 /// An associated type
1729 /// An associated existential type
1730 Existential(GenericBounds),
1733 // Bind a type to an associated type: `A=Foo`.
1734 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1735 pub struct TypeBinding {
1742 #[derive(Clone, RustcEncodable, RustcDecodable)]
1750 impl fmt::Debug for Ty {
1751 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1752 write!(f, "type({})",
1753 print::to_string(print::NO_ANN, |s| s.print_type(self)))
1757 /// Not represented directly in the AST, referred to by name through a ty_path.
1758 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1768 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1769 pub struct BareFnTy {
1770 pub unsafety: Unsafety,
1772 pub generic_params: HirVec<GenericParam>,
1773 pub decl: P<FnDecl>,
1774 pub arg_names: HirVec<Ident>,
1777 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1778 pub struct ExistTy {
1779 pub generics: Generics,
1780 pub bounds: GenericBounds,
1781 pub impl_trait_fn: Option<DefId>,
1784 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1785 /// The different kinds of types recognized by the compiler
1787 /// A variable length slice (`[T]`)
1789 /// A fixed length array (`[T; n]`)
1790 Array(P<Ty>, AnonConst),
1791 /// A raw pointer (`*const T` or `*mut T`)
1793 /// A reference (`&'a T` or `&'a mut T`)
1794 Rptr(Lifetime, MutTy),
1795 /// A bare function (e.g. `fn(usize) -> bool`)
1796 BareFn(P<BareFnTy>),
1797 /// The never type (`!`)
1799 /// A tuple (`(A, B, C, D,...)`)
1801 /// A path to a type definition (`module::module::...::Type`), or an
1802 /// associated type, e.g. `<Vec<T> as Trait>::Type` or `<T>::Target`.
1804 /// Type parameters may be stored in each `PathSegment`.
1806 /// A type definition itself. This is currently only used for the `existential type`
1807 /// item that `impl Trait` in return position desugars to.
1809 /// The generic arg list are the lifetimes (and in the future possibly parameters) that are
1810 /// actually bound on the `impl Trait`.
1811 Def(ItemId, HirVec<GenericArg>),
1812 /// A trait object type `Bound1 + Bound2 + Bound3`
1813 /// where `Bound` is a trait or a lifetime.
1814 TraitObject(HirVec<PolyTraitRef>, Lifetime),
1817 /// TyKind::Infer means the type should be inferred instead of it having been
1818 /// specified. This can appear anywhere in a type.
1820 /// Placeholder for a type that has failed to be defined.
1824 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1825 pub struct InlineAsmOutput {
1826 pub constraint: Symbol,
1828 pub is_indirect: bool,
1832 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1833 pub struct InlineAsm {
1835 pub asm_str_style: StrStyle,
1836 pub outputs: HirVec<InlineAsmOutput>,
1837 pub inputs: HirVec<Symbol>,
1838 pub clobbers: HirVec<Symbol>,
1840 pub alignstack: bool,
1841 pub dialect: AsmDialect,
1842 pub ctxt: SyntaxContext,
1845 /// represents an argument in a function header
1846 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1853 /// Represents the header (not the body) of a function declaration
1854 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1856 pub inputs: HirVec<Ty>,
1857 pub output: FunctionRetTy,
1859 /// Does the function have an implicit self?
1860 pub implicit_self: ImplicitSelfKind,
1863 /// Represents what type of implicit self a function has, if any.
1864 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
1865 pub enum ImplicitSelfKind {
1866 /// Represents a `fn x(self);`.
1868 /// Represents a `fn x(mut self);`.
1870 /// Represents a `fn x(&self);`.
1872 /// Represents a `fn x(&mut self);`.
1874 /// Represents when a function does not have a self argument or
1875 /// when a function has a `self: X` argument.
1879 impl ImplicitSelfKind {
1880 /// Does this represent an implicit self?
1881 pub fn has_implicit_self(&self) -> bool {
1883 ImplicitSelfKind::None => false,
1889 /// Is the trait definition an auto trait?
1890 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1896 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1902 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1908 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1909 pub enum Constness {
1914 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1915 pub enum Defaultness {
1916 Default { has_value: bool },
1921 pub fn has_value(&self) -> bool {
1923 Defaultness::Default { has_value, .. } => has_value,
1924 Defaultness::Final => true,
1928 pub fn is_final(&self) -> bool {
1929 *self == Defaultness::Final
1932 pub fn is_default(&self) -> bool {
1934 Defaultness::Default { .. } => true,
1940 impl fmt::Display for Unsafety {
1941 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1942 fmt::Display::fmt(match *self {
1943 Unsafety::Normal => "normal",
1944 Unsafety::Unsafe => "unsafe",
1950 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
1951 pub enum ImplPolarity {
1952 /// `impl Trait for Type`
1954 /// `impl !Trait for Type`
1958 impl fmt::Debug for ImplPolarity {
1959 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1961 ImplPolarity::Positive => "positive".fmt(f),
1962 ImplPolarity::Negative => "negative".fmt(f),
1968 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1969 pub enum FunctionRetTy {
1970 /// Return type is not specified.
1972 /// Functions default to `()` and
1973 /// closures default to inference. Span points to where return
1974 /// type would be inserted.
1975 DefaultReturn(Span),
1980 impl FunctionRetTy {
1981 pub fn span(&self) -> Span {
1983 DefaultReturn(span) => span,
1984 Return(ref ty) => ty.span,
1989 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1991 /// A span from the first token past `{` to the last token until `}`.
1992 /// For `mod foo;`, the inner span ranges from the first token
1993 /// to the last token in the external file.
1995 pub item_ids: HirVec<ItemId>,
1998 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1999 pub struct ForeignMod {
2001 pub items: HirVec<ForeignItem>,
2004 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2005 pub struct GlobalAsm {
2007 pub ctxt: SyntaxContext,
2010 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2011 pub struct EnumDef {
2012 pub variants: HirVec<Variant>,
2015 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2016 pub struct VariantKind {
2018 pub attrs: HirVec<Attribute>,
2019 pub data: VariantData,
2020 /// Explicit discriminant, eg `Foo = 1`
2021 pub disr_expr: Option<AnonConst>,
2024 pub type Variant = Spanned<VariantKind>;
2026 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
2028 /// One import, e.g. `use foo::bar` or `use foo::bar as baz`.
2029 /// Also produced for each element of a list `use`, e.g.
2030 // `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2033 /// Glob import, e.g. `use foo::*`.
2036 /// Degenerate list import, e.g. `use foo::{a, b}` produces
2037 /// an additional `use foo::{}` for performing checks such as
2038 /// unstable feature gating. May be removed in the future.
2042 /// TraitRef's appear in impls.
2044 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
2045 /// that the ref_id is for. Note that ref_id's value is not the NodeId of the
2046 /// trait being referred to but just a unique NodeId that serves as a key
2047 /// within the DefMap.
2048 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2049 pub struct TraitRef {
2052 pub hir_ref_id: HirId,
2055 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2056 pub struct PolyTraitRef {
2057 /// The `'a` in `<'a> Foo<&'a T>`
2058 pub bound_generic_params: HirVec<GenericParam>,
2060 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
2061 pub trait_ref: TraitRef,
2066 pub type Visibility = Spanned<VisibilityKind>;
2068 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2069 pub enum VisibilityKind {
2072 Restricted { path: P<Path>, id: NodeId, hir_id: HirId },
2076 impl VisibilityKind {
2077 pub fn is_pub(&self) -> bool {
2079 VisibilityKind::Public => true,
2084 pub fn is_pub_restricted(&self) -> bool {
2086 VisibilityKind::Public |
2087 VisibilityKind::Inherited => false,
2088 VisibilityKind::Crate(..) |
2089 VisibilityKind::Restricted { .. } => true,
2094 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2095 pub struct StructField {
2098 pub vis: Visibility,
2101 pub attrs: HirVec<Attribute>,
2105 // Still necessary in couple of places
2106 pub fn is_positional(&self) -> bool {
2107 let first = self.ident.as_str().as_bytes()[0];
2108 first >= b'0' && first <= b'9'
2112 /// Fields and Ids of enum variants and structs
2114 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
2115 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
2116 /// One shared Id can be successfully used for these two purposes.
2117 /// Id of the whole enum lives in `Item`.
2119 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
2120 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
2121 /// the variant itself" from enum variants.
2122 /// Id of the whole struct lives in `Item`.
2123 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2124 pub enum VariantData {
2125 Struct(HirVec<StructField>, NodeId),
2126 Tuple(HirVec<StructField>, NodeId),
2131 pub fn fields(&self) -> &[StructField] {
2133 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
2137 pub fn id(&self) -> NodeId {
2139 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id,
2142 pub fn is_struct(&self) -> bool {
2143 if let VariantData::Struct(..) = *self {
2149 pub fn is_tuple(&self) -> bool {
2150 if let VariantData::Tuple(..) = *self {
2156 pub fn is_unit(&self) -> bool {
2157 if let VariantData::Unit(..) = *self {
2165 // The bodies for items are stored "out of line", in a separate
2166 // hashmap in the `Crate`. Here we just record the node-id of the item
2167 // so it can fetched later.
2168 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2175 /// The name might be a dummy name in case of anonymous items
2176 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2181 pub attrs: HirVec<Attribute>,
2183 pub vis: Visibility,
2187 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2188 pub struct FnHeader {
2189 pub unsafety: Unsafety,
2190 pub constness: Constness,
2191 pub asyncness: IsAsync,
2195 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2197 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2199 /// E.g. `extern crate foo` or `extern crate foo_bar as foo`
2200 ExternCrate(Option<Name>),
2202 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2206 /// `use foo::bar::baz;` (with `as baz` implicitly on the right)
2207 Use(P<Path>, UseKind),
2210 Static(P<Ty>, Mutability, BodyId),
2212 Const(P<Ty>, BodyId),
2213 /// A function declaration
2214 Fn(P<FnDecl>, FnHeader, Generics, BodyId),
2217 /// An external module
2218 ForeignMod(ForeignMod),
2219 /// Module-level inline assembly (from global_asm!)
2220 GlobalAsm(P<GlobalAsm>),
2221 /// A type alias, e.g. `type Foo = Bar<u8>`
2222 Ty(P<Ty>, Generics),
2223 /// An existential type definition, e.g. `existential type Foo: Bar;`
2224 Existential(ExistTy),
2225 /// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
2226 Enum(EnumDef, Generics),
2227 /// A struct definition, e.g. `struct Foo<A> {x: A}`
2228 Struct(VariantData, Generics),
2229 /// A union definition, e.g. `union Foo<A, B> {x: A, y: B}`
2230 Union(VariantData, Generics),
2231 /// Represents a Trait Declaration
2232 Trait(IsAuto, Unsafety, Generics, GenericBounds, HirVec<TraitItemRef>),
2233 /// Represents a Trait Alias Declaration
2234 TraitAlias(Generics, GenericBounds),
2236 /// An implementation, eg `impl<A> Trait for Foo { .. }`
2241 Option<TraitRef>, // (optional) trait this impl implements
2243 HirVec<ImplItemRef>),
2247 pub fn descriptive_variant(&self) -> &str {
2249 ItemKind::ExternCrate(..) => "extern crate",
2250 ItemKind::Use(..) => "use",
2251 ItemKind::Static(..) => "static item",
2252 ItemKind::Const(..) => "constant item",
2253 ItemKind::Fn(..) => "function",
2254 ItemKind::Mod(..) => "module",
2255 ItemKind::ForeignMod(..) => "foreign module",
2256 ItemKind::GlobalAsm(..) => "global asm",
2257 ItemKind::Ty(..) => "type alias",
2258 ItemKind::Existential(..) => "existential type",
2259 ItemKind::Enum(..) => "enum",
2260 ItemKind::Struct(..) => "struct",
2261 ItemKind::Union(..) => "union",
2262 ItemKind::Trait(..) => "trait",
2263 ItemKind::TraitAlias(..) => "trait alias",
2264 ItemKind::Impl(..) => "item",
2268 pub fn adt_kind(&self) -> Option<AdtKind> {
2270 ItemKind::Struct(..) => Some(AdtKind::Struct),
2271 ItemKind::Union(..) => Some(AdtKind::Union),
2272 ItemKind::Enum(..) => Some(AdtKind::Enum),
2277 pub fn generics(&self) -> Option<&Generics> {
2279 ItemKind::Fn(_, _, ref generics, _) |
2280 ItemKind::Ty(_, ref generics) |
2281 ItemKind::Existential(ExistTy { ref generics, impl_trait_fn: None, .. }) |
2282 ItemKind::Enum(_, ref generics) |
2283 ItemKind::Struct(_, ref generics) |
2284 ItemKind::Union(_, ref generics) |
2285 ItemKind::Trait(_, _, ref generics, _, _) |
2286 ItemKind::Impl(_, _, _, ref generics, _, _, _)=> generics,
2292 /// A reference from an trait to one of its associated items. This
2293 /// contains the item's id, naturally, but also the item's name and
2294 /// some other high-level details (like whether it is an associated
2295 /// type or method, and whether it is public). This allows other
2296 /// passes to find the impl they want without loading the id (which
2297 /// means fewer edges in the incremental compilation graph).
2298 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2299 pub struct TraitItemRef {
2300 pub id: TraitItemId,
2302 pub kind: AssociatedItemKind,
2304 pub defaultness: Defaultness,
2307 /// A reference from an impl to one of its associated items. This
2308 /// contains the item's id, naturally, but also the item's name and
2309 /// some other high-level details (like whether it is an associated
2310 /// type or method, and whether it is public). This allows other
2311 /// passes to find the impl they want without loading the id (which
2312 /// means fewer edges in the incremental compilation graph).
2313 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2314 pub struct ImplItemRef {
2317 pub kind: AssociatedItemKind,
2319 pub vis: Visibility,
2320 pub defaultness: Defaultness,
2323 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
2324 pub enum AssociatedItemKind {
2326 Method { has_self: bool },
2331 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2332 pub struct ForeignItem {
2334 pub attrs: HirVec<Attribute>,
2335 pub node: ForeignItemKind,
2338 pub vis: Visibility,
2341 /// An item within an `extern` block
2342 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2343 pub enum ForeignItemKind {
2344 /// A foreign function
2345 Fn(P<FnDecl>, HirVec<Ident>, Generics),
2346 /// A foreign static item (`static ext: u8`), with optional mutability
2347 /// (the boolean is true when mutable)
2348 Static(P<Ty>, bool),
2353 impl ForeignItemKind {
2354 pub fn descriptive_variant(&self) -> &str {
2356 ForeignItemKind::Fn(..) => "foreign function",
2357 ForeignItemKind::Static(..) => "foreign static item",
2358 ForeignItemKind::Type => "foreign type",
2363 /// A free variable referred to in a function.
2364 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable)]
2365 pub struct Freevar {
2366 /// The variable being accessed free.
2369 // First span where it is accessed (there can be multiple).
2374 pub fn var_id(&self) -> NodeId {
2376 Def::Local(id) | Def::Upvar(id, ..) => id,
2377 _ => bug!("Freevar::var_id: bad def ({:?})", self.def)
2382 pub type FreevarMap = NodeMap<Vec<Freevar>>;
2384 pub type CaptureModeMap = NodeMap<CaptureClause>;
2386 #[derive(Clone, Debug)]
2387 pub struct TraitCandidate {
2389 pub import_id: Option<NodeId>,
2392 // Trait method resolution
2393 pub type TraitMap = NodeMap<Vec<TraitCandidate>>;
2395 // Map from the NodeId of a glob import to a list of items which are actually
2397 pub type GlobMap = NodeMap<FxHashSet<Name>>;
2400 pub fn provide(providers: &mut Providers<'_>) {
2401 providers.describe_def = map::describe_def;
2404 #[derive(Clone, RustcEncodable, RustcDecodable)]
2405 pub struct CodegenFnAttrs {
2406 pub flags: CodegenFnAttrFlags,
2407 /// Parsed representation of the `#[inline]` attribute
2408 pub inline: InlineAttr,
2409 /// The `#[export_name = "..."]` attribute, indicating a custom symbol a
2410 /// function should be exported under
2411 pub export_name: Option<Symbol>,
2412 /// The `#[link_name = "..."]` attribute, indicating a custom symbol an
2413 /// imported function should be imported as. Note that `export_name`
2414 /// probably isn't set when this is set, this is for foreign items while
2415 /// `#[export_name]` is for Rust-defined functions.
2416 pub link_name: Option<Symbol>,
2417 /// The `#[target_feature(enable = "...")]` attribute and the enabled
2418 /// features (only enabled features are supported right now).
2419 pub target_features: Vec<Symbol>,
2420 /// The `#[linkage = "..."]` attribute and the value we found.
2421 pub linkage: Option<Linkage>,
2422 /// The `#[link_section = "..."]` attribute, or what executable section this
2423 /// should be placed in.
2424 pub link_section: Option<Symbol>,
2428 #[derive(RustcEncodable, RustcDecodable)]
2429 pub struct CodegenFnAttrFlags: u32 {
2430 /// #[cold], a hint to LLVM that this function, when called, is never on
2432 const COLD = 1 << 0;
2433 /// #[allocator], a hint to LLVM that the pointer returned from this
2434 /// function is never null
2435 const ALLOCATOR = 1 << 1;
2436 /// #[unwind], an indicator that this function may unwind despite what
2437 /// its ABI signature may otherwise imply
2438 const UNWIND = 1 << 2;
2439 /// #[rust_allocator_nounwind], an indicator that an imported FFI
2440 /// function will never unwind. Probably obsolete by recent changes with
2441 /// #[unwind], but hasn't been removed/migrated yet
2442 const RUSTC_ALLOCATOR_NOUNWIND = 1 << 3;
2443 /// #[naked], indicates to LLVM that no function prologue/epilogue
2444 /// should be generated
2445 const NAKED = 1 << 4;
2446 /// #[no_mangle], the function's name should be the same as its symbol
2447 const NO_MANGLE = 1 << 5;
2448 /// #[rustc_std_internal_symbol], and indicator that this symbol is a
2449 /// "weird symbol" for the standard library in that it has slightly
2450 /// different linkage, visibility, and reachability rules.
2451 const RUSTC_STD_INTERNAL_SYMBOL = 1 << 6;
2452 /// #[no_debug], indicates that no debugging information should be
2453 /// generated for this function by LLVM
2454 const NO_DEBUG = 1 << 7;
2455 /// #[thread_local], indicates a static is actually a thread local
2457 const THREAD_LOCAL = 1 << 8;
2458 /// #[used], indicates that LLVM can't eliminate this function (but the
2460 const USED = 1 << 9;
2464 impl CodegenFnAttrs {
2465 pub fn new() -> CodegenFnAttrs {
2467 flags: CodegenFnAttrFlags::empty(),
2468 inline: InlineAttr::None,
2471 target_features: vec![],
2477 /// True if `#[inline]` or `#[inline(always)]` is present.
2478 pub fn requests_inline(&self) -> bool {
2480 InlineAttr::Hint | InlineAttr::Always => true,
2481 InlineAttr::None | InlineAttr::Never => false,
2485 /// True if it looks like this symbol needs to be exported, for example:
2487 /// * `#[no_mangle]` is present
2488 /// * `#[export_name(...)]` is present
2489 /// * `#[linkage]` is present
2490 pub fn contains_extern_indicator(&self) -> bool {
2491 self.flags.contains(CodegenFnAttrFlags::NO_MANGLE) ||
2492 self.export_name.is_some() ||
2493 match self.linkage {
2494 // these are private, make sure we don't try to consider
2497 Some(Linkage::Internal) |
2498 Some(Linkage::Private) => false,
2504 #[derive(Copy, Clone, Debug)]
2505 pub enum Node<'hir> {
2507 ForeignItem(&'hir ForeignItem),
2508 TraitItem(&'hir TraitItem),
2509 ImplItem(&'hir ImplItem),
2510 Variant(&'hir Variant),
2511 Field(&'hir StructField),
2512 AnonConst(&'hir AnonConst),
2515 PathSegment(&'hir PathSegment),
2517 TraitRef(&'hir TraitRef),
2522 MacroDef(&'hir MacroDef),
2524 /// StructCtor represents a tuple struct.
2525 StructCtor(&'hir VariantData),
2527 Lifetime(&'hir Lifetime),
2528 GenericParam(&'hir GenericParam),
2529 Visibility(&'hir Visibility),