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) {
925 /// Walk the pattern in left-to-right order.
927 /// If you always want to recurse, prefer this method over `walk`.
928 pub fn walk_always(&self, mut it: impl FnMut(&Pat)) {
936 /// A single field in a struct pattern.
938 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
939 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
940 /// except `is_shorthand` is true.
941 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
942 pub struct FieldPat {
943 #[stable_hasher(ignore)]
945 /// The identifier for the field.
946 #[stable_hasher(project(name))]
948 /// The pattern the field is destructured to.
950 pub is_shorthand: bool,
954 /// Explicit binding annotations given in the HIR for a binding. Note
955 /// that this is not the final binding *mode* that we infer after type
957 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
958 pub enum BindingAnnotation {
959 /// No binding annotation given: this means that the final binding mode
960 /// will depend on whether we have skipped through a `&` reference
961 /// when matching. For example, the `x` in `Some(x)` will have binding
962 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
963 /// ultimately be inferred to be by-reference.
965 /// Note that implicit reference skipping is not implemented yet (#42640).
968 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
971 /// Annotated as `ref`, like `ref x`
974 /// Annotated as `ref mut x`.
978 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
984 impl fmt::Display for RangeEnd {
985 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
986 f.write_str(match self {
987 RangeEnd::Included => "..=",
988 RangeEnd::Excluded => "..",
993 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
995 /// Represents a wildcard pattern (i.e., `_`).
998 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
999 /// The `HirId` is the canonical ID for the variable being bound,
1000 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
1001 /// which is the pattern ID of the first `x`.
1002 Binding(BindingAnnotation, HirId, Ident, Option<P<Pat>>),
1004 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
1005 /// The `bool` is `true` in the presence of a `..`.
1006 Struct(QPath, HirVec<FieldPat>, bool),
1008 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
1009 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
1010 /// `0 <= position <= subpats.len()`
1011 TupleStruct(QPath, HirVec<P<Pat>>, Option<usize>),
1013 /// An or-pattern `A | B | C`.
1014 /// Invariant: `pats.len() >= 2`.
1017 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
1020 /// A tuple pattern (e.g., `(a, b)`).
1021 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
1022 /// `0 <= position <= subpats.len()`
1023 Tuple(HirVec<P<Pat>>, Option<usize>),
1025 /// A `box` pattern.
1028 /// A reference pattern (e.g., `&mut (a, b)`).
1029 Ref(P<Pat>, Mutability),
1034 /// A range pattern (e.g., `1..=2` or `1..2`).
1035 Range(P<Expr>, P<Expr>, RangeEnd),
1037 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
1039 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
1040 /// If `slice` exists, then `after` can be non-empty.
1042 /// The representation for e.g., `[a, b, .., c, d]` is:
1044 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
1046 Slice(HirVec<P<Pat>>, Option<P<Pat>>, HirVec<P<Pat>>),
1049 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1050 pub enum BinOpKind {
1051 /// The `+` operator (addition).
1053 /// The `-` operator (subtraction).
1055 /// The `*` operator (multiplication).
1057 /// The `/` operator (division).
1059 /// The `%` operator (modulus).
1061 /// The `&&` operator (logical and).
1063 /// The `||` operator (logical or).
1065 /// The `^` operator (bitwise xor).
1067 /// The `&` operator (bitwise and).
1069 /// The `|` operator (bitwise or).
1071 /// The `<<` operator (shift left).
1073 /// The `>>` operator (shift right).
1075 /// The `==` operator (equality).
1077 /// The `<` operator (less than).
1079 /// The `<=` operator (less than or equal to).
1081 /// The `!=` operator (not equal to).
1083 /// The `>=` operator (greater than or equal to).
1085 /// The `>` operator (greater than).
1090 pub fn as_str(self) -> &'static str {
1092 BinOpKind::Add => "+",
1093 BinOpKind::Sub => "-",
1094 BinOpKind::Mul => "*",
1095 BinOpKind::Div => "/",
1096 BinOpKind::Rem => "%",
1097 BinOpKind::And => "&&",
1098 BinOpKind::Or => "||",
1099 BinOpKind::BitXor => "^",
1100 BinOpKind::BitAnd => "&",
1101 BinOpKind::BitOr => "|",
1102 BinOpKind::Shl => "<<",
1103 BinOpKind::Shr => ">>",
1104 BinOpKind::Eq => "==",
1105 BinOpKind::Lt => "<",
1106 BinOpKind::Le => "<=",
1107 BinOpKind::Ne => "!=",
1108 BinOpKind::Ge => ">=",
1109 BinOpKind::Gt => ">",
1113 pub fn is_lazy(self) -> bool {
1115 BinOpKind::And | BinOpKind::Or => true,
1120 pub fn is_shift(self) -> bool {
1122 BinOpKind::Shl | BinOpKind::Shr => true,
1127 pub fn is_comparison(self) -> bool {
1134 | BinOpKind::Ge => true,
1146 | BinOpKind::Shr => false,
1150 /// Returns `true` if the binary operator takes its arguments by value.
1151 pub fn is_by_value(self) -> bool {
1152 !self.is_comparison()
1156 impl Into<ast::BinOpKind> for BinOpKind {
1157 fn into(self) -> ast::BinOpKind {
1159 BinOpKind::Add => ast::BinOpKind::Add,
1160 BinOpKind::Sub => ast::BinOpKind::Sub,
1161 BinOpKind::Mul => ast::BinOpKind::Mul,
1162 BinOpKind::Div => ast::BinOpKind::Div,
1163 BinOpKind::Rem => ast::BinOpKind::Rem,
1164 BinOpKind::And => ast::BinOpKind::And,
1165 BinOpKind::Or => ast::BinOpKind::Or,
1166 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1167 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1168 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1169 BinOpKind::Shl => ast::BinOpKind::Shl,
1170 BinOpKind::Shr => ast::BinOpKind::Shr,
1171 BinOpKind::Eq => ast::BinOpKind::Eq,
1172 BinOpKind::Lt => ast::BinOpKind::Lt,
1173 BinOpKind::Le => ast::BinOpKind::Le,
1174 BinOpKind::Ne => ast::BinOpKind::Ne,
1175 BinOpKind::Ge => ast::BinOpKind::Ge,
1176 BinOpKind::Gt => ast::BinOpKind::Gt,
1181 pub type BinOp = Spanned<BinOpKind>;
1183 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1185 /// The `*` operator (deferencing).
1187 /// The `!` operator (logical negation).
1189 /// The `-` operator (negation).
1194 pub fn as_str(self) -> &'static str {
1202 /// Returns `true` if the unary operator takes its argument by value.
1203 pub fn is_by_value(self) -> bool {
1205 UnNeg | UnNot => true,
1212 #[derive(RustcEncodable, RustcDecodable, HashStable)]
1219 impl fmt::Debug for Stmt {
1220 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1225 print::to_string(print::NO_ANN, |s| s.print_stmt(self))
1230 /// The contents of a statement.
1231 #[derive(RustcEncodable, RustcDecodable, HashStable)]
1233 /// A local (`let`) binding.
1236 /// An item binding.
1239 /// An expression without a trailing semi-colon (must have unit type).
1242 /// An expression with a trailing semi-colon (may have any type).
1247 pub fn attrs(&self) -> &[Attribute] {
1249 StmtKind::Local(ref l) => &l.attrs,
1250 StmtKind::Item(_) => &[],
1251 StmtKind::Expr(ref e) | StmtKind::Semi(ref e) => &e.attrs,
1256 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1257 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1260 /// Type annotation, if any (otherwise the type will be inferred).
1261 pub ty: Option<P<Ty>>,
1262 /// Initializer expression to set the value, if any.
1263 pub init: Option<P<Expr>>,
1267 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1268 /// desugaring. Otherwise will be `Normal`.
1269 pub source: LocalSource,
1272 /// Represents a single arm of a `match` expression, e.g.
1273 /// `<pat> (if <guard>) => <body>`.
1274 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1276 #[stable_hasher(ignore)]
1279 pub attrs: HirVec<Attribute>,
1280 /// If this pattern and the optional guard matches, then `body` is evaluated.
1282 /// Optional guard clause.
1283 pub guard: Option<Guard>,
1284 /// The expression the arm evaluates to if this arm matches.
1288 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1293 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1295 #[stable_hasher(ignore)]
1300 pub is_shorthand: bool,
1303 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1304 pub enum BlockCheckMode {
1306 UnsafeBlock(UnsafeSource),
1307 PushUnsafeBlock(UnsafeSource),
1308 PopUnsafeBlock(UnsafeSource),
1311 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1312 pub enum UnsafeSource {
1317 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1322 /// The body of a function, closure, or constant value. In the case of
1323 /// a function, the body contains not only the function body itself
1324 /// (which is an expression), but also the argument patterns, since
1325 /// those are something that the caller doesn't really care about.
1330 /// fn foo((x, y): (u32, u32)) -> u32 {
1335 /// Here, the `Body` associated with `foo()` would contain:
1337 /// - an `params` array containing the `(x, y)` pattern
1338 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1339 /// - `generator_kind` would be `None`
1341 /// All bodies have an **owner**, which can be accessed via the HIR
1342 /// map using `body_owner_def_id()`.
1343 #[derive(RustcEncodable, RustcDecodable, Debug)]
1344 pub struct Body<'hir> {
1345 pub params: &'hir [Param],
1347 pub generator_kind: Option<GeneratorKind>,
1351 pub fn id(&self) -> BodyId {
1352 BodyId { hir_id: self.value.hir_id }
1355 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1360 /// The type of source expression that caused this generator to be created.
1361 #[derive(Clone, PartialEq, Eq, HashStable, RustcEncodable, RustcDecodable, Debug, Copy)]
1362 pub enum GeneratorKind {
1363 /// An explicit `async` block or the body of an async function.
1364 Async(AsyncGeneratorKind),
1366 /// A generator literal created via a `yield` inside a closure.
1370 impl fmt::Display for GeneratorKind {
1371 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1373 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1374 GeneratorKind::Gen => f.write_str("generator"),
1379 /// In the case of a generator created as part of an async construct,
1380 /// which kind of async construct caused it to be created?
1382 /// This helps error messages but is also used to drive coercions in
1383 /// type-checking (see #60424).
1384 #[derive(Clone, PartialEq, Eq, HashStable, RustcEncodable, RustcDecodable, Debug, Copy)]
1385 pub enum AsyncGeneratorKind {
1386 /// An explicit `async` block written by the user.
1389 /// An explicit `async` block written by the user.
1392 /// The `async` block generated as the body of an async function.
1396 impl fmt::Display for AsyncGeneratorKind {
1397 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1398 f.write_str(match self {
1399 AsyncGeneratorKind::Block => "`async` block",
1400 AsyncGeneratorKind::Closure => "`async` closure body",
1401 AsyncGeneratorKind::Fn => "`async fn` body",
1406 #[derive(Copy, Clone, Debug)]
1407 pub enum BodyOwnerKind {
1408 /// Functions and methods.
1414 /// Constants and associated constants.
1417 /// Initializer of a `static` item.
1421 impl BodyOwnerKind {
1422 pub fn is_fn_or_closure(self) -> bool {
1424 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1425 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1431 pub type Lit = Spanned<LitKind>;
1433 /// A constant (expression) that's not an item or associated item,
1434 /// but needs its own `DefId` for type-checking, const-eval, etc.
1435 /// These are usually found nested inside types (e.g., array lengths)
1436 /// or expressions (e.g., repeat counts), and also used to define
1437 /// explicit discriminant values for enum variants.
1438 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1439 pub struct AnonConst {
1445 #[derive(RustcEncodable, RustcDecodable)]
1453 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1454 #[cfg(target_arch = "x86_64")]
1455 static_assert_size!(Expr, 64);
1458 pub fn precedence(&self) -> ExprPrecedence {
1460 ExprKind::Box(_) => ExprPrecedence::Box,
1461 ExprKind::Array(_) => ExprPrecedence::Array,
1462 ExprKind::Call(..) => ExprPrecedence::Call,
1463 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1464 ExprKind::Tup(_) => ExprPrecedence::Tup,
1465 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1466 ExprKind::Unary(..) => ExprPrecedence::Unary,
1467 ExprKind::Lit(_) => ExprPrecedence::Lit,
1468 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1469 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1470 ExprKind::Loop(..) => ExprPrecedence::Loop,
1471 ExprKind::Match(..) => ExprPrecedence::Match,
1472 ExprKind::Closure(..) => ExprPrecedence::Closure,
1473 ExprKind::Block(..) => ExprPrecedence::Block,
1474 ExprKind::Assign(..) => ExprPrecedence::Assign,
1475 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1476 ExprKind::Field(..) => ExprPrecedence::Field,
1477 ExprKind::Index(..) => ExprPrecedence::Index,
1478 ExprKind::Path(..) => ExprPrecedence::Path,
1479 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1480 ExprKind::Break(..) => ExprPrecedence::Break,
1481 ExprKind::Continue(..) => ExprPrecedence::Continue,
1482 ExprKind::Ret(..) => ExprPrecedence::Ret,
1483 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1484 ExprKind::Struct(..) => ExprPrecedence::Struct,
1485 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1486 ExprKind::Yield(..) => ExprPrecedence::Yield,
1487 ExprKind::Err => ExprPrecedence::Err,
1491 // Whether this looks like a place expr, without checking for deref
1493 // This will return `true` in some potentially surprising cases such as
1494 // `CONSTANT.field`.
1495 pub fn is_syntactic_place_expr(&self) -> bool {
1496 self.is_place_expr(|_| true)
1499 // Whether this is a place expression.
1500 // `allow_projections_from` should return `true` if indexing a field or
1501 // index expression based on the given expression should be considered a
1502 // place expression.
1503 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1505 ExprKind::Path(QPath::Resolved(_, ref path)) => match path.res {
1506 Res::Local(..) | Res::Def(DefKind::Static, _) | Res::Err => true,
1510 // Type ascription inherits its place expression kind from its
1512 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1513 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1515 ExprKind::Unary(UnDeref, _) => true,
1517 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1518 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1521 // Partially qualified paths in expressions can only legally
1522 // refer to associated items which are always rvalues.
1523 ExprKind::Path(QPath::TypeRelative(..))
1524 | ExprKind::Call(..)
1525 | ExprKind::MethodCall(..)
1526 | ExprKind::Struct(..)
1528 | ExprKind::Match(..)
1529 | ExprKind::Closure(..)
1530 | ExprKind::Block(..)
1531 | ExprKind::Repeat(..)
1532 | ExprKind::Array(..)
1533 | ExprKind::Break(..)
1534 | ExprKind::Continue(..)
1536 | ExprKind::Loop(..)
1537 | ExprKind::Assign(..)
1538 | ExprKind::InlineAsm(..)
1539 | ExprKind::AssignOp(..)
1541 | ExprKind::Unary(..)
1543 | ExprKind::AddrOf(..)
1544 | ExprKind::Binary(..)
1545 | ExprKind::Yield(..)
1546 | ExprKind::Cast(..)
1547 | ExprKind::DropTemps(..)
1548 | ExprKind::Err => false,
1552 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1553 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1554 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1555 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1556 /// beyond remembering to call this function before doing analysis on it.
1557 pub fn peel_drop_temps(&self) -> &Self {
1558 let mut expr = self;
1559 while let ExprKind::DropTemps(inner) = &expr.kind {
1566 impl fmt::Debug for Expr {
1567 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1572 print::to_string(print::NO_ANN, |s| s.print_expr(self))
1577 /// Checks if the specified expression is a built-in range literal.
1578 /// (See: `LoweringContext::lower_expr()`).
1580 /// FIXME(#60607): This function is a hack. If and when we have `QPath::Lang(...)`,
1581 /// we can use that instead as simpler, more reliable mechanism, as opposed to using `SourceMap`.
1582 pub fn is_range_literal(sm: &SourceMap, expr: &Expr) -> bool {
1583 // Returns whether the given path represents a (desugared) range,
1584 // either in std or core, i.e. has either a `::std::ops::Range` or
1585 // `::core::ops::Range` prefix.
1586 fn is_range_path(path: &Path) -> bool {
1587 let segs: Vec<_> = path.segments.iter().map(|seg| seg.ident.to_string()).collect();
1588 let segs: Vec<_> = segs.iter().map(|seg| &**seg).collect();
1590 // "{{root}}" is the equivalent of `::` prefix in `Path`.
1591 if let ["{{root}}", std_core, "ops", range] = segs.as_slice() {
1592 (*std_core == "std" || *std_core == "core") && range.starts_with("Range")
1598 // Check whether a span corresponding to a range expression is a
1599 // range literal, rather than an explicit struct or `new()` call.
1600 fn is_lit(sm: &SourceMap, span: &Span) -> bool {
1601 let end_point = sm.end_point(*span);
1603 if let Ok(end_string) = sm.span_to_snippet(end_point) {
1604 !(end_string.ends_with("}") || end_string.ends_with(")"))
1611 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1612 ExprKind::Struct(ref qpath, _, _) => {
1613 if let QPath::Resolved(None, ref path) = **qpath {
1614 return is_range_path(&path) && is_lit(sm, &expr.span);
1618 // `..` desugars to its struct path.
1619 ExprKind::Path(QPath::Resolved(None, ref path)) => {
1620 return is_range_path(&path) && is_lit(sm, &expr.span);
1623 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1624 ExprKind::Call(ref func, _) => {
1625 if let ExprKind::Path(QPath::TypeRelative(ref ty, ref segment)) = func.kind {
1626 if let TyKind::Path(QPath::Resolved(None, ref path)) = ty.kind {
1627 let new_call = segment.ident.name == sym::new;
1628 return is_range_path(&path) && is_lit(sm, &expr.span) && new_call;
1639 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1641 /// A `box x` expression.
1643 /// An array (e.g., `[a, b, c, d]`).
1644 Array(HirVec<Expr>),
1645 /// A function call.
1647 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1648 /// and the second field is the list of arguments.
1649 /// This also represents calling the constructor of
1650 /// tuple-like ADTs such as tuple structs and enum variants.
1651 Call(P<Expr>, HirVec<Expr>),
1652 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1654 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1655 /// (within the angle brackets).
1656 /// The first element of the vector of `Expr`s is the expression that evaluates
1657 /// to the object on which the method is being called on (the receiver),
1658 /// and the remaining elements are the rest of the arguments.
1659 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1660 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1662 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1663 /// the `hir_id` of the `MethodCall` node itself.
1665 /// [`type_dependent_def_id`]: ../ty/struct.TypeckTables.html#method.type_dependent_def_id
1666 MethodCall(P<PathSegment>, Span, HirVec<Expr>),
1667 /// A tuple (e.g., `(a, b, c, d)`).
1669 /// A binary operation (e.g., `a + b`, `a * b`).
1670 Binary(BinOp, P<Expr>, P<Expr>),
1671 /// A unary operation (e.g., `!x`, `*x`).
1672 Unary(UnOp, P<Expr>),
1673 /// A literal (e.g., `1`, `"foo"`).
1675 /// A cast (e.g., `foo as f64`).
1676 Cast(P<Expr>, P<Ty>),
1677 /// A type reference (e.g., `Foo`).
1678 Type(P<Expr>, P<Ty>),
1679 /// Wraps the expression in a terminating scope.
1680 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1682 /// This construct only exists to tweak the drop order in HIR lowering.
1683 /// An example of that is the desugaring of `for` loops.
1685 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1687 /// I.e., `'label: loop { <block> }`.
1688 Loop(P<Block>, Option<Label>, LoopSource),
1689 /// A `match` block, with a source that indicates whether or not it is
1690 /// the result of a desugaring, and if so, which kind.
1691 Match(P<Expr>, HirVec<Arm>, MatchSource),
1692 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1694 /// The `Span` is the argument block `|...|`.
1696 /// This may also be a generator literal or an `async block` as indicated by the
1697 /// `Option<Movability>`.
1698 Closure(CaptureBy, P<FnDecl>, BodyId, Span, Option<Movability>),
1699 /// A block (e.g., `'label: { ... }`).
1700 Block(P<Block>, Option<Label>),
1702 /// An assignment (e.g., `a = foo()`).
1703 /// The `Span` argument is the span of the `=` token.
1704 Assign(P<Expr>, P<Expr>, Span),
1705 /// An assignment with an operator.
1708 AssignOp(BinOp, P<Expr>, P<Expr>),
1709 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1710 Field(P<Expr>, Ident),
1711 /// An indexing operation (`foo[2]`).
1712 Index(P<Expr>, P<Expr>),
1714 /// Path to a definition, possibly containing lifetime or type parameters.
1717 /// A referencing operation (i.e., `&a`, `&mut a`, `&raw const a`, or `&raw mut a`).
1718 AddrOf(BorrowKind, Mutability, P<Expr>),
1719 /// A `break`, with an optional label to break.
1720 Break(Destination, Option<P<Expr>>),
1721 /// A `continue`, with an optional label.
1722 Continue(Destination),
1723 /// A `return`, with an optional value to be returned.
1724 Ret(Option<P<Expr>>),
1726 /// Inline assembly (from `asm!`), with its outputs and inputs.
1727 InlineAsm(P<InlineAsm>),
1729 /// A struct or struct-like variant literal expression.
1731 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1732 /// where `base` is the `Option<Expr>`.
1733 Struct(P<QPath>, HirVec<Field>, Option<P<Expr>>),
1735 /// An array literal constructed from one repeated element.
1737 /// E.g., `[1; 5]`. The first expression is the element
1738 /// to be repeated; the second is the number of times to repeat it.
1739 Repeat(P<Expr>, AnonConst),
1741 /// A suspension point for generators (i.e., `yield <expr>`).
1742 Yield(P<Expr>, YieldSource),
1744 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1748 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1750 /// To resolve the path to a `DefId`, call [`qpath_res`].
1752 /// [`qpath_res`]: ../ty/struct.TypeckTables.html#method.qpath_res
1753 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1755 /// Path to a definition, optionally "fully-qualified" with a `Self`
1756 /// type, if the path points to an associated item in a trait.
1758 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1759 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1760 /// even though they both have the same two-segment `Clone::clone` `Path`.
1761 Resolved(Option<P<Ty>>, P<Path>),
1763 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1764 /// Will be resolved by type-checking to an associated item.
1766 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1767 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1768 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1769 TypeRelative(P<Ty>, P<PathSegment>),
1772 /// Hints at the original code for a let statement.
1773 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1774 pub enum LocalSource {
1775 /// A `match _ { .. }`.
1777 /// A desugared `for _ in _ { .. }` loop.
1779 /// When lowering async functions, we create locals within the `async move` so that
1780 /// all parameters are dropped after the future is polled.
1782 /// ```ignore (pseudo-Rust)
1783 /// async fn foo(<pattern> @ x: Type) {
1785 /// let <pattern> = x;
1790 /// A desugared `<expr>.await`.
1794 /// Hints at the original code for a `match _ { .. }`.
1795 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
1796 pub enum MatchSource {
1797 /// A `match _ { .. }`.
1799 /// An `if _ { .. }` (optionally with `else { .. }`).
1800 IfDesugar { contains_else_clause: bool },
1801 /// An `if let _ = _ { .. }` (optionally with `else { .. }`).
1802 IfLetDesugar { contains_else_clause: bool },
1803 /// A `while _ { .. }` (which was desugared to a `loop { match _ { .. } }`).
1805 /// A `while let _ = _ { .. }` (which was desugared to a
1806 /// `loop { match _ { .. } }`).
1808 /// A desugared `for _ in _ { .. }` loop.
1810 /// A desugared `?` operator.
1812 /// A desugared `<expr>.await`.
1817 pub fn name(self) -> &'static str {
1821 IfDesugar { .. } | IfLetDesugar { .. } => "if",
1822 WhileDesugar | WhileLetDesugar => "while",
1823 ForLoopDesugar => "for",
1825 AwaitDesugar => ".await",
1830 /// The loop type that yielded an `ExprKind::Loop`.
1831 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1832 pub enum LoopSource {
1833 /// A `loop { .. }` loop.
1835 /// A `while _ { .. }` loop.
1837 /// A `while let _ = _ { .. }` loop.
1839 /// A `for _ in _ { .. }` loop.
1844 pub fn name(self) -> &'static str {
1846 LoopSource::Loop => "loop",
1847 LoopSource::While | LoopSource::WhileLet => "while",
1848 LoopSource::ForLoop => "for",
1853 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1854 pub enum LoopIdError {
1856 UnlabeledCfInWhileCondition,
1860 impl fmt::Display for LoopIdError {
1861 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1862 f.write_str(match self {
1863 LoopIdError::OutsideLoopScope => "not inside loop scope",
1864 LoopIdError::UnlabeledCfInWhileCondition => {
1865 "unlabeled control flow (break or continue) in while condition"
1867 LoopIdError::UnresolvedLabel => "label not found",
1872 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1873 pub struct Destination {
1874 // This is `Some(_)` iff there is an explicit user-specified `label
1875 pub label: Option<Label>,
1877 // These errors are caught and then reported during the diagnostics pass in
1878 // librustc_passes/loops.rs
1879 pub target_id: Result<HirId, LoopIdError>,
1882 /// The yield kind that caused an `ExprKind::Yield`.
1883 #[derive(Copy, Clone, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable, HashStable)]
1884 pub enum YieldSource {
1885 /// An `<expr>.await`.
1887 /// A plain `yield`.
1891 impl fmt::Display for YieldSource {
1892 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1893 f.write_str(match self {
1894 YieldSource::Await => "`await`",
1895 YieldSource::Yield => "`yield`",
1900 impl From<GeneratorKind> for YieldSource {
1901 fn from(kind: GeneratorKind) -> Self {
1903 // Guess based on the kind of the current generator.
1904 GeneratorKind::Gen => Self::Yield,
1905 GeneratorKind::Async(_) => Self::Await,
1910 // N.B., if you change this, you'll probably want to change the corresponding
1911 // type structure in middle/ty.rs as well.
1912 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1915 pub mutbl: Mutability,
1918 /// Represents a function's signature in a trait declaration,
1919 /// trait implementation, or a free function.
1920 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1922 pub header: FnHeader,
1923 pub decl: P<FnDecl>,
1926 // The bodies for items are stored "out of line", in a separate
1927 // hashmap in the `Crate`. Here we just record the node-id of the item
1928 // so it can fetched later.
1929 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1930 pub struct TraitItemId {
1934 /// Represents an item declaration within a trait declaration,
1935 /// possibly including a default implementation. A trait item is
1936 /// either required (meaning it doesn't have an implementation, just a
1937 /// signature) or provided (meaning it has a default implementation).
1938 #[derive(RustcEncodable, RustcDecodable, Debug)]
1939 pub struct TraitItem<'hir> {
1942 pub attrs: &'hir [Attribute],
1943 pub generics: Generics,
1944 pub kind: TraitItemKind<'hir>,
1948 /// Represents a trait method's body (or just argument names).
1949 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1950 pub enum TraitMethod {
1951 /// No default body in the trait, just a signature.
1952 Required(HirVec<Ident>),
1954 /// Both signature and body are provided in the trait.
1958 /// Represents a trait method or associated constant or type
1959 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1960 pub enum TraitItemKind<'hir> {
1961 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
1962 Const(&'hir Ty, Option<BodyId>),
1963 /// A method with an optional body.
1964 Method(FnSig, TraitMethod),
1965 /// An associated type with (possibly empty) bounds and optional concrete
1967 Type(GenericBounds, Option<&'hir Ty>),
1970 // The bodies for items are stored "out of line", in a separate
1971 // hashmap in the `Crate`. Here we just record the node-id of the item
1972 // so it can fetched later.
1973 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1974 pub struct ImplItemId {
1978 /// Represents anything within an `impl` block.
1979 #[derive(RustcEncodable, RustcDecodable, Debug)]
1980 pub struct ImplItem<'hir> {
1983 pub vis: Visibility,
1984 pub defaultness: Defaultness,
1985 pub attrs: &'hir [Attribute],
1986 pub generics: Generics,
1987 pub kind: ImplItemKind<'hir>,
1991 /// Represents various kinds of content within an `impl`.
1992 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1993 pub enum ImplItemKind<'hir> {
1994 /// An associated constant of the given type, set to the constant result
1995 /// of the expression.
1996 Const(&'hir Ty, BodyId),
1997 /// A method implementation with the given signature and body.
1998 Method(FnSig, BodyId),
1999 /// An associated type.
2001 /// An associated `type = impl Trait`.
2002 OpaqueTy(GenericBounds),
2005 /// Bind a type to an associated type (i.e., `A = Foo`).
2007 /// Bindings like `A: Debug` are represented as a special type `A =
2008 /// $::Debug` that is understood by the astconv code.
2010 /// FIXME(alexreg): why have a separate type for the binding case,
2011 /// wouldn't it be better to make the `ty` field an enum like the
2015 /// enum TypeBindingKind {
2020 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2021 pub struct TypeBinding {
2023 #[stable_hasher(project(name))]
2025 pub kind: TypeBindingKind,
2029 // Represents the two kinds of type bindings.
2030 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2031 pub enum TypeBindingKind {
2032 /// E.g., `Foo<Bar: Send>`.
2033 Constraint { bounds: HirVec<GenericBound> },
2034 /// E.g., `Foo<Bar = ()>`.
2035 Equality { ty: P<Ty> },
2039 pub fn ty(&self) -> &Ty {
2041 TypeBindingKind::Equality { ref ty } => ty,
2042 _ => bug!("expected equality type binding for parenthesized generic args"),
2047 #[derive(RustcEncodable, RustcDecodable)]
2054 impl fmt::Debug for Ty {
2055 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2056 write!(f, "type({})", print::to_string(print::NO_ANN, |s| s.print_type(self)))
2060 /// Not represented directly in the AST; referred to by name through a `ty_path`.
2061 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
2071 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2072 pub struct BareFnTy {
2073 pub unsafety: Unsafety,
2075 pub generic_params: HirVec<GenericParam>,
2076 pub decl: P<FnDecl>,
2077 pub param_names: HirVec<Ident>,
2080 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2081 pub struct OpaqueTy {
2082 pub generics: Generics,
2083 pub bounds: GenericBounds,
2084 pub impl_trait_fn: Option<DefId>,
2085 pub origin: OpaqueTyOrigin,
2088 /// From whence the opaque type came.
2089 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2090 pub enum OpaqueTyOrigin {
2091 /// `type Foo = impl Trait;`
2099 /// The various kinds of types recognized by the compiler.
2100 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2102 /// A variable length slice (i.e., `[T]`).
2104 /// A fixed length array (i.e., `[T; n]`).
2105 Array(P<Ty>, AnonConst),
2106 /// A raw pointer (i.e., `*const T` or `*mut T`).
2108 /// A reference (i.e., `&'a T` or `&'a mut T`).
2109 Rptr(Lifetime, MutTy),
2110 /// A bare function (e.g., `fn(usize) -> bool`).
2111 BareFn(P<BareFnTy>),
2112 /// The never type (`!`).
2114 /// A tuple (`(A, B, C, D, ...)`).
2116 /// A path to a type definition (`module::module::...::Type`), or an
2117 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2119 /// Type parameters may be stored in each `PathSegment`.
2121 /// A type definition itself. This is currently only used for the `type Foo = impl Trait`
2122 /// item that `impl Trait` in return position desugars to.
2124 /// The generic argument list contains the lifetimes (and in the future possibly parameters)
2125 /// that are actually bound on the `impl Trait`.
2126 Def(ItemId, HirVec<GenericArg>),
2127 /// A trait object type `Bound1 + Bound2 + Bound3`
2128 /// where `Bound` is a trait or a lifetime.
2129 TraitObject(HirVec<PolyTraitRef>, Lifetime),
2132 /// `TyKind::Infer` means the type should be inferred instead of it having been
2133 /// specified. This can appear anywhere in a type.
2135 /// Placeholder for a type that has failed to be defined.
2139 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable, PartialEq)]
2140 pub struct InlineAsmOutput {
2141 pub constraint: Symbol,
2143 pub is_indirect: bool,
2147 // NOTE(eddyb) This is used within MIR as well, so unlike the rest of the HIR,
2148 // it needs to be `Clone` and use plain `Vec<T>` instead of `HirVec<T>`.
2149 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable, PartialEq)]
2150 pub struct InlineAsmInner {
2152 pub asm_str_style: StrStyle,
2153 pub outputs: Vec<InlineAsmOutput>,
2154 pub inputs: Vec<Symbol>,
2155 pub clobbers: Vec<Symbol>,
2157 pub alignstack: bool,
2158 pub dialect: AsmDialect,
2161 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2162 pub struct InlineAsm {
2163 pub inner: InlineAsmInner,
2164 pub outputs_exprs: HirVec<Expr>,
2165 pub inputs_exprs: HirVec<Expr>,
2168 /// Represents a parameter in a function header.
2169 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2171 pub attrs: HirVec<Attribute>,
2177 /// Represents the header (not the body) of a function declaration.
2178 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2180 /// The types of the function's parameters.
2182 /// Additional argument data is stored in the function's [body](Body::parameters).
2183 pub inputs: HirVec<Ty>,
2184 pub output: FunctionRetTy,
2185 pub c_variadic: bool,
2186 /// Does the function have an implicit self?
2187 pub implicit_self: ImplicitSelfKind,
2190 /// Represents what type of implicit self a function has, if any.
2191 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2192 pub enum ImplicitSelfKind {
2193 /// Represents a `fn x(self);`.
2195 /// Represents a `fn x(mut self);`.
2197 /// Represents a `fn x(&self);`.
2199 /// Represents a `fn x(&mut self);`.
2201 /// Represents when a function does not have a self argument or
2202 /// when a function has a `self: X` argument.
2206 impl ImplicitSelfKind {
2207 /// Does this represent an implicit self?
2208 pub fn has_implicit_self(&self) -> bool {
2210 ImplicitSelfKind::None => false,
2233 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2234 pub enum Defaultness {
2235 Default { has_value: bool },
2240 pub fn has_value(&self) -> bool {
2242 Defaultness::Default { has_value, .. } => has_value,
2243 Defaultness::Final => true,
2247 pub fn is_final(&self) -> bool {
2248 *self == Defaultness::Final
2251 pub fn is_default(&self) -> bool {
2253 Defaultness::Default { .. } => true,
2259 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2260 pub enum FunctionRetTy {
2261 /// Return type is not specified.
2263 /// Functions default to `()` and
2264 /// closures default to inference. Span points to where return
2265 /// type would be inserted.
2266 DefaultReturn(Span),
2267 /// Everything else.
2271 impl fmt::Display for FunctionRetTy {
2272 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2274 Return(ref ty) => print::to_string(print::NO_ANN, |s| s.print_type(ty)).fmt(f),
2275 DefaultReturn(_) => "()".fmt(f),
2280 impl FunctionRetTy {
2281 pub fn span(&self) -> Span {
2283 DefaultReturn(span) => span,
2284 Return(ref ty) => ty.span,
2289 #[derive(RustcEncodable, RustcDecodable, Debug)]
2290 pub struct Mod<'hir> {
2291 /// A span from the first token past `{` to the last token until `}`.
2292 /// For `mod foo;`, the inner span ranges from the first token
2293 /// to the last token in the external file.
2295 pub item_ids: &'hir [ItemId],
2298 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2299 pub struct ForeignMod<'hir> {
2301 pub items: &'hir [ForeignItem<'hir>],
2304 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2305 pub struct GlobalAsm {
2309 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2310 pub struct EnumDef<'hir> {
2311 pub variants: &'hir [Variant<'hir>],
2314 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2315 pub struct Variant<'hir> {
2316 /// Name of the variant.
2317 #[stable_hasher(project(name))]
2319 /// Attributes of the variant.
2320 pub attrs: &'hir [Attribute],
2321 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2323 /// Fields and constructor id of the variant.
2324 pub data: VariantData<'hir>,
2325 /// Explicit discriminant (e.g., `Foo = 1`).
2326 pub disr_expr: Option<AnonConst>,
2331 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2333 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2334 /// Also produced for each element of a list `use`, e.g.
2335 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2338 /// Glob import, e.g., `use foo::*`.
2341 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2342 /// an additional `use foo::{}` for performing checks such as
2343 /// unstable feature gating. May be removed in the future.
2347 /// References to traits in impls.
2349 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2350 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2351 /// trait being referred to but just a unique `HirId` that serves as a key
2352 /// within the resolution map.
2353 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2354 pub struct TraitRef {
2356 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2357 #[stable_hasher(ignore)]
2358 pub hir_ref_id: HirId,
2362 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2363 pub fn trait_def_id(&self) -> DefId {
2364 match self.path.res {
2365 Res::Def(DefKind::Trait, did) => did,
2366 Res::Def(DefKind::TraitAlias, did) => did,
2370 _ => unreachable!(),
2375 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2376 pub struct PolyTraitRef {
2377 /// The `'a` in `<'a> Foo<&'a T>`.
2378 pub bound_generic_params: HirVec<GenericParam>,
2380 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2381 pub trait_ref: TraitRef,
2386 pub type Visibility = Spanned<VisibilityKind>;
2388 #[derive(RustcEncodable, RustcDecodable, Debug)]
2389 pub enum VisibilityKind {
2392 Restricted { path: P<Path>, hir_id: HirId },
2396 impl VisibilityKind {
2397 pub fn is_pub(&self) -> bool {
2399 VisibilityKind::Public => true,
2404 pub fn is_pub_restricted(&self) -> bool {
2406 VisibilityKind::Public | VisibilityKind::Inherited => false,
2407 VisibilityKind::Crate(..) | VisibilityKind::Restricted { .. } => true,
2411 pub fn descr(&self) -> &'static str {
2413 VisibilityKind::Public => "public",
2414 VisibilityKind::Inherited => "private",
2415 VisibilityKind::Crate(..) => "crate-visible",
2416 VisibilityKind::Restricted { .. } => "restricted",
2421 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2422 pub struct StructField<'hir> {
2424 #[stable_hasher(project(name))]
2426 pub vis: Visibility,
2429 pub attrs: &'hir [Attribute],
2432 impl StructField<'_> {
2433 // Still necessary in couple of places
2434 pub fn is_positional(&self) -> bool {
2435 let first = self.ident.as_str().as_bytes()[0];
2436 first >= b'0' && first <= b'9'
2440 /// Fields and constructor IDs of enum variants and structs.
2441 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2442 pub enum VariantData<'hir> {
2443 /// A struct variant.
2445 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2446 Struct(&'hir [StructField<'hir>], /* recovered */ bool),
2447 /// A tuple variant.
2449 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2450 Tuple(&'hir [StructField<'hir>], HirId),
2453 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2457 impl VariantData<'hir> {
2458 /// Return the fields of this variant.
2459 pub fn fields(&self) -> &'hir [StructField<'hir>] {
2461 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2466 /// Return the `HirId` of this variant's constructor, if it has one.
2467 pub fn ctor_hir_id(&self) -> Option<HirId> {
2469 VariantData::Struct(_, _) => None,
2470 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2475 // The bodies for items are stored "out of line", in a separate
2476 // hashmap in the `Crate`. Here we just record the node-id of the item
2477 // so it can fetched later.
2478 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2485 /// The name might be a dummy name in case of anonymous items
2486 #[derive(RustcEncodable, RustcDecodable, Debug)]
2487 pub struct Item<'hir> {
2490 pub attrs: &'hir [Attribute],
2491 pub kind: ItemKind<'hir>,
2492 pub vis: Visibility,
2496 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2497 pub struct FnHeader {
2498 pub unsafety: Unsafety,
2499 pub constness: Constness,
2500 pub asyncness: IsAsync,
2505 pub fn is_const(&self) -> bool {
2506 match &self.constness {
2507 Constness::Const => true,
2513 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2514 pub enum ItemKind<'hir> {
2515 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2517 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2518 ExternCrate(Option<Name>),
2520 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2524 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2525 Use(&'hir Path, UseKind),
2527 /// A `static` item.
2528 Static(&'hir Ty, Mutability, BodyId),
2530 Const(&'hir Ty, BodyId),
2531 /// A function declaration.
2532 Fn(FnSig, Generics, BodyId),
2535 /// An external module, e.g. `extern { .. }`.
2536 ForeignMod(ForeignMod<'hir>),
2537 /// Module-level inline assembly (from `global_asm!`).
2538 GlobalAsm(&'hir GlobalAsm),
2539 /// A type alias, e.g., `type Foo = Bar<u8>`.
2540 TyAlias(&'hir Ty, Generics),
2541 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2543 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2544 Enum(EnumDef<'hir>, Generics),
2545 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2546 Struct(VariantData<'hir>, Generics),
2547 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2548 Union(VariantData<'hir>, Generics),
2549 /// A trait definition.
2550 Trait(IsAuto, Unsafety, Generics, GenericBounds, &'hir [TraitItemRef]),
2552 TraitAlias(Generics, GenericBounds),
2554 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2560 Option<TraitRef>, // (optional) trait this impl implements
2562 &'hir [ImplItemRef],
2567 pub fn descriptive_variant(&self) -> &str {
2569 ItemKind::ExternCrate(..) => "extern crate",
2570 ItemKind::Use(..) => "use",
2571 ItemKind::Static(..) => "static item",
2572 ItemKind::Const(..) => "constant item",
2573 ItemKind::Fn(..) => "function",
2574 ItemKind::Mod(..) => "module",
2575 ItemKind::ForeignMod(..) => "foreign module",
2576 ItemKind::GlobalAsm(..) => "global asm",
2577 ItemKind::TyAlias(..) => "type alias",
2578 ItemKind::OpaqueTy(..) => "opaque type",
2579 ItemKind::Enum(..) => "enum",
2580 ItemKind::Struct(..) => "struct",
2581 ItemKind::Union(..) => "union",
2582 ItemKind::Trait(..) => "trait",
2583 ItemKind::TraitAlias(..) => "trait alias",
2584 ItemKind::Impl(..) => "impl",
2588 pub fn adt_kind(&self) -> Option<AdtKind> {
2590 ItemKind::Struct(..) => Some(AdtKind::Struct),
2591 ItemKind::Union(..) => Some(AdtKind::Union),
2592 ItemKind::Enum(..) => Some(AdtKind::Enum),
2597 pub fn generics(&self) -> Option<&Generics> {
2599 ItemKind::Fn(_, ref generics, _)
2600 | ItemKind::TyAlias(_, ref generics)
2601 | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
2602 | ItemKind::Enum(_, ref generics)
2603 | ItemKind::Struct(_, ref generics)
2604 | ItemKind::Union(_, ref generics)
2605 | ItemKind::Trait(_, _, ref generics, _, _)
2606 | ItemKind::Impl(_, _, _, ref generics, _, _, _) => generics,
2612 /// A reference from an trait to one of its associated items. This
2613 /// contains the item's id, naturally, but also the item's name and
2614 /// some other high-level details (like whether it is an associated
2615 /// type or method, and whether it is public). This allows other
2616 /// passes to find the impl they want without loading the ID (which
2617 /// means fewer edges in the incremental compilation graph).
2618 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2619 pub struct TraitItemRef {
2620 pub id: TraitItemId,
2621 #[stable_hasher(project(name))]
2623 pub kind: AssocItemKind,
2625 pub defaultness: Defaultness,
2628 /// A reference from an impl to one of its associated items. This
2629 /// contains the item's ID, naturally, but also the item's name and
2630 /// some other high-level details (like whether it is an associated
2631 /// type or method, and whether it is public). This allows other
2632 /// passes to find the impl they want without loading the ID (which
2633 /// means fewer edges in the incremental compilation graph).
2634 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2635 pub struct ImplItemRef {
2637 #[stable_hasher(project(name))]
2639 pub kind: AssocItemKind,
2641 pub vis: Visibility,
2642 pub defaultness: Defaultness,
2645 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2646 pub enum AssocItemKind {
2648 Method { has_self: bool },
2653 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2654 pub struct ForeignItem<'hir> {
2655 #[stable_hasher(project(name))]
2657 pub attrs: &'hir [Attribute],
2658 pub kind: ForeignItemKind<'hir>,
2661 pub vis: Visibility,
2664 /// An item within an `extern` block.
2665 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2666 pub enum ForeignItemKind<'hir> {
2667 /// A foreign function.
2668 Fn(&'hir FnDecl, &'hir [Ident], Generics),
2669 /// A foreign static item (`static ext: u8`).
2670 Static(&'hir Ty, Mutability),
2675 impl ForeignItemKind<'hir> {
2676 pub fn descriptive_variant(&self) -> &str {
2678 ForeignItemKind::Fn(..) => "foreign function",
2679 ForeignItemKind::Static(..) => "foreign static item",
2680 ForeignItemKind::Type => "foreign type",
2685 /// A variable captured by a closure.
2686 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable, HashStable)]
2688 // First span where it is accessed (there can be multiple).
2692 pub type CaptureModeMap = NodeMap<CaptureBy>;
2694 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2695 // has length > 0 if the trait is found through an chain of imports, starting with the
2696 // import/use statement in the scope where the trait is used.
2697 #[derive(Clone, Debug)]
2698 pub struct TraitCandidate {
2700 pub import_ids: SmallVec<[NodeId; 1]>,
2703 // Trait method resolution
2704 pub type TraitMap = NodeMap<Vec<TraitCandidate>>;
2706 // Map from the NodeId of a glob import to a list of items which are actually
2708 pub type GlobMap = NodeMap<FxHashSet<Name>>;
2710 pub fn provide(providers: &mut Providers<'_>) {
2711 check_attr::provide(providers);
2712 map::provide(providers);
2713 upvars::provide(providers);
2716 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
2717 pub struct CodegenFnAttrs {
2718 pub flags: CodegenFnAttrFlags,
2719 /// Parsed representation of the `#[inline]` attribute
2720 pub inline: InlineAttr,
2721 /// Parsed representation of the `#[optimize]` attribute
2722 pub optimize: OptimizeAttr,
2723 /// The `#[export_name = "..."]` attribute, indicating a custom symbol a
2724 /// function should be exported under
2725 pub export_name: Option<Symbol>,
2726 /// The `#[link_name = "..."]` attribute, indicating a custom symbol an
2727 /// imported function should be imported as. Note that `export_name`
2728 /// probably isn't set when this is set, this is for foreign items while
2729 /// `#[export_name]` is for Rust-defined functions.
2730 pub link_name: Option<Symbol>,
2731 /// The `#[link_ordinal = "..."]` attribute, indicating an ordinal an
2732 /// imported function has in the dynamic library. Note that this must not
2733 /// be set when `link_name` is set. This is for foreign items with the
2734 /// "raw-dylib" kind.
2735 pub link_ordinal: Option<usize>,
2736 /// The `#[target_feature(enable = "...")]` attribute and the enabled
2737 /// features (only enabled features are supported right now).
2738 pub target_features: Vec<Symbol>,
2739 /// The `#[linkage = "..."]` attribute and the value we found.
2740 pub linkage: Option<Linkage>,
2741 /// The `#[link_section = "..."]` attribute, or what executable section this
2742 /// should be placed in.
2743 pub link_section: Option<Symbol>,
2747 #[derive(RustcEncodable, RustcDecodable, HashStable)]
2748 pub struct CodegenFnAttrFlags: u32 {
2749 /// `#[cold]`: a hint to LLVM that this function, when called, is never on
2751 const COLD = 1 << 0;
2752 /// `#[rustc_allocator]`: a hint to LLVM that the pointer returned from this
2753 /// function is never null.
2754 const ALLOCATOR = 1 << 1;
2755 /// `#[unwind]`: an indicator that this function may unwind despite what
2756 /// its ABI signature may otherwise imply.
2757 const UNWIND = 1 << 2;
2758 /// `#[rust_allocator_nounwind]`, an indicator that an imported FFI
2759 /// function will never unwind. Probably obsolete by recent changes with
2760 /// #[unwind], but hasn't been removed/migrated yet
2761 const RUSTC_ALLOCATOR_NOUNWIND = 1 << 3;
2762 /// `#[naked]`: an indicator to LLVM that no function prologue/epilogue
2763 /// should be generated.
2764 const NAKED = 1 << 4;
2765 /// `#[no_mangle]`: an indicator that the function's name should be the same
2767 const NO_MANGLE = 1 << 5;
2768 /// `#[rustc_std_internal_symbol]`: an indicator that this symbol is a
2769 /// "weird symbol" for the standard library in that it has slightly
2770 /// different linkage, visibility, and reachability rules.
2771 const RUSTC_STD_INTERNAL_SYMBOL = 1 << 6;
2772 /// `#[no_debug]`: an indicator that no debugging information should be
2773 /// generated for this function by LLVM.
2774 const NO_DEBUG = 1 << 7;
2775 /// `#[thread_local]`: indicates a static is actually a thread local
2777 const THREAD_LOCAL = 1 << 8;
2778 /// `#[used]`: indicates that LLVM can't eliminate this function (but the
2780 const USED = 1 << 9;
2781 /// `#[ffi_returns_twice]`, indicates that an extern function can return
2783 const FFI_RETURNS_TWICE = 1 << 10;
2784 /// `#[track_caller]`: allow access to the caller location
2785 const TRACK_CALLER = 1 << 11;
2789 impl CodegenFnAttrs {
2790 pub fn new() -> CodegenFnAttrs {
2792 flags: CodegenFnAttrFlags::empty(),
2793 inline: InlineAttr::None,
2794 optimize: OptimizeAttr::None,
2798 target_features: vec![],
2804 /// Returns `true` if `#[inline]` or `#[inline(always)]` is present.
2805 pub fn requests_inline(&self) -> bool {
2807 InlineAttr::Hint | InlineAttr::Always => true,
2808 InlineAttr::None | InlineAttr::Never => false,
2812 /// Returns `true` if it looks like this symbol needs to be exported, for example:
2814 /// * `#[no_mangle]` is present
2815 /// * `#[export_name(...)]` is present
2816 /// * `#[linkage]` is present
2817 pub fn contains_extern_indicator(&self) -> bool {
2818 self.flags.contains(CodegenFnAttrFlags::NO_MANGLE)
2819 || self.export_name.is_some()
2820 || match self.linkage {
2821 // These are private, so make sure we don't try to consider
2823 None | Some(Linkage::Internal) | Some(Linkage::Private) => false,
2829 #[derive(Copy, Clone, Debug)]
2830 pub enum Node<'hir> {
2832 Item(&'hir Item<'hir>),
2833 ForeignItem(&'hir ForeignItem<'hir>),
2834 TraitItem(&'hir TraitItem<'hir>),
2835 ImplItem(&'hir ImplItem<'hir>),
2836 Variant(&'hir Variant<'hir>),
2837 Field(&'hir StructField<'hir>),
2838 AnonConst(&'hir AnonConst),
2841 PathSegment(&'hir PathSegment),
2843 TraitRef(&'hir TraitRef),
2849 MacroDef(&'hir MacroDef<'hir>),
2851 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
2852 /// with synthesized constructors.
2853 Ctor(&'hir VariantData<'hir>),
2855 Lifetime(&'hir Lifetime),
2856 GenericParam(&'hir GenericParam),
2857 Visibility(&'hir Visibility),
2863 pub fn ident(&self) -> Option<Ident> {
2865 Node::TraitItem(TraitItem { ident, .. })
2866 | Node::ImplItem(ImplItem { ident, .. })
2867 | Node::ForeignItem(ForeignItem { ident, .. })
2868 | Node::Item(Item { ident, .. }) => Some(*ident),