1 //! HIR datatypes. See the [rustc guide] for more info.
3 //! [rustc guide]: https://rust-lang.github.io/rustc-guide/hir.html
5 pub use self::BlockCheckMode::*;
6 pub use self::CaptureClause::*;
7 pub use self::FunctionRetTy::*;
8 pub use self::Mutability::*;
9 pub use self::PrimTy::*;
10 pub use self::UnOp::*;
11 pub use self::UnsafeSource::*;
13 use crate::hir::def::{Res, DefKind};
14 use crate::hir::def_id::{DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX};
15 use crate::util::nodemap::{NodeMap, FxHashSet};
16 use crate::mir::mono::Linkage;
18 use errors::FatalError;
19 use syntax_pos::{Span, DUMMY_SP, symbol::InternedString, MultiSpan};
20 use syntax::source_map::Spanned;
21 use rustc_target::spec::abi::Abi;
22 use syntax::ast::{self, CrateSugar, Ident, Name, NodeId, AsmDialect};
23 use syntax::ast::{Attribute, Label, LitKind, StrStyle, FloatTy, IntTy, UintTy};
24 use syntax::attr::{InlineAttr, OptimizeAttr};
25 use syntax::ext::hygiene::SyntaxContext;
27 use syntax::symbol::{Symbol, kw};
28 use syntax::tokenstream::TokenStream;
29 use syntax::util::parser::ExprPrecedence;
30 use crate::ty::AdtKind;
31 use crate::ty::query::Providers;
33 use rustc_data_structures::sync::{par_for_each_in, Send, Sync};
34 use rustc_data_structures::thin_vec::ThinVec;
35 use rustc_macros::HashStable;
37 use serialize::{self, Encoder, Encodable, Decoder, Decodable};
38 use std::collections::{BTreeSet, BTreeMap};
40 use smallvec::SmallVec;
42 /// HIR doesn't commit to a concrete storage type and has its own alias for a vector.
43 /// It can be `Vec`, `P<[T]>` or potentially `Box<[T]>`, or some other container with similar
44 /// behavior. Unlike AST, HIR is mostly a static structure, so we can use an owned slice instead
45 /// of `Vec` to avoid keeping extra capacity.
46 pub type HirVec<T> = P<[T]>;
48 macro_rules! hir_vec {
49 ($elem:expr; $n:expr) => (
50 $crate::hir::HirVec::from(vec![$elem; $n])
53 $crate::hir::HirVec::from(vec![$($x),*])
61 pub mod itemlikevisit;
68 /// Uniquely identifies a node in the HIR of the current crate. It is
69 /// composed of the `owner`, which is the `DefIndex` of the directly enclosing
70 /// `hir::Item`, `hir::TraitItem`, or `hir::ImplItem` (i.e., the closest "item-like"),
71 /// and the `local_id` which is unique within the given owner.
73 /// This two-level structure makes for more stable values: One can move an item
74 /// around within the source code, or add or remove stuff before it, without
75 /// the `local_id` part of the `HirId` changing, which is a very useful property in
76 /// incremental compilation where we have to persist things through changes to
78 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)]
81 pub local_id: ItemLocalId,
85 pub fn owner_def_id(self) -> DefId {
86 DefId::local(self.owner)
89 pub fn owner_local_def_id(self) -> LocalDefId {
90 LocalDefId::from_def_id(DefId::local(self.owner))
94 impl serialize::UseSpecializedEncodable for HirId {
95 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
106 impl serialize::UseSpecializedDecodable for HirId {
107 fn default_decode<D: Decoder>(d: &mut D) -> Result<HirId, D::Error> {
108 let owner = DefIndex::decode(d)?;
109 let local_id = ItemLocalId::decode(d)?;
118 impl fmt::Display for HirId {
119 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120 write!(f, "{:?}", self)
124 // Hack to ensure that we don't try to access the private parts of `ItemLocalId` in this module
125 mod item_local_id_inner {
126 use rustc_data_structures::indexed_vec::Idx;
127 use rustc_macros::HashStable;
129 /// An `ItemLocalId` uniquely identifies something within a given "item-like";
130 /// that is, within a `hir::Item`, `hir::TraitItem`, or `hir::ImplItem`. There is no
131 /// guarantee that the numerical value of a given `ItemLocalId` corresponds to
132 /// the node's position within the owning item in any way, but there is a
133 /// guarantee that the `LocalItemId`s within an owner occupy a dense range of
134 /// integers starting at zero, so a mapping that maps all or most nodes within
135 /// an "item-like" to something else can be implemented by a `Vec` instead of a
136 /// tree or hash map.
137 pub struct ItemLocalId {
143 pub use self::item_local_id_inner::ItemLocalId;
145 /// The `HirId` corresponding to `CRATE_NODE_ID` and `CRATE_DEF_INDEX`.
146 pub const CRATE_HIR_ID: HirId = HirId {
147 owner: CRATE_DEF_INDEX,
148 local_id: ItemLocalId::from_u32_const(0)
151 pub const DUMMY_HIR_ID: HirId = HirId {
152 owner: CRATE_DEF_INDEX,
153 local_id: DUMMY_ITEM_LOCAL_ID,
156 pub const DUMMY_ITEM_LOCAL_ID: ItemLocalId = ItemLocalId::MAX;
158 #[derive(Clone, RustcEncodable, RustcDecodable, Copy, HashStable)]
159 pub struct Lifetime {
163 /// Either "`'a`", referring to a named lifetime definition,
164 /// or "``" (i.e., `kw::Invalid`), for elision placeholders.
166 /// HIR lowering inserts these placeholders in type paths that
167 /// refer to type definitions needing lifetime parameters,
168 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
169 pub name: LifetimeName,
172 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy, HashStable)]
174 /// Some user-given name like `T` or `'x`.
177 /// Synthetic name generated when user elided a lifetime in an impl header.
179 /// E.g., the lifetimes in cases like these:
181 /// impl Foo for &u32
182 /// impl Foo<'_> for u32
184 /// in that case, we rewrite to
186 /// impl<'f> Foo for &'f u32
187 /// impl<'f> Foo<'f> for u32
189 /// where `'f` is something like `Fresh(0)`. The indices are
190 /// unique per impl, but not necessarily continuous.
193 /// Indicates an illegal name was given and an error has been
194 /// repored (so we should squelch other derived errors). Occurs
195 /// when, e.g., `'_` is used in the wrong place.
200 pub fn ident(&self) -> Ident {
202 ParamName::Plain(ident) => ident,
203 ParamName::Fresh(_) |
204 ParamName::Error => Ident::with_empty_ctxt(kw::UnderscoreLifetime),
208 pub fn modern(&self) -> ParamName {
210 ParamName::Plain(ident) => ParamName::Plain(ident.modern()),
211 param_name => param_name,
216 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy, HashStable)]
217 pub enum LifetimeName {
218 /// User-given names or fresh (synthetic) names.
221 /// User wrote nothing (e.g., the lifetime in `&u32`).
224 /// Indicates an error during lowering (usually `'_` in wrong place)
225 /// that was already reported.
228 /// User wrote specifies `'_`.
231 /// User wrote `'static`.
236 pub fn ident(&self) -> Ident {
238 LifetimeName::Implicit | LifetimeName::Error => Ident::invalid(),
239 LifetimeName::Underscore => Ident::with_empty_ctxt(kw::UnderscoreLifetime),
240 LifetimeName::Static => Ident::with_empty_ctxt(kw::StaticLifetime),
241 LifetimeName::Param(param_name) => param_name.ident(),
245 pub fn is_elided(&self) -> bool {
247 LifetimeName::Implicit | LifetimeName::Underscore => true,
249 // It might seem surprising that `Fresh(_)` counts as
250 // *not* elided -- but this is because, as far as the code
251 // in the compiler is concerned -- `Fresh(_)` variants act
252 // equivalently to "some fresh name". They correspond to
253 // early-bound regions on an impl, in other words.
254 LifetimeName::Error | LifetimeName::Param(_) | LifetimeName::Static => false,
258 fn is_static(&self) -> bool {
259 self == &LifetimeName::Static
262 pub fn modern(&self) -> LifetimeName {
264 LifetimeName::Param(param_name) => LifetimeName::Param(param_name.modern()),
265 lifetime_name => lifetime_name,
270 impl fmt::Display for Lifetime {
271 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
272 self.name.ident().fmt(f)
276 impl fmt::Debug for Lifetime {
277 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
281 print::to_string(print::NO_ANN, |s| s.print_lifetime(self)))
286 pub fn is_elided(&self) -> bool {
287 self.name.is_elided()
290 pub fn is_static(&self) -> bool {
291 self.name.is_static()
295 /// A `Path` is essentially Rust's notion of a name; for instance,
296 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
297 /// along with a bunch of supporting information.
298 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
301 /// The resolution for the path.
303 /// The segments in the path: the things separated by `::`.
304 pub segments: HirVec<PathSegment>,
308 pub fn is_global(&self) -> bool {
309 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
313 impl fmt::Debug for Path {
314 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
315 write!(f, "path({})", self)
319 impl fmt::Display for Path {
320 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
321 write!(f, "{}", print::to_string(print::NO_ANN, |s| s.print_path(self, false)))
325 /// A segment of a path: an identifier, an optional lifetime, and a set of
327 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
328 pub struct PathSegment {
329 /// The identifier portion of this path segment.
330 #[stable_hasher(project(name))]
332 // `id` and `res` are optional. We currently only use these in save-analysis,
333 // any path segments without these will not have save-analysis info and
334 // therefore will not have 'jump to def' in IDEs, but otherwise will not be
335 // affected. (In general, we don't bother to get the defs for synthesized
336 // segments, only for segments which have come from the AST).
337 pub hir_id: Option<HirId>,
338 pub res: Option<Res>,
340 /// Type/lifetime parameters attached to this path. They come in
341 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
342 /// this is more than just simple syntactic sugar; the use of
343 /// parens affects the region binding rules, so we preserve the
345 pub args: Option<P<GenericArgs>>,
347 /// Whether to infer remaining type parameters, if any.
348 /// This only applies to expression and pattern paths, and
349 /// out of those only the segments with no type parameters
350 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
351 pub infer_types: bool,
355 /// Converts an identifier to the corresponding segment.
356 pub fn from_ident(ident: Ident) -> PathSegment {
368 hir_id: Option<HirId>,
378 args: if args.is_empty() {
386 // FIXME: hack required because you can't create a static
387 // `GenericArgs`, so you can't just return a `&GenericArgs`.
388 pub fn with_generic_args<F, R>(&self, f: F) -> R
389 where F: FnOnce(&GenericArgs) -> R
391 let dummy = GenericArgs::none();
392 f(if let Some(ref args) = self.args {
400 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
401 pub struct ConstArg {
402 pub value: AnonConst,
406 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
407 pub enum GenericArg {
414 pub fn span(&self) -> Span {
416 GenericArg::Lifetime(l) => l.span,
417 GenericArg::Type(t) => t.span,
418 GenericArg::Const(c) => c.span,
422 pub fn id(&self) -> HirId {
424 GenericArg::Lifetime(l) => l.hir_id,
425 GenericArg::Type(t) => t.hir_id,
426 GenericArg::Const(c) => c.value.hir_id,
430 pub fn is_const(&self) -> bool {
432 GenericArg::Const(_) => true,
438 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
439 pub struct GenericArgs {
440 /// The generic arguments for this path segment.
441 pub args: HirVec<GenericArg>,
442 /// Bindings (equality constraints) on associated types, if present.
443 /// E.g., `Foo<A = Bar>`.
444 pub bindings: HirVec<TypeBinding>,
445 /// Were arguments written in parenthesized form `Fn(T) -> U`?
446 /// This is required mostly for pretty-printing and diagnostics,
447 /// but also for changing lifetime elision rules to be "function-like".
448 pub parenthesized: bool,
452 pub fn none() -> Self {
455 bindings: HirVec::new(),
456 parenthesized: false,
460 pub fn is_empty(&self) -> bool {
461 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
464 pub fn inputs(&self) -> &[Ty] {
465 if self.parenthesized {
466 for arg in &self.args {
468 GenericArg::Lifetime(_) => {}
469 GenericArg::Type(ref ty) => {
470 if let TyKind::Tup(ref tys) = ty.node {
475 GenericArg::Const(_) => {}
479 bug!("GenericArgs::inputs: not a `Fn(T) -> U`");
482 pub fn own_counts(&self) -> GenericParamCount {
483 // We could cache this as a property of `GenericParamCount`, but
484 // the aim is to refactor this away entirely eventually and the
485 // presence of this method will be a constant reminder.
486 let mut own_counts: GenericParamCount = Default::default();
488 for arg in &self.args {
490 GenericArg::Lifetime(_) => own_counts.lifetimes += 1,
491 GenericArg::Type(_) => own_counts.types += 1,
492 GenericArg::Const(_) => own_counts.consts += 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, HashStable)]
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, HashStable)]
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, HashStable)]
530 pub enum LifetimeParamKind {
531 // Indicates that the lifetime definition was explicitly declared (e.g., in
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 (e.g., in
537 // `fn foo(x: &'a u8) -> &'a u8 { x }`).
540 // Indication that the lifetime was elided (e.g., in both cases in
541 // `fn foo(x: &u8) -> &'_ u8 { x }`).
544 // Indication that the lifetime name was somehow in error.
548 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
549 pub enum GenericParamKind {
550 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
552 kind: LifetimeParamKind,
555 default: Option<P<Ty>>,
556 synthetic: Option<SyntheticTyParamKind>,
563 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
564 pub struct GenericParam {
567 pub attrs: HirVec<Attribute>,
568 pub bounds: GenericBounds,
570 pub pure_wrt_drop: bool,
571 pub kind: GenericParamKind,
575 pub struct GenericParamCount {
576 pub lifetimes: usize,
581 /// Represents lifetimes and type parameters attached to a declaration
582 /// of a function, enum, trait, etc.
583 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
584 pub struct Generics {
585 pub params: HirVec<GenericParam>,
586 pub where_clause: WhereClause,
591 pub fn empty() -> Generics {
593 params: HirVec::new(),
594 where_clause: WhereClause {
595 hir_id: DUMMY_HIR_ID,
596 predicates: HirVec::new(),
602 pub fn own_counts(&self) -> GenericParamCount {
603 // We could cache this as a property of `GenericParamCount`, but
604 // the aim is to refactor this away entirely eventually and the
605 // presence of this method will be a constant reminder.
606 let mut own_counts: GenericParamCount = Default::default();
608 for param in &self.params {
610 GenericParamKind::Lifetime { .. } => own_counts.lifetimes += 1,
611 GenericParamKind::Type { .. } => own_counts.types += 1,
612 GenericParamKind::Const { .. } => own_counts.consts += 1,
619 pub fn get_named(&self, name: InternedString) -> Option<&GenericParam> {
620 for param in &self.params {
621 if name == param.name.ident().as_interned_str() {
628 pub fn spans(&self) -> MultiSpan {
629 if self.params.is_empty() {
632 self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
637 /// Synthetic type parameters are converted to another form during lowering; this allows
638 /// us to track the original form they had, and is useful for error messages.
639 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
640 pub enum SyntheticTyParamKind {
644 /// A where-clause in a definition.
645 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
646 pub struct WhereClause {
648 pub predicates: HirVec<WherePredicate>,
652 pub fn span(&self) -> Option<Span> {
653 self.predicates.iter().map(|predicate| predicate.span())
654 .fold(None, |acc, i| match (acc, i) {
655 (None, i) => Some(i),
663 /// A single predicate in a where-clause.
664 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
665 pub enum WherePredicate {
666 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
667 BoundPredicate(WhereBoundPredicate),
668 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
669 RegionPredicate(WhereRegionPredicate),
670 /// An equality predicate (unsupported).
671 EqPredicate(WhereEqPredicate),
674 impl WherePredicate {
675 pub fn span(&self) -> Span {
677 &WherePredicate::BoundPredicate(ref p) => p.span,
678 &WherePredicate::RegionPredicate(ref p) => p.span,
679 &WherePredicate::EqPredicate(ref p) => p.span,
684 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
685 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
686 pub struct WhereBoundPredicate {
688 /// Any generics from a `for` binding.
689 pub bound_generic_params: HirVec<GenericParam>,
690 /// The type being bounded.
691 pub bounded_ty: P<Ty>,
692 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
693 pub bounds: GenericBounds,
696 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
697 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
698 pub struct WhereRegionPredicate {
700 pub lifetime: Lifetime,
701 pub bounds: GenericBounds,
704 /// An equality predicate (e.g., `T = int`); currently unsupported.
705 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
706 pub struct WhereEqPredicate {
713 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
714 pub struct ModuleItems {
715 // Use BTreeSets here so items are in the same order as in the
716 // list of all items in Crate
717 pub items: BTreeSet<HirId>,
718 pub trait_items: BTreeSet<TraitItemId>,
719 pub impl_items: BTreeSet<ImplItemId>,
722 /// The top-level data structure that stores the entire contents of
723 /// the crate currently being compiled.
725 /// For more details, see the [rustc guide].
727 /// [rustc guide]: https://rust-lang.github.io/rustc-guide/hir.html
728 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
731 pub attrs: HirVec<Attribute>,
733 pub exported_macros: HirVec<MacroDef>,
735 // N.B., we use a BTreeMap here so that `visit_all_items` iterates
736 // over the ids in increasing order. In principle it should not
737 // matter what order we visit things in, but in *practice* it
738 // does, because it can affect the order in which errors are
739 // detected, which in turn can make compile-fail tests yield
740 // slightly different results.
741 pub items: BTreeMap<HirId, Item>,
743 pub trait_items: BTreeMap<TraitItemId, TraitItem>,
744 pub impl_items: BTreeMap<ImplItemId, ImplItem>,
745 pub bodies: BTreeMap<BodyId, Body>,
746 pub trait_impls: BTreeMap<DefId, Vec<HirId>>,
748 /// A list of the body ids written out in the order in which they
749 /// appear in the crate. If you're going to process all the bodies
750 /// in the crate, you should iterate over this list rather than the keys
752 pub body_ids: Vec<BodyId>,
754 /// A list of modules written out in the order in which they
755 /// appear in the crate. This includes the main crate module.
756 pub modules: BTreeMap<NodeId, ModuleItems>,
760 pub fn item(&self, id: HirId) -> &Item {
764 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem {
765 &self.trait_items[&id]
768 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem {
769 &self.impl_items[&id]
772 /// Visits all items in the crate in some deterministic (but
773 /// unspecified) order. If you just need to process every item,
774 /// but don't care about nesting, this method is the best choice.
776 /// If you do care about nesting -- usually because your algorithm
777 /// follows lexical scoping rules -- then you want a different
778 /// approach. You should override `visit_nested_item` in your
779 /// visitor and then call `intravisit::walk_crate` instead.
780 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
781 where V: itemlikevisit::ItemLikeVisitor<'hir>
783 for (_, item) in &self.items {
784 visitor.visit_item(item);
787 for (_, trait_item) in &self.trait_items {
788 visitor.visit_trait_item(trait_item);
791 for (_, impl_item) in &self.impl_items {
792 visitor.visit_impl_item(impl_item);
796 /// A parallel version of `visit_all_item_likes`.
797 pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
798 where V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send
801 par_for_each_in(&self.items, |(_, item)| {
802 visitor.visit_item(item);
805 par_for_each_in(&self.trait_items, |(_, trait_item)| {
806 visitor.visit_trait_item(trait_item);
809 par_for_each_in(&self.impl_items, |(_, impl_item)| {
810 visitor.visit_impl_item(impl_item);
815 pub fn body(&self, id: BodyId) -> &Body {
820 /// A macro definition, in this crate or imported from another.
822 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
823 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
824 pub struct MacroDef {
827 pub attrs: HirVec<Attribute>,
830 pub body: TokenStream,
834 /// A block of statements `{ .. }`, which may have a label (in this case the
835 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
836 /// the `rules` being anything but `DefaultBlock`.
837 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
839 /// Statements in a block.
840 pub stmts: HirVec<Stmt>,
841 /// An expression at the end of the block
842 /// without a semicolon, if any.
843 pub expr: Option<P<Expr>>,
844 #[stable_hasher(ignore)]
846 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
847 pub rules: BlockCheckMode,
849 /// If true, then there may exist `break 'a` values that aim to
850 /// break out of this block early.
851 /// Used by `'label: {}` blocks and by `catch` statements.
852 pub targeted_by_break: bool,
855 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
857 #[stable_hasher(ignore)]
863 impl fmt::Debug for Pat {
864 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
865 write!(f, "pat({}: {})", self.hir_id,
866 print::to_string(print::NO_ANN, |s| s.print_pat(self)))
871 // FIXME(#19596) this is a workaround, but there should be a better way
872 fn walk_<G>(&self, it: &mut G) -> bool
873 where G: FnMut(&Pat) -> bool
880 PatKind::Binding(.., Some(ref p)) => p.walk_(it),
881 PatKind::Struct(_, ref fields, _) => {
882 fields.iter().all(|field| field.node.pat.walk_(it))
884 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
885 s.iter().all(|p| p.walk_(it))
887 PatKind::Box(ref s) | PatKind::Ref(ref s, _) => {
890 PatKind::Slice(ref before, ref slice, ref after) => {
894 .all(|p| p.walk_(it))
899 PatKind::Binding(..) |
900 PatKind::Path(_) => {
906 pub fn walk<F>(&self, mut it: F) -> bool
907 where F: FnMut(&Pat) -> bool
913 /// A single field in a struct pattern.
915 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
916 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
917 /// except `is_shorthand` is true.
918 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
919 pub struct FieldPat {
920 #[stable_hasher(ignore)]
922 /// The identifier for the field.
923 #[stable_hasher(project(name))]
925 /// The pattern the field is destructured to.
927 pub is_shorthand: bool,
930 /// Explicit binding annotations given in the HIR for a binding. Note
931 /// that this is not the final binding *mode* that we infer after type
933 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable)]
934 pub enum BindingAnnotation {
935 /// No binding annotation given: this means that the final binding mode
936 /// will depend on whether we have skipped through a `&` reference
937 /// when matching. For example, the `x` in `Some(x)` will have binding
938 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
939 /// ultimately be inferred to be by-reference.
941 /// Note that implicit reference skipping is not implemented yet (#42640).
944 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
947 /// Annotated as `ref`, like `ref x`
950 /// Annotated as `ref mut x`.
954 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
960 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
962 /// Represents a wildcard pattern (i.e., `_`).
965 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
966 /// The `HirId` is the canonical ID for the variable being bound,
967 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
968 /// which is the pattern ID of the first `x`.
969 Binding(BindingAnnotation, HirId, Ident, Option<P<Pat>>),
971 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
972 /// The `bool` is `true` in the presence of a `..`.
973 Struct(QPath, HirVec<Spanned<FieldPat>>, bool),
975 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
976 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
977 /// `0 <= position <= subpats.len()`
978 TupleStruct(QPath, HirVec<P<Pat>>, Option<usize>),
980 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
983 /// A tuple pattern (e.g., `(a, b)`).
984 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
985 /// `0 <= position <= subpats.len()`
986 Tuple(HirVec<P<Pat>>, Option<usize>),
991 /// A reference pattern (e.g., `&mut (a, b)`).
992 Ref(P<Pat>, Mutability),
997 /// A range pattern (e.g., `1...2` or `1..2`).
998 Range(P<Expr>, P<Expr>, RangeEnd),
1000 /// `[a, b, ..i, y, z]` is represented as:
1001 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`.
1002 Slice(HirVec<P<Pat>>, Option<P<Pat>>, HirVec<P<Pat>>),
1005 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, HashStable,
1006 RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1007 pub enum Mutability {
1013 /// Returns `MutMutable` only if both arguments are mutable.
1014 pub fn and(self, other: Self) -> Self {
1016 MutMutable => other,
1017 MutImmutable => MutImmutable,
1022 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, Hash, HashStable)]
1023 pub enum BinOpKind {
1024 /// The `+` operator (addition).
1026 /// The `-` operator (subtraction).
1028 /// The `*` operator (multiplication).
1030 /// The `/` operator (division).
1032 /// The `%` operator (modulus).
1034 /// The `&&` operator (logical and).
1036 /// The `||` operator (logical or).
1038 /// The `^` operator (bitwise xor).
1040 /// The `&` operator (bitwise and).
1042 /// The `|` operator (bitwise or).
1044 /// The `<<` operator (shift left).
1046 /// The `>>` operator (shift right).
1048 /// The `==` operator (equality).
1050 /// The `<` operator (less than).
1052 /// The `<=` operator (less than or equal to).
1054 /// The `!=` operator (not equal to).
1056 /// The `>=` operator (greater than or equal to).
1058 /// The `>` operator (greater than).
1063 pub fn as_str(self) -> &'static str {
1065 BinOpKind::Add => "+",
1066 BinOpKind::Sub => "-",
1067 BinOpKind::Mul => "*",
1068 BinOpKind::Div => "/",
1069 BinOpKind::Rem => "%",
1070 BinOpKind::And => "&&",
1071 BinOpKind::Or => "||",
1072 BinOpKind::BitXor => "^",
1073 BinOpKind::BitAnd => "&",
1074 BinOpKind::BitOr => "|",
1075 BinOpKind::Shl => "<<",
1076 BinOpKind::Shr => ">>",
1077 BinOpKind::Eq => "==",
1078 BinOpKind::Lt => "<",
1079 BinOpKind::Le => "<=",
1080 BinOpKind::Ne => "!=",
1081 BinOpKind::Ge => ">=",
1082 BinOpKind::Gt => ">",
1086 pub fn is_lazy(self) -> bool {
1088 BinOpKind::And | BinOpKind::Or => true,
1093 pub fn is_shift(self) -> bool {
1095 BinOpKind::Shl | BinOpKind::Shr => true,
1100 pub fn is_comparison(self) -> bool {
1107 BinOpKind::Ge => true,
1119 BinOpKind::Shr => false,
1123 /// Returns `true` if the binary operator takes its arguments by value.
1124 pub fn is_by_value(self) -> bool {
1125 !self.is_comparison()
1129 impl Into<ast::BinOpKind> for BinOpKind {
1130 fn into(self) -> ast::BinOpKind {
1132 BinOpKind::Add => ast::BinOpKind::Add,
1133 BinOpKind::Sub => ast::BinOpKind::Sub,
1134 BinOpKind::Mul => ast::BinOpKind::Mul,
1135 BinOpKind::Div => ast::BinOpKind::Div,
1136 BinOpKind::Rem => ast::BinOpKind::Rem,
1137 BinOpKind::And => ast::BinOpKind::And,
1138 BinOpKind::Or => ast::BinOpKind::Or,
1139 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1140 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1141 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1142 BinOpKind::Shl => ast::BinOpKind::Shl,
1143 BinOpKind::Shr => ast::BinOpKind::Shr,
1144 BinOpKind::Eq => ast::BinOpKind::Eq,
1145 BinOpKind::Lt => ast::BinOpKind::Lt,
1146 BinOpKind::Le => ast::BinOpKind::Le,
1147 BinOpKind::Ne => ast::BinOpKind::Ne,
1148 BinOpKind::Ge => ast::BinOpKind::Ge,
1149 BinOpKind::Gt => ast::BinOpKind::Gt,
1154 pub type BinOp = Spanned<BinOpKind>;
1156 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, Hash, HashStable)]
1158 /// The `*` operator (deferencing).
1160 /// The `!` operator (logical negation).
1162 /// The `-` operator (negation).
1167 pub fn as_str(self) -> &'static str {
1175 /// Returns `true` if the unary operator takes its argument by value.
1176 pub fn is_by_value(self) -> bool {
1178 UnNeg | UnNot => true,
1185 #[derive(Clone, RustcEncodable, RustcDecodable)]
1192 impl fmt::Debug for Stmt {
1193 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1194 write!(f, "stmt({}: {})", self.hir_id,
1195 print::to_string(print::NO_ANN, |s| s.print_stmt(self)))
1199 /// The contents of a statement.
1200 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
1202 /// A local (`let`) binding.
1205 /// An item binding.
1208 /// An expression without a trailing semi-colon (must have unit type).
1211 /// An expression with a trailing semi-colon (may have any type).
1216 pub fn attrs(&self) -> &[Attribute] {
1218 StmtKind::Local(ref l) => &l.attrs,
1219 StmtKind::Item(_) => &[],
1220 StmtKind::Expr(ref e) |
1221 StmtKind::Semi(ref e) => &e.attrs,
1226 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1227 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1230 /// Type annotation, if any (otherwise the type will be inferred).
1231 pub ty: Option<P<Ty>>,
1232 /// Initializer expression to set the value, if any.
1233 pub init: Option<P<Expr>>,
1236 pub attrs: ThinVec<Attribute>,
1237 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1238 /// desugaring. Otherwise will be `Normal`.
1239 pub source: LocalSource,
1242 /// Represents a single arm of a `match` expression, e.g.
1243 /// `<pats> (if <guard>) => <body>`.
1244 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1246 #[stable_hasher(ignore)]
1249 pub attrs: HirVec<Attribute>,
1250 /// Multiple patterns can be combined with `|`
1251 pub pats: HirVec<P<Pat>>,
1252 /// Optional guard clause.
1253 pub guard: Option<Guard>,
1254 /// The expression the arm evaluates to if this arm matches.
1258 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1263 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1265 #[stable_hasher(ignore)]
1270 pub is_shorthand: bool,
1273 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable)]
1274 pub enum BlockCheckMode {
1276 UnsafeBlock(UnsafeSource),
1277 PushUnsafeBlock(UnsafeSource),
1278 PopUnsafeBlock(UnsafeSource),
1281 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable)]
1282 pub enum UnsafeSource {
1287 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1292 /// The body of a function, closure, or constant value. In the case of
1293 /// a function, the body contains not only the function body itself
1294 /// (which is an expression), but also the argument patterns, since
1295 /// those are something that the caller doesn't really care about.
1300 /// fn foo((x, y): (u32, u32)) -> u32 {
1305 /// Here, the `Body` associated with `foo()` would contain:
1307 /// - an `arguments` array containing the `(x, y)` pattern
1308 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1309 /// - `is_generator` would be false
1311 /// All bodies have an **owner**, which can be accessed via the HIR
1312 /// map using `body_owner_def_id()`.
1313 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1315 pub arguments: HirVec<Arg>,
1317 pub is_generator: bool,
1321 pub fn id(&self) -> BodyId {
1323 hir_id: self.value.hir_id,
1328 #[derive(Copy, Clone, Debug)]
1329 pub enum BodyOwnerKind {
1330 /// Functions and methods.
1336 /// Constants and associated constants.
1339 /// Initializer of a `static` item.
1343 impl BodyOwnerKind {
1344 pub fn is_fn_or_closure(self) -> bool {
1346 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1347 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1353 pub type Lit = Spanned<LitKind>;
1355 /// A constant (expression) that's not an item or associated item,
1356 /// but needs its own `DefId` for type-checking, const-eval, etc.
1357 /// These are usually found nested inside types (e.g., array lengths)
1358 /// or expressions (e.g., repeat counts), and also used to define
1359 /// explicit discriminant values for enum variants.
1360 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1361 pub struct AnonConst {
1367 #[derive(Clone, RustcEncodable, RustcDecodable)]
1371 pub attrs: ThinVec<Attribute>,
1375 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1376 #[cfg(target_arch = "x86_64")]
1377 static_assert_size!(Expr, 72);
1380 pub fn precedence(&self) -> ExprPrecedence {
1382 ExprKind::Box(_) => ExprPrecedence::Box,
1383 ExprKind::Array(_) => ExprPrecedence::Array,
1384 ExprKind::Call(..) => ExprPrecedence::Call,
1385 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1386 ExprKind::Tup(_) => ExprPrecedence::Tup,
1387 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1388 ExprKind::Unary(..) => ExprPrecedence::Unary,
1389 ExprKind::Lit(_) => ExprPrecedence::Lit,
1390 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1391 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1392 ExprKind::While(..) => ExprPrecedence::While,
1393 ExprKind::Loop(..) => ExprPrecedence::Loop,
1394 ExprKind::Match(..) => ExprPrecedence::Match,
1395 ExprKind::Closure(..) => ExprPrecedence::Closure,
1396 ExprKind::Block(..) => ExprPrecedence::Block,
1397 ExprKind::Assign(..) => ExprPrecedence::Assign,
1398 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1399 ExprKind::Field(..) => ExprPrecedence::Field,
1400 ExprKind::Index(..) => ExprPrecedence::Index,
1401 ExprKind::Path(..) => ExprPrecedence::Path,
1402 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1403 ExprKind::Break(..) => ExprPrecedence::Break,
1404 ExprKind::Continue(..) => ExprPrecedence::Continue,
1405 ExprKind::Ret(..) => ExprPrecedence::Ret,
1406 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1407 ExprKind::Struct(..) => ExprPrecedence::Struct,
1408 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1409 ExprKind::Yield(..) => ExprPrecedence::Yield,
1410 ExprKind::Err => ExprPrecedence::Err,
1414 pub fn is_place_expr(&self) -> bool {
1416 ExprKind::Path(QPath::Resolved(_, ref path)) => {
1419 | Res::Def(DefKind::Static, _)
1425 ExprKind::Type(ref e, _) => {
1429 ExprKind::Unary(UnDeref, _) |
1430 ExprKind::Field(..) |
1431 ExprKind::Index(..) => {
1435 // Partially qualified paths in expressions can only legally
1436 // refer to associated items which are always rvalues.
1437 ExprKind::Path(QPath::TypeRelative(..)) |
1439 ExprKind::Call(..) |
1440 ExprKind::MethodCall(..) |
1441 ExprKind::Struct(..) |
1443 ExprKind::Match(..) |
1444 ExprKind::Closure(..) |
1445 ExprKind::Block(..) |
1446 ExprKind::Repeat(..) |
1447 ExprKind::Array(..) |
1448 ExprKind::Break(..) |
1449 ExprKind::Continue(..) |
1451 ExprKind::While(..) |
1452 ExprKind::Loop(..) |
1453 ExprKind::Assign(..) |
1454 ExprKind::InlineAsm(..) |
1455 ExprKind::AssignOp(..) |
1457 ExprKind::Unary(..) |
1459 ExprKind::AddrOf(..) |
1460 ExprKind::Binary(..) |
1461 ExprKind::Yield(..) |
1462 ExprKind::Cast(..) |
1463 ExprKind::DropTemps(..) |
1471 impl fmt::Debug for Expr {
1472 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1473 write!(f, "expr({}: {})", self.hir_id,
1474 print::to_string(print::NO_ANN, |s| s.print_expr(self)))
1478 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1480 /// A `box x` expression.
1482 /// An array (e.g., `[a, b, c, d]`).
1483 Array(HirVec<Expr>),
1484 /// A function call.
1486 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1487 /// and the second field is the list of arguments.
1488 /// This also represents calling the constructor of
1489 /// tuple-like ADTs such as tuple structs and enum variants.
1490 Call(P<Expr>, HirVec<Expr>),
1491 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1493 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1494 /// (within the angle brackets).
1495 /// The first element of the vector of `Expr`s is the expression that evaluates
1496 /// to the object on which the method is being called on (the receiver),
1497 /// and the remaining elements are the rest of the arguments.
1498 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1499 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1500 MethodCall(P<PathSegment>, Span, HirVec<Expr>),
1501 /// A tuple (e.g., `(a, b, c ,d)`).
1503 /// A binary operation (e.g., `a + b`, `a * b`).
1504 Binary(BinOp, P<Expr>, P<Expr>),
1505 /// A unary operation (e.g., `!x`, `*x`).
1506 Unary(UnOp, P<Expr>),
1507 /// A literal (e.g., `1`, `"foo"`).
1509 /// A cast (e.g., `foo as f64`).
1510 Cast(P<Expr>, P<Ty>),
1511 /// A type reference (e.g., `Foo`).
1512 Type(P<Expr>, P<Ty>),
1513 /// Wraps the expression in a terminating scope.
1514 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1516 /// This construct only exists to tweak the drop order in HIR lowering.
1517 /// An example of that is the desugaring of `for` loops.
1519 /// A while loop, with an optional label
1521 /// I.e., `'label: while expr { <block> }`.
1522 While(P<Expr>, P<Block>, Option<Label>),
1523 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1525 /// I.e., `'label: loop { <block> }`.
1526 Loop(P<Block>, Option<Label>, LoopSource),
1527 /// A `match` block, with a source that indicates whether or not it is
1528 /// the result of a desugaring, and if so, which kind.
1529 Match(P<Expr>, HirVec<Arm>, MatchSource),
1530 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1532 /// The final span is the span of the argument block `|...|`.
1534 /// This may also be a generator literal, indicated by the final boolean,
1535 /// in that case there is an `GeneratorClause`.
1536 Closure(CaptureClause, P<FnDecl>, BodyId, Span, Option<GeneratorMovability>),
1537 /// A block (e.g., `'label: { ... }`).
1538 Block(P<Block>, Option<Label>),
1540 /// An assignment (e.g., `a = foo()`).
1541 Assign(P<Expr>, P<Expr>),
1542 /// An assignment with an operator.
1545 AssignOp(BinOp, P<Expr>, P<Expr>),
1546 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1547 Field(P<Expr>, Ident),
1548 /// An indexing operation (`foo[2]`).
1549 Index(P<Expr>, P<Expr>),
1551 /// Path to a definition, possibly containing lifetime or type parameters.
1554 /// A referencing operation (i.e., `&a` or `&mut a`).
1555 AddrOf(Mutability, P<Expr>),
1556 /// A `break`, with an optional label to break.
1557 Break(Destination, Option<P<Expr>>),
1558 /// A `continue`, with an optional label.
1559 Continue(Destination),
1560 /// A `return`, with an optional value to be returned.
1561 Ret(Option<P<Expr>>),
1563 /// Inline assembly (from `asm!`), with its outputs and inputs.
1564 InlineAsm(P<InlineAsm>, HirVec<Expr>, HirVec<Expr>),
1566 /// A struct or struct-like variant literal expression.
1568 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1569 /// where `base` is the `Option<Expr>`.
1570 Struct(P<QPath>, HirVec<Field>, Option<P<Expr>>),
1572 /// An array literal constructed from one repeated element.
1574 /// E.g., `[1; 5]`. The first expression is the element
1575 /// to be repeated; the second is the number of times to repeat it.
1576 Repeat(P<Expr>, AnonConst),
1578 /// A suspension point for generators (i.e., `yield <expr>`).
1581 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1585 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1586 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1588 /// Path to a definition, optionally "fully-qualified" with a `Self`
1589 /// type, if the path points to an associated item in a trait.
1591 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1592 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1593 /// even though they both have the same two-segment `Clone::clone` `Path`.
1594 Resolved(Option<P<Ty>>, P<Path>),
1596 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1597 /// Will be resolved by type-checking to an associated item.
1599 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1600 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1601 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1602 TypeRelative(P<Ty>, P<PathSegment>)
1605 /// Hints at the original code for a let statement.
1606 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, HashStable)]
1607 pub enum LocalSource {
1608 /// A `match _ { .. }`.
1610 /// A desugared `for _ in _ { .. }` loop.
1612 /// When lowering async functions, we create locals within the `async move` so that
1613 /// all arguments are dropped after the future is polled.
1615 /// ```ignore (pseudo-Rust)
1616 /// async fn foo(<pattern> @ x: Type) {
1618 /// let <pattern> = x;
1623 /// A desugared `<expr>.await`.
1627 /// Hints at the original code for a `match _ { .. }`.
1628 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy, HashStable)]
1629 pub enum MatchSource {
1630 /// A `match _ { .. }`.
1632 /// An `if _ { .. }` (optionally with `else { .. }`).
1634 contains_else_clause: bool,
1636 /// An `if let _ = _ { .. }` (optionally with `else { .. }`).
1638 contains_else_clause: bool,
1640 /// A `while let _ = _ { .. }` (which was desugared to a
1641 /// `loop { match _ { .. } }`).
1643 /// A desugared `for _ in _ { .. }` loop.
1645 /// A desugared `?` operator.
1647 /// A desugared `<expr>.await`.
1651 /// The loop type that yielded an `ExprKind::Loop`.
1652 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable)]
1653 pub enum LoopSource {
1654 /// A `loop { .. }` loop.
1656 /// A `while let _ = _ { .. }` loop.
1658 /// A `for _ in _ { .. }` loop.
1662 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, HashStable)]
1663 pub enum LoopIdError {
1665 UnlabeledCfInWhileCondition,
1669 impl fmt::Display for LoopIdError {
1670 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1671 fmt::Display::fmt(match *self {
1672 LoopIdError::OutsideLoopScope => "not inside loop scope",
1673 LoopIdError::UnlabeledCfInWhileCondition =>
1674 "unlabeled control flow (break or continue) in while condition",
1675 LoopIdError::UnresolvedLabel => "label not found",
1680 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, HashStable)]
1681 pub struct Destination {
1682 // This is `Some(_)` iff there is an explicit user-specified `label
1683 pub label: Option<Label>,
1685 // These errors are caught and then reported during the diagnostics pass in
1686 // librustc_passes/loops.rs
1687 pub target_id: Result<HirId, LoopIdError>,
1690 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, HashStable,
1691 RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1692 pub enum GeneratorMovability {
1697 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, HashStable)]
1698 pub enum CaptureClause {
1703 // N.B., if you change this, you'll probably want to change the corresponding
1704 // type structure in middle/ty.rs as well.
1705 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1708 pub mutbl: Mutability,
1711 /// Represents a method's signature in a trait declaration or implementation.
1712 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1713 pub struct MethodSig {
1714 pub header: FnHeader,
1715 pub decl: P<FnDecl>,
1718 // The bodies for items are stored "out of line", in a separate
1719 // hashmap in the `Crate`. Here we just record the node-id of the item
1720 // so it can fetched later.
1721 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1722 pub struct TraitItemId {
1726 /// Represents an item declaration within a trait declaration,
1727 /// possibly including a default implementation. A trait item is
1728 /// either required (meaning it doesn't have an implementation, just a
1729 /// signature) or provided (meaning it has a default implementation).
1730 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1731 pub struct TraitItem {
1734 pub attrs: HirVec<Attribute>,
1735 pub generics: Generics,
1736 pub node: TraitItemKind,
1740 /// Represents a trait method's body (or just argument names).
1741 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1742 pub enum TraitMethod {
1743 /// No default body in the trait, just a signature.
1744 Required(HirVec<Ident>),
1746 /// Both signature and body are provided in the trait.
1750 /// Represents a trait method or associated constant or type
1751 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1752 pub enum TraitItemKind {
1753 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
1754 Const(P<Ty>, Option<BodyId>),
1755 /// A method with an optional body.
1756 Method(MethodSig, TraitMethod),
1757 /// An associated type with (possibly empty) bounds and optional concrete
1759 Type(GenericBounds, Option<P<Ty>>),
1762 // The bodies for items are stored "out of line", in a separate
1763 // hashmap in the `Crate`. Here we just record the node-id of the item
1764 // so it can fetched later.
1765 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1766 pub struct ImplItemId {
1770 /// Represents anything within an `impl` block
1771 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1772 pub struct ImplItem {
1775 pub vis: Visibility,
1776 pub defaultness: Defaultness,
1777 pub attrs: HirVec<Attribute>,
1778 pub generics: Generics,
1779 pub node: ImplItemKind,
1783 /// Represents various kinds of content within an `impl`.
1784 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1785 pub enum ImplItemKind {
1786 /// An associated constant of the given type, set to the constant result
1787 /// of the expression
1788 Const(P<Ty>, BodyId),
1789 /// A method implementation with the given signature and body
1790 Method(MethodSig, BodyId),
1791 /// An associated type
1793 /// An associated existential type
1794 Existential(GenericBounds),
1797 /// Bind a type to an associated type (i.e., `A = Foo`).
1799 /// Bindings like `A: Debug` are represented as a special type `A =
1800 /// $::Debug` that is understood by the astconv code.
1802 /// FIXME(alexreg) -- why have a separate type for the binding case,
1803 /// wouldn't it be better to make the `ty` field an enum like:
1806 /// enum TypeBindingKind {
1811 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1812 pub struct TypeBinding {
1814 #[stable_hasher(project(name))]
1816 pub kind: TypeBindingKind,
1820 // Represents the two kinds of type bindings.
1821 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1822 pub enum TypeBindingKind {
1823 /// E.g., `Foo<Bar: Send>`.
1825 bounds: HirVec<GenericBound>,
1827 /// E.g., `Foo<Bar = ()>`.
1834 pub fn ty(&self) -> &Ty {
1836 TypeBindingKind::Equality { ref ty } => ty,
1837 _ => bug!("expected equality type binding for parenthesized generic args"),
1842 #[derive(Clone, RustcEncodable, RustcDecodable)]
1849 impl fmt::Debug for Ty {
1850 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1851 write!(f, "type({})",
1852 print::to_string(print::NO_ANN, |s| s.print_type(self)))
1856 /// Not represented directly in the AST; referred to by name through a `ty_path`.
1857 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy, HashStable)]
1867 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1868 pub struct BareFnTy {
1869 pub unsafety: Unsafety,
1871 pub generic_params: HirVec<GenericParam>,
1872 pub decl: P<FnDecl>,
1873 pub arg_names: HirVec<Ident>,
1876 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1877 pub struct ExistTy {
1878 pub generics: Generics,
1879 pub bounds: GenericBounds,
1880 pub impl_trait_fn: Option<DefId>,
1881 pub origin: ExistTyOrigin,
1884 /// Where the existential type came from
1885 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1886 pub enum ExistTyOrigin {
1887 /// `existential type Foo: Trait;`
1895 /// The various kinds of types recognized by the compiler.
1896 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1898 /// A variable length slice (i.e., `[T]`).
1900 /// A fixed length array (i.e., `[T; n]`).
1901 Array(P<Ty>, AnonConst),
1902 /// A raw pointer (i.e., `*const T` or `*mut T`).
1904 /// A reference (i.e., `&'a T` or `&'a mut T`).
1905 Rptr(Lifetime, MutTy),
1906 /// A bare function (e.g., `fn(usize) -> bool`).
1907 BareFn(P<BareFnTy>),
1908 /// The never type (`!`).
1910 /// A tuple (`(A, B, C, D, ...)`).
1912 /// A path to a type definition (`module::module::...::Type`), or an
1913 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
1915 /// Type parameters may be stored in each `PathSegment`.
1917 /// A type definition itself. This is currently only used for the `existential type`
1918 /// item that `impl Trait` in return position desugars to.
1920 /// The generic argument list contains the lifetimes (and in the future possibly parameters)
1921 /// that are actually bound on the `impl Trait`.
1922 Def(ItemId, HirVec<GenericArg>),
1923 /// A trait object type `Bound1 + Bound2 + Bound3`
1924 /// where `Bound` is a trait or a lifetime.
1925 TraitObject(HirVec<PolyTraitRef>, Lifetime),
1928 /// `TyKind::Infer` means the type should be inferred instead of it having been
1929 /// specified. This can appear anywhere in a type.
1931 /// Placeholder for a type that has failed to be defined.
1933 /// Placeholder for C-variadic arguments. We "spoof" the `VaList` created
1934 /// from the variadic arguments. This type is only valid up to typeck.
1938 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1939 pub struct InlineAsmOutput {
1940 pub constraint: Symbol,
1942 pub is_indirect: bool,
1946 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1947 pub struct InlineAsm {
1949 pub asm_str_style: StrStyle,
1950 pub outputs: HirVec<InlineAsmOutput>,
1951 pub inputs: HirVec<Symbol>,
1952 pub clobbers: HirVec<Symbol>,
1954 pub alignstack: bool,
1955 pub dialect: AsmDialect,
1956 #[stable_hasher(ignore)] // This is used for error reporting
1957 pub ctxt: SyntaxContext,
1960 /// Represents an argument in a function header.
1961 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1967 /// Represents the header (not the body) of a function declaration.
1968 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1970 /// The types of the function's arguments.
1972 /// Additional argument data is stored in the function's [body](Body::arguments).
1973 pub inputs: HirVec<Ty>,
1974 pub output: FunctionRetTy,
1975 pub c_variadic: bool,
1976 /// Does the function have an implicit self?
1977 pub implicit_self: ImplicitSelfKind,
1980 /// Represents what type of implicit self a function has, if any.
1981 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, HashStable)]
1982 pub enum ImplicitSelfKind {
1983 /// Represents a `fn x(self);`.
1985 /// Represents a `fn x(mut self);`.
1987 /// Represents a `fn x(&self);`.
1989 /// Represents a `fn x(&mut self);`.
1991 /// Represents when a function does not have a self argument or
1992 /// when a function has a `self: X` argument.
1996 impl ImplicitSelfKind {
1997 /// Does this represent an implicit self?
1998 pub fn has_implicit_self(&self) -> bool {
2000 ImplicitSelfKind::None => false,
2006 /// Is the trait definition an auto trait?
2007 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2013 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, HashStable,
2014 Ord, RustcEncodable, RustcDecodable, Debug)]
2020 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, HashStable,
2021 RustcEncodable, RustcDecodable, Hash, Debug)]
2027 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2028 pub enum Constness {
2033 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2034 pub enum Defaultness {
2035 Default { has_value: bool },
2040 pub fn has_value(&self) -> bool {
2042 Defaultness::Default { has_value, .. } => has_value,
2043 Defaultness::Final => true,
2047 pub fn is_final(&self) -> bool {
2048 *self == Defaultness::Final
2051 pub fn is_default(&self) -> bool {
2053 Defaultness::Default { .. } => true,
2059 impl fmt::Display for Unsafety {
2060 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2061 fmt::Display::fmt(match *self {
2062 Unsafety::Normal => "normal",
2063 Unsafety::Unsafe => "unsafe",
2069 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2070 pub enum ImplPolarity {
2071 /// `impl Trait for Type`
2073 /// `impl !Trait for Type`
2077 impl fmt::Debug for ImplPolarity {
2078 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2080 ImplPolarity::Positive => "positive".fmt(f),
2081 ImplPolarity::Negative => "negative".fmt(f),
2087 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2088 pub enum FunctionRetTy {
2089 /// Return type is not specified.
2091 /// Functions default to `()` and
2092 /// closures default to inference. Span points to where return
2093 /// type would be inserted.
2094 DefaultReturn(Span),
2095 /// Everything else.
2099 impl fmt::Display for FunctionRetTy {
2100 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2102 Return(ref ty) => print::to_string(print::NO_ANN, |s| s.print_type(ty)).fmt(f),
2103 DefaultReturn(_) => "()".fmt(f),
2108 impl FunctionRetTy {
2109 pub fn span(&self) -> Span {
2111 DefaultReturn(span) => span,
2112 Return(ref ty) => ty.span,
2117 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2119 /// A span from the first token past `{` to the last token until `}`.
2120 /// For `mod foo;`, the inner span ranges from the first token
2121 /// to the last token in the external file.
2123 pub item_ids: HirVec<ItemId>,
2126 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2127 pub struct ForeignMod {
2129 pub items: HirVec<ForeignItem>,
2132 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2133 pub struct GlobalAsm {
2135 #[stable_hasher(ignore)] // This is used for error reporting
2136 pub ctxt: SyntaxContext,
2139 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2140 pub struct EnumDef {
2141 pub variants: HirVec<Variant>,
2144 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2145 pub struct VariantKind {
2146 /// Name of the variant.
2147 #[stable_hasher(project(name))]
2149 /// Attributes of the variant.
2150 pub attrs: HirVec<Attribute>,
2151 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2153 /// Fields and constructor id of the variant.
2154 pub data: VariantData,
2155 /// Explicit discriminant (e.g., `Foo = 1`).
2156 pub disr_expr: Option<AnonConst>,
2159 pub type Variant = Spanned<VariantKind>;
2161 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2163 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2164 /// Also produced for each element of a list `use`, e.g.
2165 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2168 /// Glob import, e.g., `use foo::*`.
2171 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2172 /// an additional `use foo::{}` for performing checks such as
2173 /// unstable feature gating. May be removed in the future.
2177 /// References to traits in impls.
2179 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2180 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `NodeId` of the
2181 /// trait being referred to but just a unique `NodeId` that serves as a key
2182 /// within the resolution map.
2183 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2184 pub struct TraitRef {
2186 // Don't hash the ref_id. It is tracked via the thing it is used to access
2187 #[stable_hasher(ignore)]
2188 pub hir_ref_id: HirId,
2192 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2193 pub fn trait_def_id(&self) -> DefId {
2194 match self.path.res {
2195 Res::Def(DefKind::Trait, did) => did,
2196 Res::Def(DefKind::TraitAlias, did) => did,
2200 _ => unreachable!(),
2205 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2206 pub struct PolyTraitRef {
2207 /// The `'a` in `<'a> Foo<&'a T>`.
2208 pub bound_generic_params: HirVec<GenericParam>,
2210 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2211 pub trait_ref: TraitRef,
2216 pub type Visibility = Spanned<VisibilityKind>;
2218 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2219 pub enum VisibilityKind {
2222 Restricted { path: P<Path>, hir_id: HirId },
2226 impl VisibilityKind {
2227 pub fn is_pub(&self) -> bool {
2229 VisibilityKind::Public => true,
2234 pub fn is_pub_restricted(&self) -> bool {
2236 VisibilityKind::Public |
2237 VisibilityKind::Inherited => false,
2238 VisibilityKind::Crate(..) |
2239 VisibilityKind::Restricted { .. } => true,
2243 pub fn descr(&self) -> &'static str {
2245 VisibilityKind::Public => "public",
2246 VisibilityKind::Inherited => "private",
2247 VisibilityKind::Crate(..) => "crate-visible",
2248 VisibilityKind::Restricted { .. } => "restricted",
2253 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2254 pub struct StructField {
2256 #[stable_hasher(project(name))]
2258 pub vis: Visibility,
2261 pub attrs: HirVec<Attribute>,
2265 // Still necessary in couple of places
2266 pub fn is_positional(&self) -> bool {
2267 let first = self.ident.as_str().as_bytes()[0];
2268 first >= b'0' && first <= b'9'
2272 /// Fields and constructor IDs of enum variants and structs.
2273 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2274 pub enum VariantData {
2275 /// A struct variant.
2277 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2278 Struct(HirVec<StructField>, /* recovered */ bool),
2279 /// A tuple variant.
2281 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2282 Tuple(HirVec<StructField>, HirId),
2285 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2290 /// Return the fields of this variant.
2291 pub fn fields(&self) -> &[StructField] {
2293 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2298 /// Return the `HirId` of this variant's constructor, if it has one.
2299 pub fn ctor_hir_id(&self) -> Option<HirId> {
2301 VariantData::Struct(_, _) => None,
2302 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2307 // The bodies for items are stored "out of line", in a separate
2308 // hashmap in the `Crate`. Here we just record the node-id of the item
2309 // so it can fetched later.
2310 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2317 /// The name might be a dummy name in case of anonymous items
2318 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2322 pub attrs: HirVec<Attribute>,
2324 pub vis: Visibility,
2328 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, HashStable)]
2329 pub struct FnHeader {
2330 pub unsafety: Unsafety,
2331 pub constness: Constness,
2332 pub asyncness: IsAsync,
2337 pub fn is_const(&self) -> bool {
2338 match &self.constness {
2339 Constness::Const => true,
2345 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2347 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2349 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2350 ExternCrate(Option<Name>),
2352 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2356 /// `use foo::bar::baz;` (with `as baz` implicitly on the right)
2357 Use(P<Path>, UseKind),
2360 Static(P<Ty>, Mutability, BodyId),
2362 Const(P<Ty>, BodyId),
2363 /// A function declaration
2364 Fn(P<FnDecl>, FnHeader, Generics, BodyId),
2367 /// An external module
2368 ForeignMod(ForeignMod),
2369 /// Module-level inline assembly (from global_asm!)
2370 GlobalAsm(P<GlobalAsm>),
2371 /// A type alias, e.g., `type Foo = Bar<u8>`
2372 Ty(P<Ty>, Generics),
2373 /// An existential type definition, e.g., `existential type Foo: Bar;`
2374 Existential(ExistTy),
2375 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`
2376 Enum(EnumDef, Generics),
2377 /// A struct definition, e.g., `struct Foo<A> {x: A}`
2378 Struct(VariantData, Generics),
2379 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`
2380 Union(VariantData, Generics),
2381 /// Represents a Trait Declaration
2382 Trait(IsAuto, Unsafety, Generics, GenericBounds, HirVec<TraitItemRef>),
2383 /// Represents a Trait Alias Declaration
2384 TraitAlias(Generics, GenericBounds),
2386 /// An implementation, eg `impl<A> Trait for Foo { .. }`
2391 Option<TraitRef>, // (optional) trait this impl implements
2393 HirVec<ImplItemRef>),
2397 pub fn descriptive_variant(&self) -> &str {
2399 ItemKind::ExternCrate(..) => "extern crate",
2400 ItemKind::Use(..) => "use",
2401 ItemKind::Static(..) => "static item",
2402 ItemKind::Const(..) => "constant item",
2403 ItemKind::Fn(..) => "function",
2404 ItemKind::Mod(..) => "module",
2405 ItemKind::ForeignMod(..) => "foreign module",
2406 ItemKind::GlobalAsm(..) => "global asm",
2407 ItemKind::Ty(..) => "type alias",
2408 ItemKind::Existential(..) => "existential type",
2409 ItemKind::Enum(..) => "enum",
2410 ItemKind::Struct(..) => "struct",
2411 ItemKind::Union(..) => "union",
2412 ItemKind::Trait(..) => "trait",
2413 ItemKind::TraitAlias(..) => "trait alias",
2414 ItemKind::Impl(..) => "impl",
2418 pub fn adt_kind(&self) -> Option<AdtKind> {
2420 ItemKind::Struct(..) => Some(AdtKind::Struct),
2421 ItemKind::Union(..) => Some(AdtKind::Union),
2422 ItemKind::Enum(..) => Some(AdtKind::Enum),
2427 pub fn generics(&self) -> Option<&Generics> {
2429 ItemKind::Fn(_, _, ref generics, _) |
2430 ItemKind::Ty(_, ref generics) |
2431 ItemKind::Existential(ExistTy { ref generics, impl_trait_fn: None, .. }) |
2432 ItemKind::Enum(_, ref generics) |
2433 ItemKind::Struct(_, ref generics) |
2434 ItemKind::Union(_, ref generics) |
2435 ItemKind::Trait(_, _, ref generics, _, _) |
2436 ItemKind::Impl(_, _, _, ref generics, _, _, _)=> generics,
2442 /// A reference from an trait to one of its associated items. This
2443 /// contains the item's id, naturally, but also the item's name and
2444 /// some other high-level details (like whether it is an associated
2445 /// type or method, and whether it is public). This allows other
2446 /// passes to find the impl they want without loading the ID (which
2447 /// means fewer edges in the incremental compilation graph).
2448 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2449 pub struct TraitItemRef {
2450 pub id: TraitItemId,
2451 #[stable_hasher(project(name))]
2453 pub kind: AssocItemKind,
2455 pub defaultness: Defaultness,
2458 /// A reference from an impl to one of its associated items. This
2459 /// contains the item's ID, naturally, but also the item's name and
2460 /// some other high-level details (like whether it is an associated
2461 /// type or method, and whether it is public). This allows other
2462 /// passes to find the impl they want without loading the ID (which
2463 /// means fewer edges in the incremental compilation graph).
2464 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2465 pub struct ImplItemRef {
2467 #[stable_hasher(project(name))]
2469 pub kind: AssocItemKind,
2471 pub vis: Visibility,
2472 pub defaultness: Defaultness,
2475 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2476 pub enum AssocItemKind {
2478 Method { has_self: bool },
2483 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2484 pub struct ForeignItem {
2485 #[stable_hasher(project(name))]
2487 pub attrs: HirVec<Attribute>,
2488 pub node: ForeignItemKind,
2491 pub vis: Visibility,
2494 /// An item within an `extern` block.
2495 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2496 pub enum ForeignItemKind {
2497 /// A foreign function.
2498 Fn(P<FnDecl>, HirVec<Ident>, Generics),
2499 /// A foreign static item (`static ext: u8`).
2500 Static(P<Ty>, Mutability),
2505 impl ForeignItemKind {
2506 pub fn descriptive_variant(&self) -> &str {
2508 ForeignItemKind::Fn(..) => "foreign function",
2509 ForeignItemKind::Static(..) => "foreign static item",
2510 ForeignItemKind::Type => "foreign type",
2515 /// A variable captured by a closure.
2516 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable, HashStable)]
2518 // First span where it is accessed (there can be multiple).
2522 pub type CaptureModeMap = NodeMap<CaptureClause>;
2524 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2525 // has length > 0 if the trait is found through an chain of imports, starting with the
2526 // import/use statement in the scope where the trait is used.
2527 #[derive(Clone, Debug)]
2528 pub struct TraitCandidate {
2530 pub import_ids: SmallVec<[NodeId; 1]>,
2533 // Trait method resolution
2534 pub type TraitMap = NodeMap<Vec<TraitCandidate>>;
2536 // Map from the NodeId of a glob import to a list of items which are actually
2538 pub type GlobMap = NodeMap<FxHashSet<Name>>;
2540 pub fn provide(providers: &mut Providers<'_>) {
2541 check_attr::provide(providers);
2542 map::provide(providers);
2543 upvars::provide(providers);
2546 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
2547 pub struct CodegenFnAttrs {
2548 pub flags: CodegenFnAttrFlags,
2549 /// Parsed representation of the `#[inline]` attribute
2550 pub inline: InlineAttr,
2551 /// Parsed representation of the `#[optimize]` attribute
2552 pub optimize: OptimizeAttr,
2553 /// The `#[export_name = "..."]` attribute, indicating a custom symbol a
2554 /// function should be exported under
2555 pub export_name: Option<Symbol>,
2556 /// The `#[link_name = "..."]` attribute, indicating a custom symbol an
2557 /// imported function should be imported as. Note that `export_name`
2558 /// probably isn't set when this is set, this is for foreign items while
2559 /// `#[export_name]` is for Rust-defined functions.
2560 pub link_name: Option<Symbol>,
2561 /// The `#[target_feature(enable = "...")]` attribute and the enabled
2562 /// features (only enabled features are supported right now).
2563 pub target_features: Vec<Symbol>,
2564 /// The `#[linkage = "..."]` attribute and the value we found.
2565 pub linkage: Option<Linkage>,
2566 /// The `#[link_section = "..."]` attribute, or what executable section this
2567 /// should be placed in.
2568 pub link_section: Option<Symbol>,
2572 #[derive(RustcEncodable, RustcDecodable, HashStable)]
2573 pub struct CodegenFnAttrFlags: u32 {
2574 /// `#[cold]`: a hint to LLVM that this function, when called, is never on
2576 const COLD = 1 << 0;
2577 /// `#[allocator]`: a hint to LLVM that the pointer returned from this
2578 /// function is never null.
2579 const ALLOCATOR = 1 << 1;
2580 /// `#[unwind]`: an indicator that this function may unwind despite what
2581 /// its ABI signature may otherwise imply.
2582 const UNWIND = 1 << 2;
2583 /// `#[rust_allocator_nounwind]`, an indicator that an imported FFI
2584 /// function will never unwind. Probably obsolete by recent changes with
2585 /// #[unwind], but hasn't been removed/migrated yet
2586 const RUSTC_ALLOCATOR_NOUNWIND = 1 << 3;
2587 /// `#[naked]`: an indicator to LLVM that no function prologue/epilogue
2588 /// should be generated.
2589 const NAKED = 1 << 4;
2590 /// `#[no_mangle]`: an indicator that the function's name should be the same
2592 const NO_MANGLE = 1 << 5;
2593 /// `#[rustc_std_internal_symbol]`: an indicator that this symbol is a
2594 /// "weird symbol" for the standard library in that it has slightly
2595 /// different linkage, visibility, and reachability rules.
2596 const RUSTC_STD_INTERNAL_SYMBOL = 1 << 6;
2597 /// `#[no_debug]`: an indicator that no debugging information should be
2598 /// generated for this function by LLVM.
2599 const NO_DEBUG = 1 << 7;
2600 /// `#[thread_local]`: indicates a static is actually a thread local
2602 const THREAD_LOCAL = 1 << 8;
2603 /// `#[used]`: indicates that LLVM can't eliminate this function (but the
2605 const USED = 1 << 9;
2606 /// #[ffi_returns_twice], indicates that an extern function can return
2608 const FFI_RETURNS_TWICE = 1 << 10;
2612 impl CodegenFnAttrs {
2613 pub fn new() -> CodegenFnAttrs {
2615 flags: CodegenFnAttrFlags::empty(),
2616 inline: InlineAttr::None,
2617 optimize: OptimizeAttr::None,
2620 target_features: vec![],
2626 /// Returns `true` if `#[inline]` or `#[inline(always)]` is present.
2627 pub fn requests_inline(&self) -> bool {
2629 InlineAttr::Hint | InlineAttr::Always => true,
2630 InlineAttr::None | InlineAttr::Never => false,
2634 /// Returns `true` if it looks like this symbol needs to be exported, for example:
2636 /// * `#[no_mangle]` is present
2637 /// * `#[export_name(...)]` is present
2638 /// * `#[linkage]` is present
2639 pub fn contains_extern_indicator(&self) -> bool {
2640 self.flags.contains(CodegenFnAttrFlags::NO_MANGLE) ||
2641 self.export_name.is_some() ||
2642 match self.linkage {
2643 // These are private, so make sure we don't try to consider
2646 Some(Linkage::Internal) |
2647 Some(Linkage::Private) => false,
2653 #[derive(Copy, Clone, Debug)]
2654 pub enum Node<'hir> {
2656 ForeignItem(&'hir ForeignItem),
2657 TraitItem(&'hir TraitItem),
2658 ImplItem(&'hir ImplItem),
2659 Variant(&'hir Variant),
2660 Field(&'hir StructField),
2661 AnonConst(&'hir AnonConst),
2664 PathSegment(&'hir PathSegment),
2666 TraitRef(&'hir TraitRef),
2672 MacroDef(&'hir MacroDef),
2674 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
2675 /// with synthesized constructors.
2676 Ctor(&'hir VariantData),
2678 Lifetime(&'hir Lifetime),
2679 GenericParam(&'hir GenericParam),
2680 Visibility(&'hir Visibility),