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::FunctionRetTy::*;
7 pub use self::PrimTy::*;
9 pub use self::UnsafeSource::*;
11 use crate::hir::def::{DefKind, Res};
12 use crate::hir::def_id::{DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX};
13 use crate::hir::ptr::P;
14 use crate::mir::mono::Linkage;
15 use crate::ty::query::Providers;
16 use crate::ty::AdtKind;
17 use crate::util::nodemap::{FxHashSet, NodeMap};
19 use errors::FatalError;
20 use rustc_data_structures::sync::{par_for_each_in, Send, Sync};
21 use rustc_macros::HashStable;
22 use rustc_serialize::{self, Decodable, Decoder, Encodable, Encoder};
23 use rustc_target::spec::abi::Abi;
24 use smallvec::SmallVec;
25 use std::collections::{BTreeMap, BTreeSet};
27 use syntax::ast::{self, AsmDialect, CrateSugar, Ident, Name, NodeId};
28 use syntax::ast::{AttrVec, Attribute, FloatTy, IntTy, Label, LitKind, StrStyle, UintTy};
29 pub use syntax::ast::{BorrowKind, ImplPolarity, IsAuto};
30 pub use syntax::ast::{CaptureBy, Constness, Movability, Mutability, Unsafety};
31 use syntax::attr::{InlineAttr, OptimizeAttr};
32 use syntax::tokenstream::TokenStream;
33 use syntax::util::parser::ExprPrecedence;
34 use syntax_pos::source_map::{SourceMap, Spanned};
35 use syntax_pos::symbol::{kw, sym, Symbol};
36 use syntax_pos::{MultiSpan, Span, DUMMY_SP};
38 /// HIR doesn't commit to a concrete storage type and has its own alias for a vector.
39 /// It can be `Vec`, `P<[T]>` or potentially `Box<[T]>`, or some other container with similar
40 /// behavior. Unlike AST, HIR is mostly a static structure, so we can use an owned slice instead
41 /// of `Vec` to avoid keeping extra capacity.
42 pub type HirVec<T> = P<[T]>;
44 macro_rules! hir_vec {
45 ($elem:expr; $n:expr) => (
46 $crate::hir::HirVec::from(vec![$elem; $n])
49 $crate::hir::HirVec::from(vec![$($x),*])
57 pub mod itemlikevisit;
65 /// Uniquely identifies a node in the HIR of the current crate. It is
66 /// composed of the `owner`, which is the `DefIndex` of the directly enclosing
67 /// `hir::Item`, `hir::TraitItem`, or `hir::ImplItem` (i.e., the closest "item-like"),
68 /// and the `local_id` which is unique within the given owner.
70 /// This two-level structure makes for more stable values: One can move an item
71 /// around within the source code, or add or remove stuff before it, without
72 /// the `local_id` part of the `HirId` changing, which is a very useful property in
73 /// incremental compilation where we have to persist things through changes to
75 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)]
78 pub local_id: ItemLocalId,
82 pub fn owner_def_id(self) -> DefId {
83 DefId::local(self.owner)
86 pub fn owner_local_def_id(self) -> LocalDefId {
87 LocalDefId::from_def_id(DefId::local(self.owner))
91 impl rustc_serialize::UseSpecializedEncodable for HirId {
92 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
93 let HirId { owner, local_id } = *self;
101 impl rustc_serialize::UseSpecializedDecodable for HirId {
102 fn default_decode<D: Decoder>(d: &mut D) -> Result<HirId, D::Error> {
103 let owner = DefIndex::decode(d)?;
104 let local_id = ItemLocalId::decode(d)?;
106 Ok(HirId { owner, local_id })
110 impl fmt::Display for HirId {
111 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112 write!(f, "{:?}", self)
116 // Hack to ensure that we don't try to access the private parts of `ItemLocalId` in this module.
117 mod item_local_id_inner {
118 use rustc_index::vec::Idx;
119 use rustc_macros::HashStable;
120 rustc_index::newtype_index! {
121 /// An `ItemLocalId` uniquely identifies something within a given "item-like";
122 /// that is, within a `hir::Item`, `hir::TraitItem`, or `hir::ImplItem`. There is no
123 /// guarantee that the numerical value of a given `ItemLocalId` corresponds to
124 /// the node's position within the owning item in any way, but there is a
125 /// guarantee that the `LocalItemId`s within an owner occupy a dense range of
126 /// integers starting at zero, so a mapping that maps all or most nodes within
127 /// an "item-like" to something else can be implemented by a `Vec` instead of a
128 /// tree or hash map.
129 pub struct ItemLocalId {
135 pub use self::item_local_id_inner::ItemLocalId;
137 /// The `HirId` corresponding to `CRATE_NODE_ID` and `CRATE_DEF_INDEX`.
138 pub const CRATE_HIR_ID: HirId =
139 HirId { owner: CRATE_DEF_INDEX, local_id: ItemLocalId::from_u32_const(0) };
141 pub const DUMMY_HIR_ID: HirId = HirId { owner: CRATE_DEF_INDEX, local_id: DUMMY_ITEM_LOCAL_ID };
143 pub const DUMMY_ITEM_LOCAL_ID: ItemLocalId = ItemLocalId::MAX;
145 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, HashStable)]
146 pub struct Lifetime {
150 /// Either "`'a`", referring to a named lifetime definition,
151 /// or "``" (i.e., `kw::Invalid`), for elision placeholders.
153 /// HIR lowering inserts these placeholders in type paths that
154 /// refer to type definitions needing lifetime parameters,
155 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
156 pub name: LifetimeName,
159 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy, HashStable)]
161 /// Some user-given name like `T` or `'x`.
164 /// Synthetic name generated when user elided a lifetime in an impl header.
166 /// E.g., the lifetimes in cases like these:
168 /// impl Foo for &u32
169 /// impl Foo<'_> for u32
171 /// in that case, we rewrite to
173 /// impl<'f> Foo for &'f u32
174 /// impl<'f> Foo<'f> for u32
176 /// where `'f` is something like `Fresh(0)`. The indices are
177 /// unique per impl, but not necessarily continuous.
180 /// Indicates an illegal name was given and an error has been
181 /// reported (so we should squelch other derived errors). Occurs
182 /// when, e.g., `'_` is used in the wrong place.
187 pub fn ident(&self) -> Ident {
189 ParamName::Plain(ident) => ident,
190 ParamName::Fresh(_) | ParamName::Error => {
191 Ident::with_dummy_span(kw::UnderscoreLifetime)
196 pub fn modern(&self) -> ParamName {
198 ParamName::Plain(ident) => ParamName::Plain(ident.modern()),
199 param_name => param_name,
204 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy, HashStable)]
205 pub enum LifetimeName {
206 /// User-given names or fresh (synthetic) names.
209 /// User wrote nothing (e.g., the lifetime in `&u32`).
212 /// Implicit lifetime in a context like `dyn Foo`. This is
213 /// distinguished from implicit lifetimes elsewhere because the
214 /// lifetime that they default to must appear elsewhere within the
215 /// enclosing type. This means that, in an `impl Trait` context, we
216 /// don't have to create a parameter for them. That is, `impl
217 /// Trait<Item = &u32>` expands to an opaque type like `type
218 /// Foo<'a> = impl Trait<Item = &'a u32>`, but `impl Trait<item =
219 /// dyn Bar>` expands to `type Foo = impl Trait<Item = dyn Bar +
220 /// 'static>`. The latter uses `ImplicitObjectLifetimeDefault` so
221 /// that surrounding code knows not to create a lifetime
223 ImplicitObjectLifetimeDefault,
225 /// Indicates an error during lowering (usually `'_` in wrong place)
226 /// that was already reported.
229 /// User wrote specifies `'_`.
232 /// User wrote `'static`.
237 pub fn ident(&self) -> Ident {
239 LifetimeName::ImplicitObjectLifetimeDefault
240 | LifetimeName::Implicit
241 | LifetimeName::Error => Ident::invalid(),
242 LifetimeName::Underscore => Ident::with_dummy_span(kw::UnderscoreLifetime),
243 LifetimeName::Static => Ident::with_dummy_span(kw::StaticLifetime),
244 LifetimeName::Param(param_name) => param_name.ident(),
248 pub fn is_elided(&self) -> bool {
250 LifetimeName::ImplicitObjectLifetimeDefault
251 | LifetimeName::Implicit
252 | 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 {
287 print::to_string(print::NO_ANN, |s| s.print_lifetime(self))
293 pub fn is_elided(&self) -> bool {
294 self.name.is_elided()
297 pub fn is_static(&self) -> bool {
298 self.name.is_static()
302 /// A `Path` is essentially Rust's notion of a name; for instance,
303 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
304 /// along with a bunch of supporting information.
305 #[derive(RustcEncodable, RustcDecodable, HashStable)]
308 /// The resolution for the path.
310 /// The segments in the path: the things separated by `::`.
311 pub segments: HirVec<PathSegment>,
315 pub fn is_global(&self) -> bool {
316 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
320 impl fmt::Debug for Path {
321 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
322 write!(f, "path({})", self)
326 impl fmt::Display for Path {
327 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
328 write!(f, "{}", print::to_string(print::NO_ANN, |s| s.print_path(self, false)))
332 /// A segment of a path: an identifier, an optional lifetime, and a set of
334 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
335 pub struct PathSegment {
336 /// The identifier portion of this path segment.
337 #[stable_hasher(project(name))]
339 // `id` and `res` are optional. We currently only use these in save-analysis,
340 // any path segments without these will not have save-analysis info and
341 // therefore will not have 'jump to def' in IDEs, but otherwise will not be
342 // affected. (In general, we don't bother to get the defs for synthesized
343 // segments, only for segments which have come from the AST).
344 pub hir_id: Option<HirId>,
345 pub res: Option<Res>,
347 /// Type/lifetime parameters attached to this path. They come in
348 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
349 /// this is more than just simple syntactic sugar; the use of
350 /// parens affects the region binding rules, so we preserve the
352 pub args: Option<P<GenericArgs>>,
354 /// Whether to infer remaining type parameters, if any.
355 /// This only applies to expression and pattern paths, and
356 /// out of those only the segments with no type parameters
357 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
358 pub infer_args: bool,
362 /// Converts an identifier to the corresponding segment.
363 pub fn from_ident(ident: Ident) -> PathSegment {
364 PathSegment { ident, hir_id: None, res: None, infer_args: true, args: None }
369 hir_id: Option<HirId>,
379 args: if args.is_empty() { None } else { Some(P(args)) },
383 pub fn generic_args(&self) -> &GenericArgs {
384 if let Some(ref args) = self.args {
387 const DUMMY: &GenericArgs = &GenericArgs::none();
393 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
394 pub struct ConstArg {
395 pub value: AnonConst,
399 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
400 pub enum GenericArg {
407 pub fn span(&self) -> Span {
409 GenericArg::Lifetime(l) => l.span,
410 GenericArg::Type(t) => t.span,
411 GenericArg::Const(c) => c.span,
415 pub fn id(&self) -> HirId {
417 GenericArg::Lifetime(l) => l.hir_id,
418 GenericArg::Type(t) => t.hir_id,
419 GenericArg::Const(c) => c.value.hir_id,
423 pub fn is_const(&self) -> bool {
425 GenericArg::Const(_) => true,
431 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
432 pub struct GenericArgs {
433 /// The generic arguments for this path segment.
434 pub args: HirVec<GenericArg>,
435 /// Bindings (equality constraints) on associated types, if present.
436 /// E.g., `Foo<A = Bar>`.
437 pub bindings: HirVec<TypeBinding>,
438 /// Were arguments written in parenthesized form `Fn(T) -> U`?
439 /// This is required mostly for pretty-printing and diagnostics,
440 /// but also for changing lifetime elision rules to be "function-like".
441 pub parenthesized: bool,
445 pub const fn none() -> Self {
446 Self { args: HirVec::new(), bindings: HirVec::new(), parenthesized: false }
449 pub fn is_empty(&self) -> bool {
450 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
453 pub fn inputs(&self) -> &[Ty] {
454 if self.parenthesized {
455 for arg in &self.args {
457 GenericArg::Lifetime(_) => {}
458 GenericArg::Type(ref ty) => {
459 if let TyKind::Tup(ref tys) = ty.kind {
464 GenericArg::Const(_) => {}
468 bug!("GenericArgs::inputs: not a `Fn(T) -> U`");
471 pub fn own_counts(&self) -> GenericParamCount {
472 // We could cache this as a property of `GenericParamCount`, but
473 // the aim is to refactor this away entirely eventually and the
474 // presence of this method will be a constant reminder.
475 let mut own_counts: GenericParamCount = Default::default();
477 for arg in &self.args {
479 GenericArg::Lifetime(_) => own_counts.lifetimes += 1,
480 GenericArg::Type(_) => own_counts.types += 1,
481 GenericArg::Const(_) => own_counts.consts += 1,
489 /// A modifier on a bound, currently this is only used for `?Sized`, where the
490 /// modifier is `Maybe`. Negative bounds should also be handled here.
491 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
492 pub enum TraitBoundModifier {
497 /// The AST represents all type param bounds as types.
498 /// `typeck::collect::compute_bounds` matches these against
499 /// the "special" built-in traits (see `middle::lang_items`) and
500 /// detects `Copy`, `Send` and `Sync`.
501 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
502 pub enum GenericBound {
503 Trait(PolyTraitRef, TraitBoundModifier),
508 pub fn span(&self) -> Span {
510 &GenericBound::Trait(ref t, ..) => t.span,
511 &GenericBound::Outlives(ref l) => l.span,
516 pub type GenericBounds = HirVec<GenericBound>;
518 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable)]
519 pub enum LifetimeParamKind {
520 // Indicates that the lifetime definition was explicitly declared (e.g., in
521 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
524 // Indicates that the lifetime definition was synthetically added
525 // as a result of an in-band lifetime usage (e.g., in
526 // `fn foo(x: &'a u8) -> &'a u8 { x }`).
529 // Indication that the lifetime was elided (e.g., in both cases in
530 // `fn foo(x: &u8) -> &'_ u8 { x }`).
533 // Indication that the lifetime name was somehow in error.
537 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
538 pub enum GenericParamKind {
539 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
541 kind: LifetimeParamKind,
544 default: Option<P<Ty>>,
545 synthetic: Option<SyntheticTyParamKind>,
552 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
553 pub struct GenericParam {
556 pub attrs: HirVec<Attribute>,
557 pub bounds: GenericBounds,
559 pub pure_wrt_drop: bool,
560 pub kind: GenericParamKind,
564 pub struct GenericParamCount {
565 pub lifetimes: usize,
570 /// Represents lifetimes and type parameters attached to a declaration
571 /// of a function, enum, trait, etc.
572 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
573 pub struct Generics {
574 pub params: HirVec<GenericParam>,
575 pub where_clause: WhereClause,
580 pub const fn empty() -> Generics {
582 params: HirVec::new(),
583 where_clause: WhereClause { predicates: HirVec::new(), span: DUMMY_SP },
588 pub fn own_counts(&self) -> GenericParamCount {
589 // We could cache this as a property of `GenericParamCount`, but
590 // the aim is to refactor this away entirely eventually and the
591 // presence of this method will be a constant reminder.
592 let mut own_counts: GenericParamCount = Default::default();
594 for param in &self.params {
596 GenericParamKind::Lifetime { .. } => own_counts.lifetimes += 1,
597 GenericParamKind::Type { .. } => own_counts.types += 1,
598 GenericParamKind::Const { .. } => own_counts.consts += 1,
605 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam> {
606 for param in &self.params {
607 if name == param.name.ident().name {
614 pub fn spans(&self) -> MultiSpan {
615 if self.params.is_empty() {
618 self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
623 /// Synthetic type parameters are converted to another form during lowering; this allows
624 /// us to track the original form they had, and is useful for error messages.
625 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
626 pub enum SyntheticTyParamKind {
630 /// A where-clause in a definition.
631 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
632 pub struct WhereClause {
633 pub predicates: HirVec<WherePredicate>,
634 // Only valid if predicates isn't empty.
639 pub fn span(&self) -> Option<Span> {
640 if self.predicates.is_empty() { None } else { Some(self.span) }
643 /// The `WhereClause` under normal circumstances points at either the predicates or the empty
644 /// space where the `where` clause should be. Only of use for diagnostic suggestions.
645 pub fn span_for_predicates_or_empty_place(&self) -> Span {
650 /// A single predicate in a where-clause.
651 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
652 pub enum WherePredicate {
653 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
654 BoundPredicate(WhereBoundPredicate),
655 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
656 RegionPredicate(WhereRegionPredicate),
657 /// An equality predicate (unsupported).
658 EqPredicate(WhereEqPredicate),
661 impl WherePredicate {
662 pub fn span(&self) -> Span {
664 &WherePredicate::BoundPredicate(ref p) => p.span,
665 &WherePredicate::RegionPredicate(ref p) => p.span,
666 &WherePredicate::EqPredicate(ref p) => p.span,
671 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
672 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
673 pub struct WhereBoundPredicate {
675 /// Any generics from a `for` binding.
676 pub bound_generic_params: HirVec<GenericParam>,
677 /// The type being bounded.
678 pub bounded_ty: P<Ty>,
679 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
680 pub bounds: GenericBounds,
683 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
684 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
685 pub struct WhereRegionPredicate {
687 pub lifetime: Lifetime,
688 pub bounds: GenericBounds,
691 /// An equality predicate (e.g., `T = int`); currently unsupported.
692 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
693 pub struct WhereEqPredicate {
700 #[derive(RustcEncodable, RustcDecodable, Debug)]
701 pub struct ModuleItems {
702 // Use BTreeSets here so items are in the same order as in the
703 // list of all items in Crate
704 pub items: BTreeSet<HirId>,
705 pub trait_items: BTreeSet<TraitItemId>,
706 pub impl_items: BTreeSet<ImplItemId>,
709 /// The top-level data structure that stores the entire contents of
710 /// the crate currently being compiled.
712 /// For more details, see the [rustc guide].
714 /// [rustc guide]: https://rust-lang.github.io/rustc-guide/hir.html
715 #[derive(RustcEncodable, RustcDecodable, Debug)]
716 pub struct Crate<'hir> {
717 pub module: Mod<'hir>,
718 pub attrs: &'hir [Attribute],
720 pub exported_macros: &'hir [MacroDef<'hir>],
721 // Attributes from non-exported macros, kept only for collecting the library feature list.
722 pub non_exported_macro_attrs: &'hir [Attribute],
724 // N.B., we use a `BTreeMap` here so that `visit_all_items` iterates
725 // over the ids in increasing order. In principle it should not
726 // matter what order we visit things in, but in *practice* it
727 // does, because it can affect the order in which errors are
728 // detected, which in turn can make compile-fail tests yield
729 // slightly different results.
730 pub items: BTreeMap<HirId, Item<'hir>>,
732 pub trait_items: BTreeMap<TraitItemId, TraitItem<'hir>>,
733 pub impl_items: BTreeMap<ImplItemId, ImplItem<'hir>>,
734 pub bodies: BTreeMap<BodyId, Body<'hir>>,
735 pub trait_impls: BTreeMap<DefId, Vec<HirId>>,
737 /// A list of the body ids written out in the order in which they
738 /// appear in the crate. If you're going to process all the bodies
739 /// in the crate, you should iterate over this list rather than the keys
741 pub body_ids: Vec<BodyId>,
743 /// A list of modules written out in the order in which they
744 /// appear in the crate. This includes the main crate module.
745 pub modules: BTreeMap<HirId, ModuleItems>,
749 pub fn item(&self, id: HirId) -> &Item<'hir> {
753 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem<'hir> {
754 &self.trait_items[&id]
757 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem<'hir> {
758 &self.impl_items[&id]
761 pub fn body(&self, id: BodyId) -> &Body<'hir> {
767 /// Visits all items in the crate in some deterministic (but
768 /// unspecified) order. If you just need to process every item,
769 /// but don't care about nesting, this method is the best choice.
771 /// If you do care about nesting -- usually because your algorithm
772 /// follows lexical scoping rules -- then you want a different
773 /// approach. You should override `visit_nested_item` in your
774 /// visitor and then call `intravisit::walk_crate` instead.
775 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
777 V: itemlikevisit::ItemLikeVisitor<'hir>,
779 for (_, item) in &self.items {
780 visitor.visit_item(item);
783 for (_, trait_item) in &self.trait_items {
784 visitor.visit_trait_item(trait_item);
787 for (_, impl_item) in &self.impl_items {
788 visitor.visit_impl_item(impl_item);
792 /// A parallel version of `visit_all_item_likes`.
793 pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
795 V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send,
799 par_for_each_in(&self.items, |(_, item)| {
800 visitor.visit_item(item);
804 par_for_each_in(&self.trait_items, |(_, trait_item)| {
805 visitor.visit_trait_item(trait_item);
809 par_for_each_in(&self.impl_items, |(_, impl_item)| {
810 visitor.visit_impl_item(impl_item);
817 /// A macro definition, in this crate or imported from another.
819 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
820 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
821 pub struct MacroDef<'hir> {
824 pub attrs: &'hir [Attribute],
827 pub body: TokenStream,
831 /// A block of statements `{ .. }`, which may have a label (in this case the
832 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
833 /// the `rules` being anything but `DefaultBlock`.
834 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
836 /// Statements in a block.
837 pub stmts: HirVec<Stmt>,
838 /// An expression at the end of the block
839 /// without a semicolon, if any.
840 pub expr: Option<P<Expr>>,
841 #[stable_hasher(ignore)]
843 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
844 pub rules: BlockCheckMode,
846 /// If true, then there may exist `break 'a` values that aim to
847 /// break out of this block early.
848 /// Used by `'label: {}` blocks and by `try {}` blocks.
849 pub targeted_by_break: bool,
852 #[derive(RustcEncodable, RustcDecodable, HashStable)]
854 #[stable_hasher(ignore)]
860 impl fmt::Debug for Pat {
861 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
866 print::to_string(print::NO_ANN, |s| s.print_pat(self))
872 // FIXME(#19596) this is a workaround, but there should be a better way
873 fn walk_short_(&self, it: &mut impl FnMut(&Pat) -> bool) -> bool {
880 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
881 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
882 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
883 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
884 Slice(before, slice, after) => {
885 before.iter().chain(slice.iter()).chain(after.iter()).all(|p| p.walk_short_(it))
890 /// Walk the pattern in left-to-right order,
891 /// short circuiting (with `.all(..)`) if `false` is returned.
893 /// Note that when visiting e.g. `Tuple(ps)`,
894 /// if visiting `ps[0]` returns `false`,
895 /// then `ps[1]` will not be visited.
896 pub fn walk_short(&self, mut it: impl FnMut(&Pat) -> bool) -> bool {
897 self.walk_short_(&mut it)
900 // FIXME(#19596) this is a workaround, but there should be a better way
901 fn walk_(&self, it: &mut impl FnMut(&Pat) -> bool) {
908 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
909 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
910 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
911 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
912 Slice(before, slice, after) => {
913 before.iter().chain(slice.iter()).chain(after.iter()).for_each(|p| p.walk_(it))
918 /// Walk the pattern in left-to-right order.
920 /// If `it(pat)` returns `false`, the children are not visited.
921 pub fn walk(&self, mut it: impl FnMut(&Pat) -> bool) {
926 /// A single field in a struct pattern.
928 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
929 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
930 /// except `is_shorthand` is true.
931 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
932 pub struct FieldPat {
933 #[stable_hasher(ignore)]
935 /// The identifier for the field.
936 #[stable_hasher(project(name))]
938 /// The pattern the field is destructured to.
940 pub is_shorthand: bool,
944 /// Explicit binding annotations given in the HIR for a binding. Note
945 /// that this is not the final binding *mode* that we infer after type
947 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
948 pub enum BindingAnnotation {
949 /// No binding annotation given: this means that the final binding mode
950 /// will depend on whether we have skipped through a `&` reference
951 /// when matching. For example, the `x` in `Some(x)` will have binding
952 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
953 /// ultimately be inferred to be by-reference.
955 /// Note that implicit reference skipping is not implemented yet (#42640).
958 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
961 /// Annotated as `ref`, like `ref x`
964 /// Annotated as `ref mut x`.
968 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
974 impl fmt::Display for RangeEnd {
975 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
976 f.write_str(match self {
977 RangeEnd::Included => "..=",
978 RangeEnd::Excluded => "..",
983 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
985 /// Represents a wildcard pattern (i.e., `_`).
988 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
989 /// The `HirId` is the canonical ID for the variable being bound,
990 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
991 /// which is the pattern ID of the first `x`.
992 Binding(BindingAnnotation, HirId, Ident, Option<P<Pat>>),
994 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
995 /// The `bool` is `true` in the presence of a `..`.
996 Struct(QPath, HirVec<FieldPat>, bool),
998 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
999 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
1000 /// `0 <= position <= subpats.len()`
1001 TupleStruct(QPath, HirVec<P<Pat>>, Option<usize>),
1003 /// An or-pattern `A | B | C`.
1004 /// Invariant: `pats.len() >= 2`.
1007 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
1010 /// A tuple pattern (e.g., `(a, b)`).
1011 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
1012 /// `0 <= position <= subpats.len()`
1013 Tuple(HirVec<P<Pat>>, Option<usize>),
1015 /// A `box` pattern.
1018 /// A reference pattern (e.g., `&mut (a, b)`).
1019 Ref(P<Pat>, Mutability),
1024 /// A range pattern (e.g., `1..=2` or `1..2`).
1025 Range(P<Expr>, P<Expr>, RangeEnd),
1027 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
1029 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
1030 /// If `slice` exists, then `after` can be non-empty.
1032 /// The representation for e.g., `[a, b, .., c, d]` is:
1034 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
1036 Slice(HirVec<P<Pat>>, Option<P<Pat>>, HirVec<P<Pat>>),
1039 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1040 pub enum BinOpKind {
1041 /// The `+` operator (addition).
1043 /// The `-` operator (subtraction).
1045 /// The `*` operator (multiplication).
1047 /// The `/` operator (division).
1049 /// The `%` operator (modulus).
1051 /// The `&&` operator (logical and).
1053 /// The `||` operator (logical or).
1055 /// The `^` operator (bitwise xor).
1057 /// The `&` operator (bitwise and).
1059 /// The `|` operator (bitwise or).
1061 /// The `<<` operator (shift left).
1063 /// The `>>` operator (shift right).
1065 /// The `==` operator (equality).
1067 /// The `<` operator (less than).
1069 /// The `<=` operator (less than or equal to).
1071 /// The `!=` operator (not equal to).
1073 /// The `>=` operator (greater than or equal to).
1075 /// The `>` operator (greater than).
1080 pub fn as_str(self) -> &'static str {
1082 BinOpKind::Add => "+",
1083 BinOpKind::Sub => "-",
1084 BinOpKind::Mul => "*",
1085 BinOpKind::Div => "/",
1086 BinOpKind::Rem => "%",
1087 BinOpKind::And => "&&",
1088 BinOpKind::Or => "||",
1089 BinOpKind::BitXor => "^",
1090 BinOpKind::BitAnd => "&",
1091 BinOpKind::BitOr => "|",
1092 BinOpKind::Shl => "<<",
1093 BinOpKind::Shr => ">>",
1094 BinOpKind::Eq => "==",
1095 BinOpKind::Lt => "<",
1096 BinOpKind::Le => "<=",
1097 BinOpKind::Ne => "!=",
1098 BinOpKind::Ge => ">=",
1099 BinOpKind::Gt => ">",
1103 pub fn is_lazy(self) -> bool {
1105 BinOpKind::And | BinOpKind::Or => true,
1110 pub fn is_shift(self) -> bool {
1112 BinOpKind::Shl | BinOpKind::Shr => true,
1117 pub fn is_comparison(self) -> bool {
1124 | BinOpKind::Ge => true,
1136 | BinOpKind::Shr => false,
1140 /// Returns `true` if the binary operator takes its arguments by value.
1141 pub fn is_by_value(self) -> bool {
1142 !self.is_comparison()
1146 impl Into<ast::BinOpKind> for BinOpKind {
1147 fn into(self) -> ast::BinOpKind {
1149 BinOpKind::Add => ast::BinOpKind::Add,
1150 BinOpKind::Sub => ast::BinOpKind::Sub,
1151 BinOpKind::Mul => ast::BinOpKind::Mul,
1152 BinOpKind::Div => ast::BinOpKind::Div,
1153 BinOpKind::Rem => ast::BinOpKind::Rem,
1154 BinOpKind::And => ast::BinOpKind::And,
1155 BinOpKind::Or => ast::BinOpKind::Or,
1156 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1157 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1158 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1159 BinOpKind::Shl => ast::BinOpKind::Shl,
1160 BinOpKind::Shr => ast::BinOpKind::Shr,
1161 BinOpKind::Eq => ast::BinOpKind::Eq,
1162 BinOpKind::Lt => ast::BinOpKind::Lt,
1163 BinOpKind::Le => ast::BinOpKind::Le,
1164 BinOpKind::Ne => ast::BinOpKind::Ne,
1165 BinOpKind::Ge => ast::BinOpKind::Ge,
1166 BinOpKind::Gt => ast::BinOpKind::Gt,
1171 pub type BinOp = Spanned<BinOpKind>;
1173 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1175 /// The `*` operator (deferencing).
1177 /// The `!` operator (logical negation).
1179 /// The `-` operator (negation).
1184 pub fn as_str(self) -> &'static str {
1192 /// Returns `true` if the unary operator takes its argument by value.
1193 pub fn is_by_value(self) -> bool {
1195 UnNeg | UnNot => true,
1202 #[derive(RustcEncodable, RustcDecodable, HashStable)]
1209 impl fmt::Debug for Stmt {
1210 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1215 print::to_string(print::NO_ANN, |s| s.print_stmt(self))
1220 /// The contents of a statement.
1221 #[derive(RustcEncodable, RustcDecodable, HashStable)]
1223 /// A local (`let`) binding.
1226 /// An item binding.
1229 /// An expression without a trailing semi-colon (must have unit type).
1232 /// An expression with a trailing semi-colon (may have any type).
1237 pub fn attrs(&self) -> &[Attribute] {
1239 StmtKind::Local(ref l) => &l.attrs,
1240 StmtKind::Item(_) => &[],
1241 StmtKind::Expr(ref e) | StmtKind::Semi(ref e) => &e.attrs,
1246 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1247 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1250 /// Type annotation, if any (otherwise the type will be inferred).
1251 pub ty: Option<P<Ty>>,
1252 /// Initializer expression to set the value, if any.
1253 pub init: Option<P<Expr>>,
1257 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1258 /// desugaring. Otherwise will be `Normal`.
1259 pub source: LocalSource,
1262 /// Represents a single arm of a `match` expression, e.g.
1263 /// `<pat> (if <guard>) => <body>`.
1264 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1266 #[stable_hasher(ignore)]
1269 pub attrs: HirVec<Attribute>,
1270 /// If this pattern and the optional guard matches, then `body` is evaluated.
1272 /// Optional guard clause.
1273 pub guard: Option<Guard>,
1274 /// The expression the arm evaluates to if this arm matches.
1278 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1283 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1285 #[stable_hasher(ignore)]
1290 pub is_shorthand: bool,
1293 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1294 pub enum BlockCheckMode {
1296 UnsafeBlock(UnsafeSource),
1297 PushUnsafeBlock(UnsafeSource),
1298 PopUnsafeBlock(UnsafeSource),
1301 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1302 pub enum UnsafeSource {
1307 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1312 /// The body of a function, closure, or constant value. In the case of
1313 /// a function, the body contains not only the function body itself
1314 /// (which is an expression), but also the argument patterns, since
1315 /// those are something that the caller doesn't really care about.
1320 /// fn foo((x, y): (u32, u32)) -> u32 {
1325 /// Here, the `Body` associated with `foo()` would contain:
1327 /// - an `params` array containing the `(x, y)` pattern
1328 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1329 /// - `generator_kind` would be `None`
1331 /// All bodies have an **owner**, which can be accessed via the HIR
1332 /// map using `body_owner_def_id()`.
1333 #[derive(RustcEncodable, RustcDecodable, Debug)]
1334 pub struct Body<'hir> {
1335 pub params: &'hir [Param],
1337 pub generator_kind: Option<GeneratorKind>,
1341 pub fn id(&self) -> BodyId {
1342 BodyId { hir_id: self.value.hir_id }
1345 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1350 /// The type of source expression that caused this generator to be created.
1351 #[derive(Clone, PartialEq, Eq, HashStable, RustcEncodable, RustcDecodable, Debug, Copy)]
1352 pub enum GeneratorKind {
1353 /// An explicit `async` block or the body of an async function.
1354 Async(AsyncGeneratorKind),
1356 /// A generator literal created via a `yield` inside a closure.
1360 impl fmt::Display for GeneratorKind {
1361 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1363 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1364 GeneratorKind::Gen => f.write_str("generator"),
1369 /// In the case of a generator created as part of an async construct,
1370 /// which kind of async construct caused it to be created?
1372 /// This helps error messages but is also used to drive coercions in
1373 /// type-checking (see #60424).
1374 #[derive(Clone, PartialEq, Eq, HashStable, RustcEncodable, RustcDecodable, Debug, Copy)]
1375 pub enum AsyncGeneratorKind {
1376 /// An explicit `async` block written by the user.
1379 /// An explicit `async` block written by the user.
1382 /// The `async` block generated as the body of an async function.
1386 impl fmt::Display for AsyncGeneratorKind {
1387 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1388 f.write_str(match self {
1389 AsyncGeneratorKind::Block => "`async` block",
1390 AsyncGeneratorKind::Closure => "`async` closure body",
1391 AsyncGeneratorKind::Fn => "`async fn` body",
1396 #[derive(Copy, Clone, Debug)]
1397 pub enum BodyOwnerKind {
1398 /// Functions and methods.
1404 /// Constants and associated constants.
1407 /// Initializer of a `static` item.
1411 impl BodyOwnerKind {
1412 pub fn is_fn_or_closure(self) -> bool {
1414 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1415 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1421 pub type Lit = Spanned<LitKind>;
1423 /// A constant (expression) that's not an item or associated item,
1424 /// but needs its own `DefId` for type-checking, const-eval, etc.
1425 /// These are usually found nested inside types (e.g., array lengths)
1426 /// or expressions (e.g., repeat counts), and also used to define
1427 /// explicit discriminant values for enum variants.
1428 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1429 pub struct AnonConst {
1435 #[derive(RustcEncodable, RustcDecodable)]
1443 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1444 #[cfg(target_arch = "x86_64")]
1445 static_assert_size!(Expr, 64);
1448 pub fn precedence(&self) -> ExprPrecedence {
1450 ExprKind::Box(_) => ExprPrecedence::Box,
1451 ExprKind::Array(_) => ExprPrecedence::Array,
1452 ExprKind::Call(..) => ExprPrecedence::Call,
1453 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1454 ExprKind::Tup(_) => ExprPrecedence::Tup,
1455 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1456 ExprKind::Unary(..) => ExprPrecedence::Unary,
1457 ExprKind::Lit(_) => ExprPrecedence::Lit,
1458 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1459 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1460 ExprKind::Loop(..) => ExprPrecedence::Loop,
1461 ExprKind::Match(..) => ExprPrecedence::Match,
1462 ExprKind::Closure(..) => ExprPrecedence::Closure,
1463 ExprKind::Block(..) => ExprPrecedence::Block,
1464 ExprKind::Assign(..) => ExprPrecedence::Assign,
1465 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1466 ExprKind::Field(..) => ExprPrecedence::Field,
1467 ExprKind::Index(..) => ExprPrecedence::Index,
1468 ExprKind::Path(..) => ExprPrecedence::Path,
1469 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1470 ExprKind::Break(..) => ExprPrecedence::Break,
1471 ExprKind::Continue(..) => ExprPrecedence::Continue,
1472 ExprKind::Ret(..) => ExprPrecedence::Ret,
1473 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1474 ExprKind::Struct(..) => ExprPrecedence::Struct,
1475 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1476 ExprKind::Yield(..) => ExprPrecedence::Yield,
1477 ExprKind::Err => ExprPrecedence::Err,
1481 // Whether this looks like a place expr, without checking for deref
1483 // This will return `true` in some potentially surprising cases such as
1484 // `CONSTANT.field`.
1485 pub fn is_syntactic_place_expr(&self) -> bool {
1486 self.is_place_expr(|_| true)
1489 // Whether this is a place expression.
1490 // `allow_projections_from` should return `true` if indexing a field or
1491 // index expression based on the given expression should be considered a
1492 // place expression.
1493 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1495 ExprKind::Path(QPath::Resolved(_, ref path)) => match path.res {
1496 Res::Local(..) | Res::Def(DefKind::Static, _) | Res::Err => true,
1500 // Type ascription inherits its place expression kind from its
1502 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1503 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1505 ExprKind::Unary(UnDeref, _) => true,
1507 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1508 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1511 // Partially qualified paths in expressions can only legally
1512 // refer to associated items which are always rvalues.
1513 ExprKind::Path(QPath::TypeRelative(..))
1514 | ExprKind::Call(..)
1515 | ExprKind::MethodCall(..)
1516 | ExprKind::Struct(..)
1518 | ExprKind::Match(..)
1519 | ExprKind::Closure(..)
1520 | ExprKind::Block(..)
1521 | ExprKind::Repeat(..)
1522 | ExprKind::Array(..)
1523 | ExprKind::Break(..)
1524 | ExprKind::Continue(..)
1526 | ExprKind::Loop(..)
1527 | ExprKind::Assign(..)
1528 | ExprKind::InlineAsm(..)
1529 | ExprKind::AssignOp(..)
1531 | ExprKind::Unary(..)
1533 | ExprKind::AddrOf(..)
1534 | ExprKind::Binary(..)
1535 | ExprKind::Yield(..)
1536 | ExprKind::Cast(..)
1537 | ExprKind::DropTemps(..)
1538 | ExprKind::Err => false,
1542 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1543 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1544 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1545 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1546 /// beyond remembering to call this function before doing analysis on it.
1547 pub fn peel_drop_temps(&self) -> &Self {
1548 let mut expr = self;
1549 while let ExprKind::DropTemps(inner) = &expr.kind {
1556 impl fmt::Debug for Expr {
1557 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1562 print::to_string(print::NO_ANN, |s| s.print_expr(self))
1567 /// Checks if the specified expression is a built-in range literal.
1568 /// (See: `LoweringContext::lower_expr()`).
1570 /// FIXME(#60607): This function is a hack. If and when we have `QPath::Lang(...)`,
1571 /// we can use that instead as simpler, more reliable mechanism, as opposed to using `SourceMap`.
1572 pub fn is_range_literal(sm: &SourceMap, expr: &Expr) -> bool {
1573 // Returns whether the given path represents a (desugared) range,
1574 // either in std or core, i.e. has either a `::std::ops::Range` or
1575 // `::core::ops::Range` prefix.
1576 fn is_range_path(path: &Path) -> bool {
1577 let segs: Vec<_> = path.segments.iter().map(|seg| seg.ident.to_string()).collect();
1578 let segs: Vec<_> = segs.iter().map(|seg| &**seg).collect();
1580 // "{{root}}" is the equivalent of `::` prefix in `Path`.
1581 if let ["{{root}}", std_core, "ops", range] = segs.as_slice() {
1582 (*std_core == "std" || *std_core == "core") && range.starts_with("Range")
1588 // Check whether a span corresponding to a range expression is a
1589 // range literal, rather than an explicit struct or `new()` call.
1590 fn is_lit(sm: &SourceMap, span: &Span) -> bool {
1591 let end_point = sm.end_point(*span);
1593 if let Ok(end_string) = sm.span_to_snippet(end_point) {
1594 !(end_string.ends_with("}") || end_string.ends_with(")"))
1601 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1602 ExprKind::Struct(ref qpath, _, _) => {
1603 if let QPath::Resolved(None, ref path) = **qpath {
1604 return is_range_path(&path) && is_lit(sm, &expr.span);
1608 // `..` desugars to its struct path.
1609 ExprKind::Path(QPath::Resolved(None, ref path)) => {
1610 return is_range_path(&path) && is_lit(sm, &expr.span);
1613 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1614 ExprKind::Call(ref func, _) => {
1615 if let ExprKind::Path(QPath::TypeRelative(ref ty, ref segment)) = func.kind {
1616 if let TyKind::Path(QPath::Resolved(None, ref path)) = ty.kind {
1617 let new_call = segment.ident.name == sym::new;
1618 return is_range_path(&path) && is_lit(sm, &expr.span) && new_call;
1629 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1631 /// A `box x` expression.
1633 /// An array (e.g., `[a, b, c, d]`).
1634 Array(HirVec<Expr>),
1635 /// A function call.
1637 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1638 /// and the second field is the list of arguments.
1639 /// This also represents calling the constructor of
1640 /// tuple-like ADTs such as tuple structs and enum variants.
1641 Call(P<Expr>, HirVec<Expr>),
1642 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1644 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1645 /// (within the angle brackets).
1646 /// The first element of the vector of `Expr`s is the expression that evaluates
1647 /// to the object on which the method is being called on (the receiver),
1648 /// and the remaining elements are the rest of the arguments.
1649 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1650 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1652 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1653 /// the `hir_id` of the `MethodCall` node itself.
1655 /// [`type_dependent_def_id`]: ../ty/struct.TypeckTables.html#method.type_dependent_def_id
1656 MethodCall(P<PathSegment>, Span, HirVec<Expr>),
1657 /// A tuple (e.g., `(a, b, c, d)`).
1659 /// A binary operation (e.g., `a + b`, `a * b`).
1660 Binary(BinOp, P<Expr>, P<Expr>),
1661 /// A unary operation (e.g., `!x`, `*x`).
1662 Unary(UnOp, P<Expr>),
1663 /// A literal (e.g., `1`, `"foo"`).
1665 /// A cast (e.g., `foo as f64`).
1666 Cast(P<Expr>, P<Ty>),
1667 /// A type reference (e.g., `Foo`).
1668 Type(P<Expr>, P<Ty>),
1669 /// Wraps the expression in a terminating scope.
1670 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1672 /// This construct only exists to tweak the drop order in HIR lowering.
1673 /// An example of that is the desugaring of `for` loops.
1675 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1677 /// I.e., `'label: loop { <block> }`.
1678 Loop(P<Block>, Option<Label>, LoopSource),
1679 /// A `match` block, with a source that indicates whether or not it is
1680 /// the result of a desugaring, and if so, which kind.
1681 Match(P<Expr>, HirVec<Arm>, MatchSource),
1682 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1684 /// The `Span` is the argument block `|...|`.
1686 /// This may also be a generator literal or an `async block` as indicated by the
1687 /// `Option<Movability>`.
1688 Closure(CaptureBy, P<FnDecl>, BodyId, Span, Option<Movability>),
1689 /// A block (e.g., `'label: { ... }`).
1690 Block(P<Block>, Option<Label>),
1692 /// An assignment (e.g., `a = foo()`).
1693 /// The `Span` argument is the span of the `=` token.
1694 Assign(P<Expr>, P<Expr>, Span),
1695 /// An assignment with an operator.
1698 AssignOp(BinOp, P<Expr>, P<Expr>),
1699 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1700 Field(P<Expr>, Ident),
1701 /// An indexing operation (`foo[2]`).
1702 Index(P<Expr>, P<Expr>),
1704 /// Path to a definition, possibly containing lifetime or type parameters.
1707 /// A referencing operation (i.e., `&a`, `&mut a`, `&raw const a`, or `&raw mut a`).
1708 AddrOf(BorrowKind, Mutability, P<Expr>),
1709 /// A `break`, with an optional label to break.
1710 Break(Destination, Option<P<Expr>>),
1711 /// A `continue`, with an optional label.
1712 Continue(Destination),
1713 /// A `return`, with an optional value to be returned.
1714 Ret(Option<P<Expr>>),
1716 /// Inline assembly (from `asm!`), with its outputs and inputs.
1717 InlineAsm(P<InlineAsm>),
1719 /// A struct or struct-like variant literal expression.
1721 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1722 /// where `base` is the `Option<Expr>`.
1723 Struct(P<QPath>, HirVec<Field>, Option<P<Expr>>),
1725 /// An array literal constructed from one repeated element.
1727 /// E.g., `[1; 5]`. The first expression is the element
1728 /// to be repeated; the second is the number of times to repeat it.
1729 Repeat(P<Expr>, AnonConst),
1731 /// A suspension point for generators (i.e., `yield <expr>`).
1732 Yield(P<Expr>, YieldSource),
1734 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1738 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1740 /// To resolve the path to a `DefId`, call [`qpath_res`].
1742 /// [`qpath_res`]: ../ty/struct.TypeckTables.html#method.qpath_res
1743 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1745 /// Path to a definition, optionally "fully-qualified" with a `Self`
1746 /// type, if the path points to an associated item in a trait.
1748 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1749 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1750 /// even though they both have the same two-segment `Clone::clone` `Path`.
1751 Resolved(Option<P<Ty>>, P<Path>),
1753 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1754 /// Will be resolved by type-checking to an associated item.
1756 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1757 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1758 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1759 TypeRelative(P<Ty>, P<PathSegment>),
1762 /// Hints at the original code for a let statement.
1763 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1764 pub enum LocalSource {
1765 /// A `match _ { .. }`.
1767 /// A desugared `for _ in _ { .. }` loop.
1769 /// When lowering async functions, we create locals within the `async move` so that
1770 /// all parameters are dropped after the future is polled.
1772 /// ```ignore (pseudo-Rust)
1773 /// async fn foo(<pattern> @ x: Type) {
1775 /// let <pattern> = x;
1780 /// A desugared `<expr>.await`.
1784 /// Hints at the original code for a `match _ { .. }`.
1785 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
1786 pub enum MatchSource {
1787 /// A `match _ { .. }`.
1789 /// An `if _ { .. }` (optionally with `else { .. }`).
1790 IfDesugar { contains_else_clause: bool },
1791 /// An `if let _ = _ { .. }` (optionally with `else { .. }`).
1792 IfLetDesugar { contains_else_clause: bool },
1793 /// A `while _ { .. }` (which was desugared to a `loop { match _ { .. } }`).
1795 /// A `while let _ = _ { .. }` (which was desugared to a
1796 /// `loop { match _ { .. } }`).
1798 /// A desugared `for _ in _ { .. }` loop.
1800 /// A desugared `?` operator.
1802 /// A desugared `<expr>.await`.
1807 pub fn name(self) -> &'static str {
1811 IfDesugar { .. } | IfLetDesugar { .. } => "if",
1812 WhileDesugar | WhileLetDesugar => "while",
1813 ForLoopDesugar => "for",
1815 AwaitDesugar => ".await",
1820 /// The loop type that yielded an `ExprKind::Loop`.
1821 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1822 pub enum LoopSource {
1823 /// A `loop { .. }` loop.
1825 /// A `while _ { .. }` loop.
1827 /// A `while let _ = _ { .. }` loop.
1829 /// A `for _ in _ { .. }` loop.
1834 pub fn name(self) -> &'static str {
1836 LoopSource::Loop => "loop",
1837 LoopSource::While | LoopSource::WhileLet => "while",
1838 LoopSource::ForLoop => "for",
1843 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1844 pub enum LoopIdError {
1846 UnlabeledCfInWhileCondition,
1850 impl fmt::Display for LoopIdError {
1851 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1852 f.write_str(match self {
1853 LoopIdError::OutsideLoopScope => "not inside loop scope",
1854 LoopIdError::UnlabeledCfInWhileCondition => {
1855 "unlabeled control flow (break or continue) in while condition"
1857 LoopIdError::UnresolvedLabel => "label not found",
1862 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1863 pub struct Destination {
1864 // This is `Some(_)` iff there is an explicit user-specified `label
1865 pub label: Option<Label>,
1867 // These errors are caught and then reported during the diagnostics pass in
1868 // librustc_passes/loops.rs
1869 pub target_id: Result<HirId, LoopIdError>,
1872 /// The yield kind that caused an `ExprKind::Yield`.
1873 #[derive(Copy, Clone, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable, HashStable)]
1874 pub enum YieldSource {
1875 /// An `<expr>.await`.
1877 /// A plain `yield`.
1881 impl fmt::Display for YieldSource {
1882 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1883 f.write_str(match self {
1884 YieldSource::Await => "`await`",
1885 YieldSource::Yield => "`yield`",
1890 impl From<GeneratorKind> for YieldSource {
1891 fn from(kind: GeneratorKind) -> Self {
1893 // Guess based on the kind of the current generator.
1894 GeneratorKind::Gen => Self::Yield,
1895 GeneratorKind::Async(_) => Self::Await,
1900 // N.B., if you change this, you'll probably want to change the corresponding
1901 // type structure in middle/ty.rs as well.
1902 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1905 pub mutbl: Mutability,
1908 /// Represents a function's signature in a trait declaration,
1909 /// trait implementation, or a free function.
1910 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1912 pub header: FnHeader,
1913 pub decl: P<FnDecl>,
1916 // The bodies for items are stored "out of line", in a separate
1917 // hashmap in the `Crate`. Here we just record the node-id of the item
1918 // so it can fetched later.
1919 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1920 pub struct TraitItemId {
1924 /// Represents an item declaration within a trait declaration,
1925 /// possibly including a default implementation. A trait item is
1926 /// either required (meaning it doesn't have an implementation, just a
1927 /// signature) or provided (meaning it has a default implementation).
1928 #[derive(RustcEncodable, RustcDecodable, Debug)]
1929 pub struct TraitItem<'hir> {
1932 pub attrs: &'hir [Attribute],
1933 pub generics: Generics,
1934 pub kind: TraitItemKind<'hir>,
1938 /// Represents a trait method's body (or just argument names).
1939 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1940 pub enum TraitMethod {
1941 /// No default body in the trait, just a signature.
1942 Required(HirVec<Ident>),
1944 /// Both signature and body are provided in the trait.
1948 /// Represents a trait method or associated constant or type
1949 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1950 pub enum TraitItemKind<'hir> {
1951 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
1952 Const(&'hir Ty, Option<BodyId>),
1953 /// A method with an optional body.
1954 Method(FnSig, TraitMethod),
1955 /// An associated type with (possibly empty) bounds and optional concrete
1957 Type(GenericBounds, Option<&'hir Ty>),
1960 // The bodies for items are stored "out of line", in a separate
1961 // hashmap in the `Crate`. Here we just record the node-id of the item
1962 // so it can fetched later.
1963 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1964 pub struct ImplItemId {
1968 /// Represents anything within an `impl` block.
1969 #[derive(RustcEncodable, RustcDecodable, Debug)]
1970 pub struct ImplItem<'hir> {
1973 pub vis: Visibility,
1974 pub defaultness: Defaultness,
1975 pub attrs: &'hir [Attribute],
1976 pub generics: Generics,
1977 pub kind: ImplItemKind<'hir>,
1981 /// Represents various kinds of content within an `impl`.
1982 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1983 pub enum ImplItemKind<'hir> {
1984 /// An associated constant of the given type, set to the constant result
1985 /// of the expression.
1986 Const(&'hir Ty, BodyId),
1987 /// A method implementation with the given signature and body.
1988 Method(FnSig, BodyId),
1989 /// An associated type.
1991 /// An associated `type = impl Trait`.
1992 OpaqueTy(GenericBounds),
1995 /// Bind a type to an associated type (i.e., `A = Foo`).
1997 /// Bindings like `A: Debug` are represented as a special type `A =
1998 /// $::Debug` that is understood by the astconv code.
2000 /// FIXME(alexreg): why have a separate type for the binding case,
2001 /// wouldn't it be better to make the `ty` field an enum like the
2005 /// enum TypeBindingKind {
2010 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2011 pub struct TypeBinding {
2013 #[stable_hasher(project(name))]
2015 pub kind: TypeBindingKind,
2019 // Represents the two kinds of type bindings.
2020 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2021 pub enum TypeBindingKind {
2022 /// E.g., `Foo<Bar: Send>`.
2023 Constraint { bounds: HirVec<GenericBound> },
2024 /// E.g., `Foo<Bar = ()>`.
2025 Equality { ty: P<Ty> },
2029 pub fn ty(&self) -> &Ty {
2031 TypeBindingKind::Equality { ref ty } => ty,
2032 _ => bug!("expected equality type binding for parenthesized generic args"),
2037 #[derive(RustcEncodable, RustcDecodable)]
2044 impl fmt::Debug for Ty {
2045 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2046 write!(f, "type({})", print::to_string(print::NO_ANN, |s| s.print_type(self)))
2050 /// Not represented directly in the AST; referred to by name through a `ty_path`.
2051 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
2061 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2062 pub struct BareFnTy {
2063 pub unsafety: Unsafety,
2065 pub generic_params: HirVec<GenericParam>,
2066 pub decl: P<FnDecl>,
2067 pub param_names: HirVec<Ident>,
2070 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2071 pub struct OpaqueTy {
2072 pub generics: Generics,
2073 pub bounds: GenericBounds,
2074 pub impl_trait_fn: Option<DefId>,
2075 pub origin: OpaqueTyOrigin,
2078 /// From whence the opaque type came.
2079 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2080 pub enum OpaqueTyOrigin {
2081 /// `type Foo = impl Trait;`
2089 /// The various kinds of types recognized by the compiler.
2090 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2092 /// A variable length slice (i.e., `[T]`).
2094 /// A fixed length array (i.e., `[T; n]`).
2095 Array(P<Ty>, AnonConst),
2096 /// A raw pointer (i.e., `*const T` or `*mut T`).
2098 /// A reference (i.e., `&'a T` or `&'a mut T`).
2099 Rptr(Lifetime, MutTy),
2100 /// A bare function (e.g., `fn(usize) -> bool`).
2101 BareFn(P<BareFnTy>),
2102 /// The never type (`!`).
2104 /// A tuple (`(A, B, C, D, ...)`).
2106 /// A path to a type definition (`module::module::...::Type`), or an
2107 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2109 /// Type parameters may be stored in each `PathSegment`.
2111 /// A type definition itself. This is currently only used for the `type Foo = impl Trait`
2112 /// item that `impl Trait` in return position desugars to.
2114 /// The generic argument list contains the lifetimes (and in the future possibly parameters)
2115 /// that are actually bound on the `impl Trait`.
2116 Def(ItemId, HirVec<GenericArg>),
2117 /// A trait object type `Bound1 + Bound2 + Bound3`
2118 /// where `Bound` is a trait or a lifetime.
2119 TraitObject(HirVec<PolyTraitRef>, Lifetime),
2122 /// `TyKind::Infer` means the type should be inferred instead of it having been
2123 /// specified. This can appear anywhere in a type.
2125 /// Placeholder for a type that has failed to be defined.
2129 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable, PartialEq)]
2130 pub struct InlineAsmOutput {
2131 pub constraint: Symbol,
2133 pub is_indirect: bool,
2137 // NOTE(eddyb) This is used within MIR as well, so unlike the rest of the HIR,
2138 // it needs to be `Clone` and use plain `Vec<T>` instead of `HirVec<T>`.
2139 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable, PartialEq)]
2140 pub struct InlineAsmInner {
2142 pub asm_str_style: StrStyle,
2143 pub outputs: Vec<InlineAsmOutput>,
2144 pub inputs: Vec<Symbol>,
2145 pub clobbers: Vec<Symbol>,
2147 pub alignstack: bool,
2148 pub dialect: AsmDialect,
2151 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2152 pub struct InlineAsm {
2153 pub inner: InlineAsmInner,
2154 pub outputs_exprs: HirVec<Expr>,
2155 pub inputs_exprs: HirVec<Expr>,
2158 /// Represents a parameter in a function header.
2159 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2161 pub attrs: HirVec<Attribute>,
2167 /// Represents the header (not the body) of a function declaration.
2168 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2170 /// The types of the function's parameters.
2172 /// Additional argument data is stored in the function's [body](Body::parameters).
2173 pub inputs: HirVec<Ty>,
2174 pub output: FunctionRetTy,
2175 pub c_variadic: bool,
2176 /// Does the function have an implicit self?
2177 pub implicit_self: ImplicitSelfKind,
2180 /// Represents what type of implicit self a function has, if any.
2181 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2182 pub enum ImplicitSelfKind {
2183 /// Represents a `fn x(self);`.
2185 /// Represents a `fn x(mut self);`.
2187 /// Represents a `fn x(&self);`.
2189 /// Represents a `fn x(&mut self);`.
2191 /// Represents when a function does not have a self argument or
2192 /// when a function has a `self: X` argument.
2196 impl ImplicitSelfKind {
2197 /// Does this represent an implicit self?
2198 pub fn has_implicit_self(&self) -> bool {
2200 ImplicitSelfKind::None => false,
2223 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2224 pub enum Defaultness {
2225 Default { has_value: bool },
2230 pub fn has_value(&self) -> bool {
2232 Defaultness::Default { has_value, .. } => has_value,
2233 Defaultness::Final => true,
2237 pub fn is_final(&self) -> bool {
2238 *self == Defaultness::Final
2241 pub fn is_default(&self) -> bool {
2243 Defaultness::Default { .. } => true,
2249 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2250 pub enum FunctionRetTy {
2251 /// Return type is not specified.
2253 /// Functions default to `()` and
2254 /// closures default to inference. Span points to where return
2255 /// type would be inserted.
2256 DefaultReturn(Span),
2257 /// Everything else.
2261 impl fmt::Display for FunctionRetTy {
2262 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2264 Return(ref ty) => print::to_string(print::NO_ANN, |s| s.print_type(ty)).fmt(f),
2265 DefaultReturn(_) => "()".fmt(f),
2270 impl FunctionRetTy {
2271 pub fn span(&self) -> Span {
2273 DefaultReturn(span) => span,
2274 Return(ref ty) => ty.span,
2279 #[derive(RustcEncodable, RustcDecodable, Debug)]
2280 pub struct Mod<'hir> {
2281 /// A span from the first token past `{` to the last token until `}`.
2282 /// For `mod foo;`, the inner span ranges from the first token
2283 /// to the last token in the external file.
2285 pub item_ids: &'hir [ItemId],
2288 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2289 pub struct ForeignMod<'hir> {
2291 pub items: &'hir [ForeignItem<'hir>],
2294 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2295 pub struct GlobalAsm {
2299 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2300 pub struct EnumDef<'hir> {
2301 pub variants: &'hir [Variant<'hir>],
2304 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2305 pub struct Variant<'hir> {
2306 /// Name of the variant.
2307 #[stable_hasher(project(name))]
2309 /// Attributes of the variant.
2310 pub attrs: &'hir [Attribute],
2311 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2313 /// Fields and constructor id of the variant.
2314 pub data: VariantData<'hir>,
2315 /// Explicit discriminant (e.g., `Foo = 1`).
2316 pub disr_expr: Option<AnonConst>,
2321 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2323 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2324 /// Also produced for each element of a list `use`, e.g.
2325 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2328 /// Glob import, e.g., `use foo::*`.
2331 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2332 /// an additional `use foo::{}` for performing checks such as
2333 /// unstable feature gating. May be removed in the future.
2337 /// References to traits in impls.
2339 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2340 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2341 /// trait being referred to but just a unique `HirId` that serves as a key
2342 /// within the resolution map.
2343 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2344 pub struct TraitRef {
2346 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2347 #[stable_hasher(ignore)]
2348 pub hir_ref_id: HirId,
2352 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2353 pub fn trait_def_id(&self) -> DefId {
2354 match self.path.res {
2355 Res::Def(DefKind::Trait, did) => did,
2356 Res::Def(DefKind::TraitAlias, did) => did,
2360 _ => unreachable!(),
2365 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2366 pub struct PolyTraitRef {
2367 /// The `'a` in `<'a> Foo<&'a T>`.
2368 pub bound_generic_params: HirVec<GenericParam>,
2370 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2371 pub trait_ref: TraitRef,
2376 pub type Visibility = Spanned<VisibilityKind>;
2378 #[derive(RustcEncodable, RustcDecodable, Debug)]
2379 pub enum VisibilityKind {
2382 Restricted { path: P<Path>, hir_id: HirId },
2386 impl VisibilityKind {
2387 pub fn is_pub(&self) -> bool {
2389 VisibilityKind::Public => true,
2394 pub fn is_pub_restricted(&self) -> bool {
2396 VisibilityKind::Public | VisibilityKind::Inherited => false,
2397 VisibilityKind::Crate(..) | VisibilityKind::Restricted { .. } => true,
2401 pub fn descr(&self) -> &'static str {
2403 VisibilityKind::Public => "public",
2404 VisibilityKind::Inherited => "private",
2405 VisibilityKind::Crate(..) => "crate-visible",
2406 VisibilityKind::Restricted { .. } => "restricted",
2411 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2412 pub struct StructField<'hir> {
2414 #[stable_hasher(project(name))]
2416 pub vis: Visibility,
2419 pub attrs: &'hir [Attribute],
2422 impl StructField<'_> {
2423 // Still necessary in couple of places
2424 pub fn is_positional(&self) -> bool {
2425 let first = self.ident.as_str().as_bytes()[0];
2426 first >= b'0' && first <= b'9'
2430 /// Fields and constructor IDs of enum variants and structs.
2431 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2432 pub enum VariantData<'hir> {
2433 /// A struct variant.
2435 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2436 Struct(&'hir [StructField<'hir>], /* recovered */ bool),
2437 /// A tuple variant.
2439 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2440 Tuple(&'hir [StructField<'hir>], HirId),
2443 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2447 impl VariantData<'hir> {
2448 /// Return the fields of this variant.
2449 pub fn fields(&self) -> &'hir [StructField<'hir>] {
2451 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2456 /// Return the `HirId` of this variant's constructor, if it has one.
2457 pub fn ctor_hir_id(&self) -> Option<HirId> {
2459 VariantData::Struct(_, _) => None,
2460 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2465 // The bodies for items are stored "out of line", in a separate
2466 // hashmap in the `Crate`. Here we just record the node-id of the item
2467 // so it can fetched later.
2468 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2475 /// The name might be a dummy name in case of anonymous items
2476 #[derive(RustcEncodable, RustcDecodable, Debug)]
2477 pub struct Item<'hir> {
2480 pub attrs: &'hir [Attribute],
2481 pub kind: ItemKind<'hir>,
2482 pub vis: Visibility,
2486 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2487 pub struct FnHeader {
2488 pub unsafety: Unsafety,
2489 pub constness: Constness,
2490 pub asyncness: IsAsync,
2495 pub fn is_const(&self) -> bool {
2496 match &self.constness {
2497 Constness::Const => true,
2503 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2504 pub enum ItemKind<'hir> {
2505 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2507 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2508 ExternCrate(Option<Name>),
2510 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2514 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2515 Use(&'hir Path, UseKind),
2517 /// A `static` item.
2518 Static(&'hir Ty, Mutability, BodyId),
2520 Const(&'hir Ty, BodyId),
2521 /// A function declaration.
2522 Fn(FnSig, Generics, BodyId),
2525 /// An external module, e.g. `extern { .. }`.
2526 ForeignMod(ForeignMod<'hir>),
2527 /// Module-level inline assembly (from `global_asm!`).
2528 GlobalAsm(&'hir GlobalAsm),
2529 /// A type alias, e.g., `type Foo = Bar<u8>`.
2530 TyAlias(&'hir Ty, Generics),
2531 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2533 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2534 Enum(EnumDef<'hir>, Generics),
2535 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2536 Struct(VariantData<'hir>, Generics),
2537 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2538 Union(VariantData<'hir>, Generics),
2539 /// A trait definition.
2540 Trait(IsAuto, Unsafety, Generics, GenericBounds, &'hir [TraitItemRef]),
2542 TraitAlias(Generics, GenericBounds),
2544 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2550 Option<TraitRef>, // (optional) trait this impl implements
2552 &'hir [ImplItemRef],
2557 pub fn descriptive_variant(&self) -> &str {
2559 ItemKind::ExternCrate(..) => "extern crate",
2560 ItemKind::Use(..) => "use",
2561 ItemKind::Static(..) => "static item",
2562 ItemKind::Const(..) => "constant item",
2563 ItemKind::Fn(..) => "function",
2564 ItemKind::Mod(..) => "module",
2565 ItemKind::ForeignMod(..) => "foreign module",
2566 ItemKind::GlobalAsm(..) => "global asm",
2567 ItemKind::TyAlias(..) => "type alias",
2568 ItemKind::OpaqueTy(..) => "opaque type",
2569 ItemKind::Enum(..) => "enum",
2570 ItemKind::Struct(..) => "struct",
2571 ItemKind::Union(..) => "union",
2572 ItemKind::Trait(..) => "trait",
2573 ItemKind::TraitAlias(..) => "trait alias",
2574 ItemKind::Impl(..) => "impl",
2578 pub fn adt_kind(&self) -> Option<AdtKind> {
2580 ItemKind::Struct(..) => Some(AdtKind::Struct),
2581 ItemKind::Union(..) => Some(AdtKind::Union),
2582 ItemKind::Enum(..) => Some(AdtKind::Enum),
2587 pub fn generics(&self) -> Option<&Generics> {
2589 ItemKind::Fn(_, ref generics, _)
2590 | ItemKind::TyAlias(_, ref generics)
2591 | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
2592 | ItemKind::Enum(_, ref generics)
2593 | ItemKind::Struct(_, ref generics)
2594 | ItemKind::Union(_, ref generics)
2595 | ItemKind::Trait(_, _, ref generics, _, _)
2596 | ItemKind::Impl(_, _, _, ref generics, _, _, _) => generics,
2602 /// A reference from an trait to one of its associated items. This
2603 /// contains the item's id, naturally, but also the item's name and
2604 /// some other high-level details (like whether it is an associated
2605 /// type or method, and whether it is public). This allows other
2606 /// passes to find the impl they want without loading the ID (which
2607 /// means fewer edges in the incremental compilation graph).
2608 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2609 pub struct TraitItemRef {
2610 pub id: TraitItemId,
2611 #[stable_hasher(project(name))]
2613 pub kind: AssocItemKind,
2615 pub defaultness: Defaultness,
2618 /// A reference from an impl to one of its associated items. This
2619 /// contains the item's ID, naturally, but also the item's name and
2620 /// some other high-level details (like whether it is an associated
2621 /// type or method, and whether it is public). This allows other
2622 /// passes to find the impl they want without loading the ID (which
2623 /// means fewer edges in the incremental compilation graph).
2624 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2625 pub struct ImplItemRef {
2627 #[stable_hasher(project(name))]
2629 pub kind: AssocItemKind,
2631 pub vis: Visibility,
2632 pub defaultness: Defaultness,
2635 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2636 pub enum AssocItemKind {
2638 Method { has_self: bool },
2643 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2644 pub struct ForeignItem<'hir> {
2645 #[stable_hasher(project(name))]
2647 pub attrs: &'hir [Attribute],
2648 pub kind: ForeignItemKind<'hir>,
2651 pub vis: Visibility,
2654 /// An item within an `extern` block.
2655 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2656 pub enum ForeignItemKind<'hir> {
2657 /// A foreign function.
2658 Fn(&'hir FnDecl, &'hir [Ident], Generics),
2659 /// A foreign static item (`static ext: u8`).
2660 Static(&'hir Ty, Mutability),
2665 impl ForeignItemKind<'hir> {
2666 pub fn descriptive_variant(&self) -> &str {
2668 ForeignItemKind::Fn(..) => "foreign function",
2669 ForeignItemKind::Static(..) => "foreign static item",
2670 ForeignItemKind::Type => "foreign type",
2675 /// A variable captured by a closure.
2676 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable, HashStable)]
2678 // First span where it is accessed (there can be multiple).
2682 pub type CaptureModeMap = NodeMap<CaptureBy>;
2684 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2685 // has length > 0 if the trait is found through an chain of imports, starting with the
2686 // import/use statement in the scope where the trait is used.
2687 #[derive(Clone, Debug)]
2688 pub struct TraitCandidate {
2690 pub import_ids: SmallVec<[NodeId; 1]>,
2693 // Trait method resolution
2694 pub type TraitMap = NodeMap<Vec<TraitCandidate>>;
2696 // Map from the NodeId of a glob import to a list of items which are actually
2698 pub type GlobMap = NodeMap<FxHashSet<Name>>;
2700 pub fn provide(providers: &mut Providers<'_>) {
2701 check_attr::provide(providers);
2702 map::provide(providers);
2703 upvars::provide(providers);
2706 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
2707 pub struct CodegenFnAttrs {
2708 pub flags: CodegenFnAttrFlags,
2709 /// Parsed representation of the `#[inline]` attribute
2710 pub inline: InlineAttr,
2711 /// Parsed representation of the `#[optimize]` attribute
2712 pub optimize: OptimizeAttr,
2713 /// The `#[export_name = "..."]` attribute, indicating a custom symbol a
2714 /// function should be exported under
2715 pub export_name: Option<Symbol>,
2716 /// The `#[link_name = "..."]` attribute, indicating a custom symbol an
2717 /// imported function should be imported as. Note that `export_name`
2718 /// probably isn't set when this is set, this is for foreign items while
2719 /// `#[export_name]` is for Rust-defined functions.
2720 pub link_name: Option<Symbol>,
2721 /// The `#[link_ordinal = "..."]` attribute, indicating an ordinal an
2722 /// imported function has in the dynamic library. Note that this must not
2723 /// be set when `link_name` is set. This is for foreign items with the
2724 /// "raw-dylib" kind.
2725 pub link_ordinal: Option<usize>,
2726 /// The `#[target_feature(enable = "...")]` attribute and the enabled
2727 /// features (only enabled features are supported right now).
2728 pub target_features: Vec<Symbol>,
2729 /// The `#[linkage = "..."]` attribute and the value we found.
2730 pub linkage: Option<Linkage>,
2731 /// The `#[link_section = "..."]` attribute, or what executable section this
2732 /// should be placed in.
2733 pub link_section: Option<Symbol>,
2737 #[derive(RustcEncodable, RustcDecodable, HashStable)]
2738 pub struct CodegenFnAttrFlags: u32 {
2739 /// `#[cold]`: a hint to LLVM that this function, when called, is never on
2741 const COLD = 1 << 0;
2742 /// `#[rustc_allocator]`: a hint to LLVM that the pointer returned from this
2743 /// function is never null.
2744 const ALLOCATOR = 1 << 1;
2745 /// `#[unwind]`: an indicator that this function may unwind despite what
2746 /// its ABI signature may otherwise imply.
2747 const UNWIND = 1 << 2;
2748 /// `#[rust_allocator_nounwind]`, an indicator that an imported FFI
2749 /// function will never unwind. Probably obsolete by recent changes with
2750 /// #[unwind], but hasn't been removed/migrated yet
2751 const RUSTC_ALLOCATOR_NOUNWIND = 1 << 3;
2752 /// `#[naked]`: an indicator to LLVM that no function prologue/epilogue
2753 /// should be generated.
2754 const NAKED = 1 << 4;
2755 /// `#[no_mangle]`: an indicator that the function's name should be the same
2757 const NO_MANGLE = 1 << 5;
2758 /// `#[rustc_std_internal_symbol]`: an indicator that this symbol is a
2759 /// "weird symbol" for the standard library in that it has slightly
2760 /// different linkage, visibility, and reachability rules.
2761 const RUSTC_STD_INTERNAL_SYMBOL = 1 << 6;
2762 /// `#[no_debug]`: an indicator that no debugging information should be
2763 /// generated for this function by LLVM.
2764 const NO_DEBUG = 1 << 7;
2765 /// `#[thread_local]`: indicates a static is actually a thread local
2767 const THREAD_LOCAL = 1 << 8;
2768 /// `#[used]`: indicates that LLVM can't eliminate this function (but the
2770 const USED = 1 << 9;
2771 /// `#[ffi_returns_twice]`, indicates that an extern function can return
2773 const FFI_RETURNS_TWICE = 1 << 10;
2774 /// `#[track_caller]`: allow access to the caller location
2775 const TRACK_CALLER = 1 << 11;
2779 impl CodegenFnAttrs {
2780 pub fn new() -> CodegenFnAttrs {
2782 flags: CodegenFnAttrFlags::empty(),
2783 inline: InlineAttr::None,
2784 optimize: OptimizeAttr::None,
2788 target_features: vec![],
2794 /// Returns `true` if `#[inline]` or `#[inline(always)]` is present.
2795 pub fn requests_inline(&self) -> bool {
2797 InlineAttr::Hint | InlineAttr::Always => true,
2798 InlineAttr::None | InlineAttr::Never => false,
2802 /// Returns `true` if it looks like this symbol needs to be exported, for example:
2804 /// * `#[no_mangle]` is present
2805 /// * `#[export_name(...)]` is present
2806 /// * `#[linkage]` is present
2807 pub fn contains_extern_indicator(&self) -> bool {
2808 self.flags.contains(CodegenFnAttrFlags::NO_MANGLE)
2809 || self.export_name.is_some()
2810 || match self.linkage {
2811 // These are private, so make sure we don't try to consider
2813 None | Some(Linkage::Internal) | Some(Linkage::Private) => false,
2819 #[derive(Copy, Clone, Debug)]
2820 pub enum Node<'hir> {
2822 Item(&'hir Item<'hir>),
2823 ForeignItem(&'hir ForeignItem<'hir>),
2824 TraitItem(&'hir TraitItem<'hir>),
2825 ImplItem(&'hir ImplItem<'hir>),
2826 Variant(&'hir Variant<'hir>),
2827 Field(&'hir StructField<'hir>),
2828 AnonConst(&'hir AnonConst),
2831 PathSegment(&'hir PathSegment),
2833 TraitRef(&'hir TraitRef),
2839 MacroDef(&'hir MacroDef<'hir>),
2841 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
2842 /// with synthesized constructors.
2843 Ctor(&'hir VariantData<'hir>),
2845 Lifetime(&'hir Lifetime),
2846 GenericParam(&'hir GenericParam),
2847 Visibility(&'hir Visibility),
2853 pub fn ident(&self) -> Option<Ident> {
2855 Node::TraitItem(TraitItem { ident, .. })
2856 | Node::ImplItem(ImplItem { ident, .. })
2857 | Node::ForeignItem(ForeignItem { ident, .. })
2858 | Node::Item(Item { ident, .. }) => Some(*ident),