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::mir::mono::Linkage;
14 use crate::ty::query::Providers;
15 use crate::util::nodemap::{FxHashSet, NodeMap};
17 use errors::FatalError;
18 use rustc_data_structures::sync::{par_for_each_in, Send, Sync};
19 use rustc_macros::HashStable;
20 use rustc_serialize::{self, Decodable, Decoder, Encodable, Encoder};
21 use rustc_span::source_map::{SourceMap, Spanned};
22 use rustc_span::symbol::{kw, sym, Symbol};
23 use rustc_span::{MultiSpan, Span, DUMMY_SP};
24 use rustc_target::spec::abi::Abi;
25 use smallvec::SmallVec;
26 use std::collections::{BTreeMap, BTreeSet};
28 use syntax::ast::{self, AsmDialect, CrateSugar, Ident, Name, NodeId};
29 use syntax::ast::{AttrVec, Attribute, FloatTy, IntTy, Label, LitKind, StrStyle, UintTy};
30 pub use syntax::ast::{BorrowKind, ImplPolarity, IsAuto};
31 pub use syntax::ast::{CaptureBy, Constness, Movability, Mutability, Unsafety};
32 use syntax::attr::{InlineAttr, OptimizeAttr};
33 use syntax::tokenstream::TokenStream;
34 use syntax::util::parser::ExprPrecedence;
40 pub mod itemlikevisit;
46 /// Uniquely identifies a node in the HIR of the current crate. It is
47 /// composed of the `owner`, which is the `DefIndex` of the directly enclosing
48 /// `hir::Item`, `hir::TraitItem`, or `hir::ImplItem` (i.e., the closest "item-like"),
49 /// and the `local_id` which is unique within the given owner.
51 /// This two-level structure makes for more stable values: One can move an item
52 /// around within the source code, or add or remove stuff before it, without
53 /// the `local_id` part of the `HirId` changing, which is a very useful property in
54 /// incremental compilation where we have to persist things through changes to
56 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)]
59 pub local_id: ItemLocalId,
63 pub fn owner_def_id(self) -> DefId {
64 DefId::local(self.owner)
67 pub fn owner_local_def_id(self) -> LocalDefId {
68 LocalDefId::from_def_id(DefId::local(self.owner))
72 impl rustc_serialize::UseSpecializedEncodable for HirId {
73 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
74 let HirId { owner, local_id } = *self;
82 impl rustc_serialize::UseSpecializedDecodable for HirId {
83 fn default_decode<D: Decoder>(d: &mut D) -> Result<HirId, D::Error> {
84 let owner = DefIndex::decode(d)?;
85 let local_id = ItemLocalId::decode(d)?;
87 Ok(HirId { owner, local_id })
91 impl fmt::Display for HirId {
92 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93 write!(f, "{:?}", self)
97 // Hack to ensure that we don't try to access the private parts of `ItemLocalId` in this module.
98 mod item_local_id_inner {
99 use rustc_index::vec::Idx;
100 use rustc_macros::HashStable;
101 rustc_index::newtype_index! {
102 /// An `ItemLocalId` uniquely identifies something within a given "item-like";
103 /// that is, within a `hir::Item`, `hir::TraitItem`, or `hir::ImplItem`. There is no
104 /// guarantee that the numerical value of a given `ItemLocalId` corresponds to
105 /// the node's position within the owning item in any way, but there is a
106 /// guarantee that the `LocalItemId`s within an owner occupy a dense range of
107 /// integers starting at zero, so a mapping that maps all or most nodes within
108 /// an "item-like" to something else can be implemented by a `Vec` instead of a
109 /// tree or hash map.
110 pub struct ItemLocalId {
116 pub use self::item_local_id_inner::ItemLocalId;
118 /// The `HirId` corresponding to `CRATE_NODE_ID` and `CRATE_DEF_INDEX`.
119 pub const CRATE_HIR_ID: HirId =
120 HirId { owner: CRATE_DEF_INDEX, local_id: ItemLocalId::from_u32_const(0) };
122 pub const DUMMY_HIR_ID: HirId = HirId { owner: CRATE_DEF_INDEX, local_id: DUMMY_ITEM_LOCAL_ID };
124 pub const DUMMY_ITEM_LOCAL_ID: ItemLocalId = ItemLocalId::MAX;
126 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, HashStable)]
127 pub struct Lifetime {
131 /// Either "`'a`", referring to a named lifetime definition,
132 /// or "``" (i.e., `kw::Invalid`), for elision placeholders.
134 /// HIR lowering inserts these placeholders in type paths that
135 /// refer to type definitions needing lifetime parameters,
136 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
137 pub name: LifetimeName,
140 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy, HashStable)]
142 /// Some user-given name like `T` or `'x`.
145 /// Synthetic name generated when user elided a lifetime in an impl header.
147 /// E.g., the lifetimes in cases like these:
149 /// impl Foo for &u32
150 /// impl Foo<'_> for u32
152 /// in that case, we rewrite to
154 /// impl<'f> Foo for &'f u32
155 /// impl<'f> Foo<'f> for u32
157 /// where `'f` is something like `Fresh(0)`. The indices are
158 /// unique per impl, but not necessarily continuous.
161 /// Indicates an illegal name was given and an error has been
162 /// reported (so we should squelch other derived errors). Occurs
163 /// when, e.g., `'_` is used in the wrong place.
168 pub fn ident(&self) -> Ident {
170 ParamName::Plain(ident) => ident,
171 ParamName::Fresh(_) | ParamName::Error => {
172 Ident::with_dummy_span(kw::UnderscoreLifetime)
177 pub fn modern(&self) -> ParamName {
179 ParamName::Plain(ident) => ParamName::Plain(ident.modern()),
180 param_name => param_name,
185 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy, HashStable)]
186 pub enum LifetimeName {
187 /// User-given names or fresh (synthetic) names.
190 /// User wrote nothing (e.g., the lifetime in `&u32`).
193 /// Implicit lifetime in a context like `dyn Foo`. This is
194 /// distinguished from implicit lifetimes elsewhere because the
195 /// lifetime that they default to must appear elsewhere within the
196 /// enclosing type. This means that, in an `impl Trait` context, we
197 /// don't have to create a parameter for them. That is, `impl
198 /// Trait<Item = &u32>` expands to an opaque type like `type
199 /// Foo<'a> = impl Trait<Item = &'a u32>`, but `impl Trait<item =
200 /// dyn Bar>` expands to `type Foo = impl Trait<Item = dyn Bar +
201 /// 'static>`. The latter uses `ImplicitObjectLifetimeDefault` so
202 /// that surrounding code knows not to create a lifetime
204 ImplicitObjectLifetimeDefault,
206 /// Indicates an error during lowering (usually `'_` in wrong place)
207 /// that was already reported.
210 /// User wrote specifies `'_`.
213 /// User wrote `'static`.
218 pub fn ident(&self) -> Ident {
220 LifetimeName::ImplicitObjectLifetimeDefault
221 | LifetimeName::Implicit
222 | LifetimeName::Error => Ident::invalid(),
223 LifetimeName::Underscore => Ident::with_dummy_span(kw::UnderscoreLifetime),
224 LifetimeName::Static => Ident::with_dummy_span(kw::StaticLifetime),
225 LifetimeName::Param(param_name) => param_name.ident(),
229 pub fn is_elided(&self) -> bool {
231 LifetimeName::ImplicitObjectLifetimeDefault
232 | LifetimeName::Implicit
233 | LifetimeName::Underscore => true,
235 // It might seem surprising that `Fresh(_)` counts as
236 // *not* elided -- but this is because, as far as the code
237 // in the compiler is concerned -- `Fresh(_)` variants act
238 // equivalently to "some fresh name". They correspond to
239 // early-bound regions on an impl, in other words.
240 LifetimeName::Error | LifetimeName::Param(_) | LifetimeName::Static => false,
244 fn is_static(&self) -> bool {
245 self == &LifetimeName::Static
248 pub fn modern(&self) -> LifetimeName {
250 LifetimeName::Param(param_name) => LifetimeName::Param(param_name.modern()),
251 lifetime_name => lifetime_name,
256 impl fmt::Display for Lifetime {
257 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
258 self.name.ident().fmt(f)
262 impl fmt::Debug for Lifetime {
263 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
268 print::to_string(print::NO_ANN, |s| s.print_lifetime(self))
274 pub fn is_elided(&self) -> bool {
275 self.name.is_elided()
278 pub fn is_static(&self) -> bool {
279 self.name.is_static()
283 /// A `Path` is essentially Rust's notion of a name; for instance,
284 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
285 /// along with a bunch of supporting information.
286 #[derive(RustcEncodable, RustcDecodable, HashStable)]
287 pub struct Path<'hir> {
289 /// The resolution for the path.
291 /// The segments in the path: the things separated by `::`.
292 pub segments: &'hir [PathSegment<'hir>],
296 pub fn is_global(&self) -> bool {
297 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
301 impl fmt::Debug for Path<'_> {
302 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
303 write!(f, "path({})", self)
307 impl fmt::Display for Path<'_> {
308 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
309 write!(f, "{}", print::to_string(print::NO_ANN, |s| s.print_path(self, false)))
313 /// A segment of a path: an identifier, an optional lifetime, and a set of
315 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
316 pub struct PathSegment<'hir> {
317 /// The identifier portion of this path segment.
318 #[stable_hasher(project(name))]
320 // `id` and `res` are optional. We currently only use these in save-analysis,
321 // any path segments without these will not have save-analysis info and
322 // therefore will not have 'jump to def' in IDEs, but otherwise will not be
323 // affected. (In general, we don't bother to get the defs for synthesized
324 // segments, only for segments which have come from the AST).
325 pub hir_id: Option<HirId>,
326 pub res: Option<Res>,
328 /// Type/lifetime parameters attached to this path. They come in
329 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
330 /// this is more than just simple syntactic sugar; the use of
331 /// parens affects the region binding rules, so we preserve the
333 pub args: Option<&'hir GenericArgs<'hir>>,
335 /// Whether to infer remaining type parameters, if any.
336 /// This only applies to expression and pattern paths, and
337 /// out of those only the segments with no type parameters
338 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
339 pub infer_args: bool,
342 impl<'hir> PathSegment<'hir> {
343 /// Converts an identifier to the corresponding segment.
344 pub fn from_ident(ident: Ident) -> PathSegment<'hir> {
345 PathSegment { ident, hir_id: None, res: None, infer_args: true, args: None }
348 pub fn generic_args(&self) -> &GenericArgs<'hir> {
349 if let Some(ref args) = self.args {
352 const DUMMY: &GenericArgs<'_> = &GenericArgs::none();
358 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
359 pub struct ConstArg {
360 pub value: AnonConst,
364 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
365 pub enum GenericArg<'hir> {
371 impl GenericArg<'_> {
372 pub fn span(&self) -> Span {
374 GenericArg::Lifetime(l) => l.span,
375 GenericArg::Type(t) => t.span,
376 GenericArg::Const(c) => c.span,
380 pub fn id(&self) -> HirId {
382 GenericArg::Lifetime(l) => l.hir_id,
383 GenericArg::Type(t) => t.hir_id,
384 GenericArg::Const(c) => c.value.hir_id,
388 pub fn is_const(&self) -> bool {
390 GenericArg::Const(_) => true,
396 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
397 pub struct GenericArgs<'hir> {
398 /// The generic arguments for this path segment.
399 pub args: &'hir [GenericArg<'hir>],
400 /// Bindings (equality constraints) on associated types, if present.
401 /// E.g., `Foo<A = Bar>`.
402 pub bindings: &'hir [TypeBinding<'hir>],
403 /// Were arguments written in parenthesized form `Fn(T) -> U`?
404 /// This is required mostly for pretty-printing and diagnostics,
405 /// but also for changing lifetime elision rules to be "function-like".
406 pub parenthesized: bool,
409 impl GenericArgs<'_> {
410 pub const fn none() -> Self {
411 Self { args: &[], bindings: &[], parenthesized: false }
414 pub fn is_empty(&self) -> bool {
415 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
418 pub fn inputs(&self) -> &[Ty<'_>] {
419 if self.parenthesized {
420 for arg in self.args {
422 GenericArg::Lifetime(_) => {}
423 GenericArg::Type(ref ty) => {
424 if let TyKind::Tup(ref tys) = ty.kind {
429 GenericArg::Const(_) => {}
433 bug!("GenericArgs::inputs: not a `Fn(T) -> U`");
436 pub fn own_counts(&self) -> GenericParamCount {
437 // We could cache this as a property of `GenericParamCount`, but
438 // the aim is to refactor this away entirely eventually and the
439 // presence of this method will be a constant reminder.
440 let mut own_counts: GenericParamCount = Default::default();
442 for arg in self.args {
444 GenericArg::Lifetime(_) => own_counts.lifetimes += 1,
445 GenericArg::Type(_) => own_counts.types += 1,
446 GenericArg::Const(_) => own_counts.consts += 1,
454 /// A modifier on a bound, currently this is only used for `?Sized`, where the
455 /// modifier is `Maybe`. Negative bounds should also be handled here.
456 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
457 pub enum TraitBoundModifier {
462 /// The AST represents all type param bounds as types.
463 /// `typeck::collect::compute_bounds` matches these against
464 /// the "special" built-in traits (see `middle::lang_items`) and
465 /// detects `Copy`, `Send` and `Sync`.
466 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
467 pub enum GenericBound<'hir> {
468 Trait(PolyTraitRef<'hir>, TraitBoundModifier),
472 impl GenericBound<'_> {
473 pub fn span(&self) -> Span {
475 &GenericBound::Trait(ref t, ..) => t.span,
476 &GenericBound::Outlives(ref l) => l.span,
481 pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
483 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable)]
484 pub enum LifetimeParamKind {
485 // Indicates that the lifetime definition was explicitly declared (e.g., in
486 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
489 // Indicates that the lifetime definition was synthetically added
490 // as a result of an in-band lifetime usage (e.g., in
491 // `fn foo(x: &'a u8) -> &'a u8 { x }`).
494 // Indication that the lifetime was elided (e.g., in both cases in
495 // `fn foo(x: &u8) -> &'_ u8 { x }`).
498 // Indication that the lifetime name was somehow in error.
502 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
503 pub enum GenericParamKind<'hir> {
504 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
506 kind: LifetimeParamKind,
509 default: Option<&'hir Ty<'hir>>,
510 synthetic: Option<SyntheticTyParamKind>,
517 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
518 pub struct GenericParam<'hir> {
521 pub attrs: &'hir [Attribute],
522 pub bounds: GenericBounds<'hir>,
524 pub pure_wrt_drop: bool,
525 pub kind: GenericParamKind<'hir>,
529 pub struct GenericParamCount {
530 pub lifetimes: usize,
535 /// Represents lifetimes and type parameters attached to a declaration
536 /// of a function, enum, trait, etc.
537 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
538 pub struct Generics<'hir> {
539 pub params: &'hir [GenericParam<'hir>],
540 pub where_clause: WhereClause<'hir>,
544 impl Generics<'hir> {
545 pub const fn empty() -> Generics<'hir> {
548 where_clause: WhereClause { predicates: &[], span: DUMMY_SP },
553 pub fn own_counts(&self) -> GenericParamCount {
554 // We could cache this as a property of `GenericParamCount`, but
555 // the aim is to refactor this away entirely eventually and the
556 // presence of this method will be a constant reminder.
557 let mut own_counts: GenericParamCount = Default::default();
559 for param in self.params {
561 GenericParamKind::Lifetime { .. } => own_counts.lifetimes += 1,
562 GenericParamKind::Type { .. } => own_counts.types += 1,
563 GenericParamKind::Const { .. } => own_counts.consts += 1,
570 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'_>> {
571 for param in self.params {
572 if name == param.name.ident().name {
579 pub fn spans(&self) -> MultiSpan {
580 if self.params.is_empty() {
583 self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
588 /// Synthetic type parameters are converted to another form during lowering; this allows
589 /// us to track the original form they had, and is useful for error messages.
590 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
591 pub enum SyntheticTyParamKind {
595 /// A where-clause in a definition.
596 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
597 pub struct WhereClause<'hir> {
598 pub predicates: &'hir [WherePredicate<'hir>],
599 // Only valid if predicates isn't empty.
603 impl WhereClause<'_> {
604 pub fn span(&self) -> Option<Span> {
605 if self.predicates.is_empty() { None } else { Some(self.span) }
608 /// The `WhereClause` under normal circumstances points at either the predicates or the empty
609 /// space where the `where` clause should be. Only of use for diagnostic suggestions.
610 pub fn span_for_predicates_or_empty_place(&self) -> Span {
615 /// A single predicate in a where-clause.
616 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
617 pub enum WherePredicate<'hir> {
618 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
619 BoundPredicate(WhereBoundPredicate<'hir>),
620 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
621 RegionPredicate(WhereRegionPredicate<'hir>),
622 /// An equality predicate (unsupported).
623 EqPredicate(WhereEqPredicate<'hir>),
626 impl WherePredicate<'_> {
627 pub fn span(&self) -> Span {
629 &WherePredicate::BoundPredicate(ref p) => p.span,
630 &WherePredicate::RegionPredicate(ref p) => p.span,
631 &WherePredicate::EqPredicate(ref p) => p.span,
636 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
637 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
638 pub struct WhereBoundPredicate<'hir> {
640 /// Any generics from a `for` binding.
641 pub bound_generic_params: &'hir [GenericParam<'hir>],
642 /// The type being bounded.
643 pub bounded_ty: &'hir Ty<'hir>,
644 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
645 pub bounds: GenericBounds<'hir>,
648 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
649 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
650 pub struct WhereRegionPredicate<'hir> {
652 pub lifetime: Lifetime,
653 pub bounds: GenericBounds<'hir>,
656 /// An equality predicate (e.g., `T = int`); currently unsupported.
657 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
658 pub struct WhereEqPredicate<'hir> {
661 pub lhs_ty: &'hir Ty<'hir>,
662 pub rhs_ty: &'hir Ty<'hir>,
665 #[derive(RustcEncodable, RustcDecodable, Debug)]
666 pub struct ModuleItems {
667 // Use BTreeSets here so items are in the same order as in the
668 // list of all items in Crate
669 pub items: BTreeSet<HirId>,
670 pub trait_items: BTreeSet<TraitItemId>,
671 pub impl_items: BTreeSet<ImplItemId>,
674 /// The top-level data structure that stores the entire contents of
675 /// the crate currently being compiled.
677 /// For more details, see the [rustc guide].
679 /// [rustc guide]: https://rust-lang.github.io/rustc-guide/hir.html
680 #[derive(RustcEncodable, RustcDecodable, Debug)]
681 pub struct Crate<'hir> {
682 pub module: Mod<'hir>,
683 pub attrs: &'hir [Attribute],
685 pub exported_macros: &'hir [MacroDef<'hir>],
686 // Attributes from non-exported macros, kept only for collecting the library feature list.
687 pub non_exported_macro_attrs: &'hir [Attribute],
689 // N.B., we use a `BTreeMap` here so that `visit_all_items` iterates
690 // over the ids in increasing order. In principle it should not
691 // matter what order we visit things in, but in *practice* it
692 // does, because it can affect the order in which errors are
693 // detected, which in turn can make compile-fail tests yield
694 // slightly different results.
695 pub items: BTreeMap<HirId, Item<'hir>>,
697 pub trait_items: BTreeMap<TraitItemId, TraitItem<'hir>>,
698 pub impl_items: BTreeMap<ImplItemId, ImplItem<'hir>>,
699 pub bodies: BTreeMap<BodyId, Body<'hir>>,
700 pub trait_impls: BTreeMap<DefId, Vec<HirId>>,
702 /// A list of the body ids written out in the order in which they
703 /// appear in the crate. If you're going to process all the bodies
704 /// in the crate, you should iterate over this list rather than the keys
706 pub body_ids: Vec<BodyId>,
708 /// A list of modules written out in the order in which they
709 /// appear in the crate. This includes the main crate module.
710 pub modules: BTreeMap<HirId, ModuleItems>,
714 pub fn item(&self, id: HirId) -> &Item<'hir> {
718 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem<'hir> {
719 &self.trait_items[&id]
722 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem<'hir> {
723 &self.impl_items[&id]
726 pub fn body(&self, id: BodyId) -> &Body<'hir> {
732 /// Visits all items in the crate in some deterministic (but
733 /// unspecified) order. If you just need to process every item,
734 /// but don't care about nesting, this method is the best choice.
736 /// If you do care about nesting -- usually because your algorithm
737 /// follows lexical scoping rules -- then you want a different
738 /// approach. You should override `visit_nested_item` in your
739 /// visitor and then call `intravisit::walk_crate` instead.
740 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
742 V: itemlikevisit::ItemLikeVisitor<'hir>,
744 for (_, item) in &self.items {
745 visitor.visit_item(item);
748 for (_, trait_item) in &self.trait_items {
749 visitor.visit_trait_item(trait_item);
752 for (_, impl_item) in &self.impl_items {
753 visitor.visit_impl_item(impl_item);
757 /// A parallel version of `visit_all_item_likes`.
758 pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
760 V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send,
764 par_for_each_in(&self.items, |(_, item)| {
765 visitor.visit_item(item);
769 par_for_each_in(&self.trait_items, |(_, trait_item)| {
770 visitor.visit_trait_item(trait_item);
774 par_for_each_in(&self.impl_items, |(_, impl_item)| {
775 visitor.visit_impl_item(impl_item);
782 /// A macro definition, in this crate or imported from another.
784 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
785 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
786 pub struct MacroDef<'hir> {
788 pub vis: Visibility<'hir>,
789 pub attrs: &'hir [Attribute],
792 pub body: TokenStream,
796 /// A block of statements `{ .. }`, which may have a label (in this case the
797 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
798 /// the `rules` being anything but `DefaultBlock`.
799 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
800 pub struct Block<'hir> {
801 /// Statements in a block.
802 pub stmts: &'hir [Stmt<'hir>],
803 /// An expression at the end of the block
804 /// without a semicolon, if any.
805 pub expr: Option<&'hir Expr<'hir>>,
806 #[stable_hasher(ignore)]
808 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
809 pub rules: BlockCheckMode,
811 /// If true, then there may exist `break 'a` values that aim to
812 /// break out of this block early.
813 /// Used by `'label: {}` blocks and by `try {}` blocks.
814 pub targeted_by_break: bool,
817 #[derive(RustcEncodable, RustcDecodable, HashStable)]
818 pub struct Pat<'hir> {
819 #[stable_hasher(ignore)]
821 pub kind: PatKind<'hir>,
825 impl fmt::Debug for Pat<'_> {
826 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
831 print::to_string(print::NO_ANN, |s| s.print_pat(self))
837 // FIXME(#19596) this is a workaround, but there should be a better way
838 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'_>) -> bool) -> bool {
845 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
846 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
847 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
848 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
849 Slice(before, slice, after) => {
850 before.iter().chain(slice.iter()).chain(after.iter()).all(|p| p.walk_short_(it))
855 /// Walk the pattern in left-to-right order,
856 /// short circuiting (with `.all(..)`) if `false` is returned.
858 /// Note that when visiting e.g. `Tuple(ps)`,
859 /// if visiting `ps[0]` returns `false`,
860 /// then `ps[1]` will not be visited.
861 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'_>) -> bool) -> bool {
862 self.walk_short_(&mut it)
865 // FIXME(#19596) this is a workaround, but there should be a better way
866 fn walk_(&self, it: &mut impl FnMut(&Pat<'_>) -> bool) {
873 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
874 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
875 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
876 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
877 Slice(before, slice, after) => {
878 before.iter().chain(slice.iter()).chain(after.iter()).for_each(|p| p.walk_(it))
883 /// Walk the pattern in left-to-right order.
885 /// If `it(pat)` returns `false`, the children are not visited.
886 pub fn walk(&self, mut it: impl FnMut(&Pat<'_>) -> bool) {
890 /// Walk the pattern in left-to-right order.
892 /// If you always want to recurse, prefer this method over `walk`.
893 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
901 /// A single field in a struct pattern.
903 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
904 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
905 /// except `is_shorthand` is true.
906 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
907 pub struct FieldPat<'hir> {
908 #[stable_hasher(ignore)]
910 /// The identifier for the field.
911 #[stable_hasher(project(name))]
913 /// The pattern the field is destructured to.
914 pub pat: &'hir Pat<'hir>,
915 pub is_shorthand: bool,
919 /// Explicit binding annotations given in the HIR for a binding. Note
920 /// that this is not the final binding *mode* that we infer after type
922 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
923 pub enum BindingAnnotation {
924 /// No binding annotation given: this means that the final binding mode
925 /// will depend on whether we have skipped through a `&` reference
926 /// when matching. For example, the `x` in `Some(x)` will have binding
927 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
928 /// ultimately be inferred to be by-reference.
930 /// Note that implicit reference skipping is not implemented yet (#42640).
933 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
936 /// Annotated as `ref`, like `ref x`
939 /// Annotated as `ref mut x`.
943 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
949 impl fmt::Display for RangeEnd {
950 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
951 f.write_str(match self {
952 RangeEnd::Included => "..=",
953 RangeEnd::Excluded => "..",
958 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
959 pub enum PatKind<'hir> {
960 /// Represents a wildcard pattern (i.e., `_`).
963 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
964 /// The `HirId` is the canonical ID for the variable being bound,
965 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
966 /// which is the pattern ID of the first `x`.
967 Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
969 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
970 /// The `bool` is `true` in the presence of a `..`.
971 Struct(QPath<'hir>, &'hir [FieldPat<'hir>], bool),
973 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
974 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
975 /// `0 <= position <= subpats.len()`
976 TupleStruct(QPath<'hir>, &'hir [&'hir Pat<'hir>], Option<usize>),
978 /// An or-pattern `A | B | C`.
979 /// Invariant: `pats.len() >= 2`.
980 Or(&'hir [&'hir Pat<'hir>]),
982 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
985 /// A tuple pattern (e.g., `(a, b)`).
986 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
987 /// `0 <= position <= subpats.len()`
988 Tuple(&'hir [&'hir Pat<'hir>], Option<usize>),
991 Box(&'hir Pat<'hir>),
993 /// A reference pattern (e.g., `&mut (a, b)`).
994 Ref(&'hir Pat<'hir>, Mutability),
997 Lit(&'hir Expr<'hir>),
999 /// A range pattern (e.g., `1..=2` or `1..2`).
1000 Range(&'hir Expr<'hir>, &'hir Expr<'hir>, RangeEnd),
1002 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
1004 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
1005 /// If `slice` exists, then `after` can be non-empty.
1007 /// The representation for e.g., `[a, b, .., c, d]` is:
1009 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
1011 Slice(&'hir [&'hir Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [&'hir Pat<'hir>]),
1014 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1015 pub enum BinOpKind {
1016 /// The `+` operator (addition).
1018 /// The `-` operator (subtraction).
1020 /// The `*` operator (multiplication).
1022 /// The `/` operator (division).
1024 /// The `%` operator (modulus).
1026 /// The `&&` operator (logical and).
1028 /// The `||` operator (logical or).
1030 /// The `^` operator (bitwise xor).
1032 /// The `&` operator (bitwise and).
1034 /// The `|` operator (bitwise or).
1036 /// The `<<` operator (shift left).
1038 /// The `>>` operator (shift right).
1040 /// The `==` operator (equality).
1042 /// The `<` operator (less than).
1044 /// The `<=` operator (less than or equal to).
1046 /// The `!=` operator (not equal to).
1048 /// The `>=` operator (greater than or equal to).
1050 /// The `>` operator (greater than).
1055 pub fn as_str(self) -> &'static str {
1057 BinOpKind::Add => "+",
1058 BinOpKind::Sub => "-",
1059 BinOpKind::Mul => "*",
1060 BinOpKind::Div => "/",
1061 BinOpKind::Rem => "%",
1062 BinOpKind::And => "&&",
1063 BinOpKind::Or => "||",
1064 BinOpKind::BitXor => "^",
1065 BinOpKind::BitAnd => "&",
1066 BinOpKind::BitOr => "|",
1067 BinOpKind::Shl => "<<",
1068 BinOpKind::Shr => ">>",
1069 BinOpKind::Eq => "==",
1070 BinOpKind::Lt => "<",
1071 BinOpKind::Le => "<=",
1072 BinOpKind::Ne => "!=",
1073 BinOpKind::Ge => ">=",
1074 BinOpKind::Gt => ">",
1078 pub fn is_lazy(self) -> bool {
1080 BinOpKind::And | BinOpKind::Or => true,
1085 pub fn is_shift(self) -> bool {
1087 BinOpKind::Shl | BinOpKind::Shr => true,
1092 pub fn is_comparison(self) -> bool {
1099 | BinOpKind::Ge => true,
1111 | BinOpKind::Shr => false,
1115 /// Returns `true` if the binary operator takes its arguments by value.
1116 pub fn is_by_value(self) -> bool {
1117 !self.is_comparison()
1121 impl Into<ast::BinOpKind> for BinOpKind {
1122 fn into(self) -> ast::BinOpKind {
1124 BinOpKind::Add => ast::BinOpKind::Add,
1125 BinOpKind::Sub => ast::BinOpKind::Sub,
1126 BinOpKind::Mul => ast::BinOpKind::Mul,
1127 BinOpKind::Div => ast::BinOpKind::Div,
1128 BinOpKind::Rem => ast::BinOpKind::Rem,
1129 BinOpKind::And => ast::BinOpKind::And,
1130 BinOpKind::Or => ast::BinOpKind::Or,
1131 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1132 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1133 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1134 BinOpKind::Shl => ast::BinOpKind::Shl,
1135 BinOpKind::Shr => ast::BinOpKind::Shr,
1136 BinOpKind::Eq => ast::BinOpKind::Eq,
1137 BinOpKind::Lt => ast::BinOpKind::Lt,
1138 BinOpKind::Le => ast::BinOpKind::Le,
1139 BinOpKind::Ne => ast::BinOpKind::Ne,
1140 BinOpKind::Ge => ast::BinOpKind::Ge,
1141 BinOpKind::Gt => ast::BinOpKind::Gt,
1146 pub type BinOp = Spanned<BinOpKind>;
1148 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1150 /// The `*` operator (deferencing).
1152 /// The `!` operator (logical negation).
1154 /// The `-` operator (negation).
1159 pub fn as_str(self) -> &'static str {
1167 /// Returns `true` if the unary operator takes its argument by value.
1168 pub fn is_by_value(self) -> bool {
1170 UnNeg | UnNot => true,
1177 #[derive(RustcEncodable, RustcDecodable, HashStable)]
1178 pub struct Stmt<'hir> {
1180 pub kind: StmtKind<'hir>,
1184 impl fmt::Debug for Stmt<'_> {
1185 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1190 print::to_string(print::NO_ANN, |s| s.print_stmt(self))
1195 /// The contents of a statement.
1196 #[derive(RustcEncodable, RustcDecodable, HashStable)]
1197 pub enum StmtKind<'hir> {
1198 /// A local (`let`) binding.
1199 Local(&'hir Local<'hir>),
1201 /// An item binding.
1204 /// An expression without a trailing semi-colon (must have unit type).
1205 Expr(&'hir Expr<'hir>),
1207 /// An expression with a trailing semi-colon (may have any type).
1208 Semi(&'hir Expr<'hir>),
1211 impl StmtKind<'hir> {
1212 pub fn attrs(&self) -> &'hir [Attribute] {
1214 StmtKind::Local(ref l) => &l.attrs,
1215 StmtKind::Item(_) => &[],
1216 StmtKind::Expr(ref e) | StmtKind::Semi(ref e) => &e.attrs,
1221 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1222 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1223 pub struct Local<'hir> {
1224 pub pat: &'hir Pat<'hir>,
1225 /// Type annotation, if any (otherwise the type will be inferred).
1226 pub ty: Option<&'hir Ty<'hir>>,
1227 /// Initializer expression to set the value, if any.
1228 pub init: Option<&'hir Expr<'hir>>,
1232 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1233 /// desugaring. Otherwise will be `Normal`.
1234 pub source: LocalSource,
1237 /// Represents a single arm of a `match` expression, e.g.
1238 /// `<pat> (if <guard>) => <body>`.
1239 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1240 pub struct Arm<'hir> {
1241 #[stable_hasher(ignore)]
1244 pub attrs: &'hir [Attribute],
1245 /// If this pattern and the optional guard matches, then `body` is evaluated.
1246 pub pat: &'hir Pat<'hir>,
1247 /// Optional guard clause.
1248 pub guard: Option<Guard<'hir>>,
1249 /// The expression the arm evaluates to if this arm matches.
1250 pub body: &'hir Expr<'hir>,
1253 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1254 pub enum Guard<'hir> {
1255 If(&'hir Expr<'hir>),
1258 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1259 pub struct Field<'hir> {
1260 #[stable_hasher(ignore)]
1263 pub expr: &'hir Expr<'hir>,
1265 pub is_shorthand: bool,
1268 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1269 pub enum BlockCheckMode {
1271 UnsafeBlock(UnsafeSource),
1272 PushUnsafeBlock(UnsafeSource),
1273 PopUnsafeBlock(UnsafeSource),
1276 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1277 pub enum UnsafeSource {
1282 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1287 /// The body of a function, closure, or constant value. In the case of
1288 /// a function, the body contains not only the function body itself
1289 /// (which is an expression), but also the argument patterns, since
1290 /// those are something that the caller doesn't really care about.
1295 /// fn foo((x, y): (u32, u32)) -> u32 {
1300 /// Here, the `Body` associated with `foo()` would contain:
1302 /// - an `params` array containing the `(x, y)` pattern
1303 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1304 /// - `generator_kind` would be `None`
1306 /// All bodies have an **owner**, which can be accessed via the HIR
1307 /// map using `body_owner_def_id()`.
1308 #[derive(RustcEncodable, RustcDecodable, Debug)]
1309 pub struct Body<'hir> {
1310 pub params: &'hir [Param<'hir>],
1311 pub value: Expr<'hir>,
1312 pub generator_kind: Option<GeneratorKind>,
1316 pub fn id(&self) -> BodyId {
1317 BodyId { hir_id: self.value.hir_id }
1320 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1325 /// The type of source expression that caused this generator to be created.
1326 #[derive(Clone, PartialEq, Eq, HashStable, RustcEncodable, RustcDecodable, Debug, Copy)]
1327 pub enum GeneratorKind {
1328 /// An explicit `async` block or the body of an async function.
1329 Async(AsyncGeneratorKind),
1331 /// A generator literal created via a `yield` inside a closure.
1335 impl fmt::Display for GeneratorKind {
1336 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1338 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1339 GeneratorKind::Gen => f.write_str("generator"),
1344 /// In the case of a generator created as part of an async construct,
1345 /// which kind of async construct caused it to be created?
1347 /// This helps error messages but is also used to drive coercions in
1348 /// type-checking (see #60424).
1349 #[derive(Clone, PartialEq, Eq, HashStable, RustcEncodable, RustcDecodable, Debug, Copy)]
1350 pub enum AsyncGeneratorKind {
1351 /// An explicit `async` block written by the user.
1354 /// An explicit `async` block written by the user.
1357 /// The `async` block generated as the body of an async function.
1361 impl fmt::Display for AsyncGeneratorKind {
1362 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1363 f.write_str(match self {
1364 AsyncGeneratorKind::Block => "`async` block",
1365 AsyncGeneratorKind::Closure => "`async` closure body",
1366 AsyncGeneratorKind::Fn => "`async fn` body",
1371 #[derive(Copy, Clone, Debug)]
1372 pub enum BodyOwnerKind {
1373 /// Functions and methods.
1379 /// Constants and associated constants.
1382 /// Initializer of a `static` item.
1386 impl BodyOwnerKind {
1387 pub fn is_fn_or_closure(self) -> bool {
1389 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1390 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1396 pub type Lit = Spanned<LitKind>;
1398 /// A constant (expression) that's not an item or associated item,
1399 /// but needs its own `DefId` for type-checking, const-eval, etc.
1400 /// These are usually found nested inside types (e.g., array lengths)
1401 /// or expressions (e.g., repeat counts), and also used to define
1402 /// explicit discriminant values for enum variants.
1403 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1404 pub struct AnonConst {
1410 #[derive(RustcEncodable, RustcDecodable)]
1411 pub struct Expr<'hir> {
1413 pub kind: ExprKind<'hir>,
1418 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1419 #[cfg(target_arch = "x86_64")]
1420 static_assert_size!(Expr<'static>, 64);
1423 pub fn precedence(&self) -> ExprPrecedence {
1425 ExprKind::Box(_) => ExprPrecedence::Box,
1426 ExprKind::Array(_) => ExprPrecedence::Array,
1427 ExprKind::Call(..) => ExprPrecedence::Call,
1428 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1429 ExprKind::Tup(_) => ExprPrecedence::Tup,
1430 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1431 ExprKind::Unary(..) => ExprPrecedence::Unary,
1432 ExprKind::Lit(_) => ExprPrecedence::Lit,
1433 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1434 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1435 ExprKind::Loop(..) => ExprPrecedence::Loop,
1436 ExprKind::Match(..) => ExprPrecedence::Match,
1437 ExprKind::Closure(..) => ExprPrecedence::Closure,
1438 ExprKind::Block(..) => ExprPrecedence::Block,
1439 ExprKind::Assign(..) => ExprPrecedence::Assign,
1440 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1441 ExprKind::Field(..) => ExprPrecedence::Field,
1442 ExprKind::Index(..) => ExprPrecedence::Index,
1443 ExprKind::Path(..) => ExprPrecedence::Path,
1444 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1445 ExprKind::Break(..) => ExprPrecedence::Break,
1446 ExprKind::Continue(..) => ExprPrecedence::Continue,
1447 ExprKind::Ret(..) => ExprPrecedence::Ret,
1448 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1449 ExprKind::Struct(..) => ExprPrecedence::Struct,
1450 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1451 ExprKind::Yield(..) => ExprPrecedence::Yield,
1452 ExprKind::Err => ExprPrecedence::Err,
1456 // Whether this looks like a place expr, without checking for deref
1458 // This will return `true` in some potentially surprising cases such as
1459 // `CONSTANT.field`.
1460 pub fn is_syntactic_place_expr(&self) -> bool {
1461 self.is_place_expr(|_| true)
1464 // Whether this is a place expression.
1465 // `allow_projections_from` should return `true` if indexing a field or
1466 // index expression based on the given expression should be considered a
1467 // place expression.
1468 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1470 ExprKind::Path(QPath::Resolved(_, ref path)) => match path.res {
1471 Res::Local(..) | Res::Def(DefKind::Static, _) | Res::Err => true,
1475 // Type ascription inherits its place expression kind from its
1477 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1478 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1480 ExprKind::Unary(UnDeref, _) => true,
1482 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1483 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1486 // Partially qualified paths in expressions can only legally
1487 // refer to associated items which are always rvalues.
1488 ExprKind::Path(QPath::TypeRelative(..))
1489 | ExprKind::Call(..)
1490 | ExprKind::MethodCall(..)
1491 | ExprKind::Struct(..)
1493 | ExprKind::Match(..)
1494 | ExprKind::Closure(..)
1495 | ExprKind::Block(..)
1496 | ExprKind::Repeat(..)
1497 | ExprKind::Array(..)
1498 | ExprKind::Break(..)
1499 | ExprKind::Continue(..)
1501 | ExprKind::Loop(..)
1502 | ExprKind::Assign(..)
1503 | ExprKind::InlineAsm(..)
1504 | ExprKind::AssignOp(..)
1506 | ExprKind::Unary(..)
1508 | ExprKind::AddrOf(..)
1509 | ExprKind::Binary(..)
1510 | ExprKind::Yield(..)
1511 | ExprKind::Cast(..)
1512 | ExprKind::DropTemps(..)
1513 | ExprKind::Err => false,
1517 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1518 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1519 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1520 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1521 /// beyond remembering to call this function before doing analysis on it.
1522 pub fn peel_drop_temps(&self) -> &Self {
1523 let mut expr = self;
1524 while let ExprKind::DropTemps(inner) = &expr.kind {
1531 impl fmt::Debug for Expr<'_> {
1532 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1537 print::to_string(print::NO_ANN, |s| s.print_expr(self))
1542 /// Checks if the specified expression is a built-in range literal.
1543 /// (See: `LoweringContext::lower_expr()`).
1545 /// FIXME(#60607): This function is a hack. If and when we have `QPath::Lang(...)`,
1546 /// we can use that instead as simpler, more reliable mechanism, as opposed to using `SourceMap`.
1547 pub fn is_range_literal(sm: &SourceMap, expr: &Expr<'_>) -> bool {
1548 // Returns whether the given path represents a (desugared) range,
1549 // either in std or core, i.e. has either a `::std::ops::Range` or
1550 // `::core::ops::Range` prefix.
1551 fn is_range_path(path: &Path<'_>) -> bool {
1552 let segs: Vec<_> = path.segments.iter().map(|seg| seg.ident.to_string()).collect();
1553 let segs: Vec<_> = segs.iter().map(|seg| &**seg).collect();
1555 // "{{root}}" is the equivalent of `::` prefix in `Path`.
1556 if let ["{{root}}", std_core, "ops", range] = segs.as_slice() {
1557 (*std_core == "std" || *std_core == "core") && range.starts_with("Range")
1563 // Check whether a span corresponding to a range expression is a
1564 // range literal, rather than an explicit struct or `new()` call.
1565 fn is_lit(sm: &SourceMap, span: &Span) -> bool {
1566 let end_point = sm.end_point(*span);
1568 if let Ok(end_string) = sm.span_to_snippet(end_point) {
1569 !(end_string.ends_with("}") || end_string.ends_with(")"))
1576 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1577 ExprKind::Struct(ref qpath, _, _) => {
1578 if let QPath::Resolved(None, ref path) = **qpath {
1579 return is_range_path(&path) && is_lit(sm, &expr.span);
1583 // `..` desugars to its struct path.
1584 ExprKind::Path(QPath::Resolved(None, ref path)) => {
1585 return is_range_path(&path) && is_lit(sm, &expr.span);
1588 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1589 ExprKind::Call(ref func, _) => {
1590 if let ExprKind::Path(QPath::TypeRelative(ref ty, ref segment)) = func.kind {
1591 if let TyKind::Path(QPath::Resolved(None, ref path)) = ty.kind {
1592 let new_call = segment.ident.name == sym::new;
1593 return is_range_path(&path) && is_lit(sm, &expr.span) && new_call;
1604 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1605 pub enum ExprKind<'hir> {
1606 /// A `box x` expression.
1607 Box(&'hir Expr<'hir>),
1608 /// An array (e.g., `[a, b, c, d]`).
1609 Array(&'hir [Expr<'hir>]),
1610 /// A function call.
1612 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1613 /// and the second field is the list of arguments.
1614 /// This also represents calling the constructor of
1615 /// tuple-like ADTs such as tuple structs and enum variants.
1616 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1617 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1619 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1620 /// (within the angle brackets).
1621 /// The first element of the vector of `Expr`s is the expression that evaluates
1622 /// to the object on which the method is being called on (the receiver),
1623 /// and the remaining elements are the rest of the arguments.
1624 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1625 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1627 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1628 /// the `hir_id` of the `MethodCall` node itself.
1630 /// [`type_dependent_def_id`]: ../ty/struct.TypeckTables.html#method.type_dependent_def_id
1631 MethodCall(&'hir PathSegment<'hir>, Span, &'hir [Expr<'hir>]),
1632 /// A tuple (e.g., `(a, b, c, d)`).
1633 Tup(&'hir [Expr<'hir>]),
1634 /// A binary operation (e.g., `a + b`, `a * b`).
1635 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1636 /// A unary operation (e.g., `!x`, `*x`).
1637 Unary(UnOp, &'hir Expr<'hir>),
1638 /// A literal (e.g., `1`, `"foo"`).
1640 /// A cast (e.g., `foo as f64`).
1641 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1642 /// A type reference (e.g., `Foo`).
1643 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1644 /// Wraps the expression in a terminating scope.
1645 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1647 /// This construct only exists to tweak the drop order in HIR lowering.
1648 /// An example of that is the desugaring of `for` loops.
1649 DropTemps(&'hir Expr<'hir>),
1650 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1652 /// I.e., `'label: loop { <block> }`.
1653 Loop(&'hir Block<'hir>, Option<Label>, LoopSource),
1654 /// A `match` block, with a source that indicates whether or not it is
1655 /// the result of a desugaring, and if so, which kind.
1656 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1657 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1659 /// The `Span` is the argument block `|...|`.
1661 /// This may also be a generator literal or an `async block` as indicated by the
1662 /// `Option<Movability>`.
1663 Closure(CaptureBy, &'hir FnDecl<'hir>, BodyId, Span, Option<Movability>),
1664 /// A block (e.g., `'label: { ... }`).
1665 Block(&'hir Block<'hir>, Option<Label>),
1667 /// An assignment (e.g., `a = foo()`).
1668 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1669 /// An assignment with an operator.
1672 AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1673 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1674 Field(&'hir Expr<'hir>, Ident),
1675 /// An indexing operation (`foo[2]`).
1676 Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1678 /// Path to a definition, possibly containing lifetime or type parameters.
1681 /// A referencing operation (i.e., `&a` or `&mut a`).
1682 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1683 /// A `break`, with an optional label to break.
1684 Break(Destination, Option<&'hir Expr<'hir>>),
1685 /// A `continue`, with an optional label.
1686 Continue(Destination),
1687 /// A `return`, with an optional value to be returned.
1688 Ret(Option<&'hir Expr<'hir>>),
1690 /// Inline assembly (from `asm!`), with its outputs and inputs.
1691 InlineAsm(&'hir InlineAsm<'hir>),
1693 /// A struct or struct-like variant literal expression.
1695 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1696 /// where `base` is the `Option<Expr>`.
1697 Struct(&'hir QPath<'hir>, &'hir [Field<'hir>], Option<&'hir Expr<'hir>>),
1699 /// An array literal constructed from one repeated element.
1701 /// E.g., `[1; 5]`. The first expression is the element
1702 /// to be repeated; the second is the number of times to repeat it.
1703 Repeat(&'hir Expr<'hir>, AnonConst),
1705 /// A suspension point for generators (i.e., `yield <expr>`).
1706 Yield(&'hir Expr<'hir>, YieldSource),
1708 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1712 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1714 /// To resolve the path to a `DefId`, call [`qpath_res`].
1716 /// [`qpath_res`]: ../ty/struct.TypeckTables.html#method.qpath_res
1717 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1718 pub enum QPath<'hir> {
1719 /// Path to a definition, optionally "fully-qualified" with a `Self`
1720 /// type, if the path points to an associated item in a trait.
1722 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1723 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1724 /// even though they both have the same two-segment `Clone::clone` `Path`.
1725 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
1727 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1728 /// Will be resolved by type-checking to an associated item.
1730 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1731 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1732 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1733 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
1736 /// Hints at the original code for a let statement.
1737 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1738 pub enum LocalSource {
1739 /// A `match _ { .. }`.
1741 /// A desugared `for _ in _ { .. }` loop.
1743 /// When lowering async functions, we create locals within the `async move` so that
1744 /// all parameters are dropped after the future is polled.
1746 /// ```ignore (pseudo-Rust)
1747 /// async fn foo(<pattern> @ x: Type) {
1749 /// let <pattern> = x;
1754 /// A desugared `<expr>.await`.
1758 /// Hints at the original code for a `match _ { .. }`.
1759 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
1760 pub enum MatchSource {
1761 /// A `match _ { .. }`.
1763 /// An `if _ { .. }` (optionally with `else { .. }`).
1764 IfDesugar { contains_else_clause: bool },
1765 /// An `if let _ = _ { .. }` (optionally with `else { .. }`).
1766 IfLetDesugar { contains_else_clause: bool },
1767 /// A `while _ { .. }` (which was desugared to a `loop { match _ { .. } }`).
1769 /// A `while let _ = _ { .. }` (which was desugared to a
1770 /// `loop { match _ { .. } }`).
1772 /// A desugared `for _ in _ { .. }` loop.
1774 /// A desugared `?` operator.
1776 /// A desugared `<expr>.await`.
1781 pub fn name(self) -> &'static str {
1785 IfDesugar { .. } | IfLetDesugar { .. } => "if",
1786 WhileDesugar | WhileLetDesugar => "while",
1787 ForLoopDesugar => "for",
1789 AwaitDesugar => ".await",
1794 /// The loop type that yielded an `ExprKind::Loop`.
1795 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1796 pub enum LoopSource {
1797 /// A `loop { .. }` loop.
1799 /// A `while _ { .. }` loop.
1801 /// A `while let _ = _ { .. }` loop.
1803 /// A `for _ in _ { .. }` loop.
1808 pub fn name(self) -> &'static str {
1810 LoopSource::Loop => "loop",
1811 LoopSource::While | LoopSource::WhileLet => "while",
1812 LoopSource::ForLoop => "for",
1817 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1818 pub enum LoopIdError {
1820 UnlabeledCfInWhileCondition,
1824 impl fmt::Display for LoopIdError {
1825 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1826 f.write_str(match self {
1827 LoopIdError::OutsideLoopScope => "not inside loop scope",
1828 LoopIdError::UnlabeledCfInWhileCondition => {
1829 "unlabeled control flow (break or continue) in while condition"
1831 LoopIdError::UnresolvedLabel => "label not found",
1836 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1837 pub struct Destination {
1838 // This is `Some(_)` iff there is an explicit user-specified `label
1839 pub label: Option<Label>,
1841 // These errors are caught and then reported during the diagnostics pass in
1842 // librustc_passes/loops.rs
1843 pub target_id: Result<HirId, LoopIdError>,
1846 /// The yield kind that caused an `ExprKind::Yield`.
1847 #[derive(Copy, Clone, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable, HashStable)]
1848 pub enum YieldSource {
1849 /// An `<expr>.await`.
1851 /// A plain `yield`.
1855 impl fmt::Display for YieldSource {
1856 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1857 f.write_str(match self {
1858 YieldSource::Await => "`await`",
1859 YieldSource::Yield => "`yield`",
1864 impl From<GeneratorKind> for YieldSource {
1865 fn from(kind: GeneratorKind) -> Self {
1867 // Guess based on the kind of the current generator.
1868 GeneratorKind::Gen => Self::Yield,
1869 GeneratorKind::Async(_) => Self::Await,
1874 // N.B., if you change this, you'll probably want to change the corresponding
1875 // type structure in middle/ty.rs as well.
1876 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1877 pub struct MutTy<'hir> {
1878 pub ty: &'hir Ty<'hir>,
1879 pub mutbl: Mutability,
1882 /// Represents a function's signature in a trait declaration,
1883 /// trait implementation, or a free function.
1884 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1885 pub struct FnSig<'hir> {
1886 pub header: FnHeader,
1887 pub decl: &'hir FnDecl<'hir>,
1890 // The bodies for items are stored "out of line", in a separate
1891 // hashmap in the `Crate`. Here we just record the node-id of the item
1892 // so it can fetched later.
1893 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1894 pub struct TraitItemId {
1898 /// Represents an item declaration within a trait declaration,
1899 /// possibly including a default implementation. A trait item is
1900 /// either required (meaning it doesn't have an implementation, just a
1901 /// signature) or provided (meaning it has a default implementation).
1902 #[derive(RustcEncodable, RustcDecodable, Debug)]
1903 pub struct TraitItem<'hir> {
1906 pub attrs: &'hir [Attribute],
1907 pub generics: Generics<'hir>,
1908 pub kind: TraitItemKind<'hir>,
1912 /// Represents a trait method's body (or just argument names).
1913 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1914 pub enum TraitMethod<'hir> {
1915 /// No default body in the trait, just a signature.
1916 Required(&'hir [Ident]),
1918 /// Both signature and body are provided in the trait.
1922 /// Represents a trait method or associated constant or type
1923 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1924 pub enum TraitItemKind<'hir> {
1925 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
1926 Const(&'hir Ty<'hir>, Option<BodyId>),
1927 /// A method with an optional body.
1928 Method(FnSig<'hir>, TraitMethod<'hir>),
1929 /// An associated type with (possibly empty) bounds and optional concrete
1931 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
1934 // The bodies for items are stored "out of line", in a separate
1935 // hashmap in the `Crate`. Here we just record the node-id of the item
1936 // so it can fetched later.
1937 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1938 pub struct ImplItemId {
1942 /// Represents anything within an `impl` block.
1943 #[derive(RustcEncodable, RustcDecodable, Debug)]
1944 pub struct ImplItem<'hir> {
1947 pub vis: Visibility<'hir>,
1948 pub defaultness: Defaultness,
1949 pub attrs: &'hir [Attribute],
1950 pub generics: Generics<'hir>,
1951 pub kind: ImplItemKind<'hir>,
1955 /// Represents various kinds of content within an `impl`.
1956 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1957 pub enum ImplItemKind<'hir> {
1958 /// An associated constant of the given type, set to the constant result
1959 /// of the expression.
1960 Const(&'hir Ty<'hir>, BodyId),
1961 /// A method implementation with the given signature and body.
1962 Method(FnSig<'hir>, BodyId),
1963 /// An associated type.
1964 TyAlias(&'hir Ty<'hir>),
1965 /// An associated `type = impl Trait`.
1966 OpaqueTy(GenericBounds<'hir>),
1969 /// Bind a type to an associated type (i.e., `A = Foo`).
1971 /// Bindings like `A: Debug` are represented as a special type `A =
1972 /// $::Debug` that is understood by the astconv code.
1974 /// FIXME(alexreg): why have a separate type for the binding case,
1975 /// wouldn't it be better to make the `ty` field an enum like the
1979 /// enum TypeBindingKind {
1984 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1985 pub struct TypeBinding<'hir> {
1987 #[stable_hasher(project(name))]
1989 pub kind: TypeBindingKind<'hir>,
1993 // Represents the two kinds of type bindings.
1994 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1995 pub enum TypeBindingKind<'hir> {
1996 /// E.g., `Foo<Bar: Send>`.
1997 Constraint { bounds: &'hir [GenericBound<'hir>] },
1998 /// E.g., `Foo<Bar = ()>`.
1999 Equality { ty: &'hir Ty<'hir> },
2002 impl TypeBinding<'_> {
2003 pub fn ty(&self) -> &Ty<'_> {
2005 TypeBindingKind::Equality { ref ty } => ty,
2006 _ => bug!("expected equality type binding for parenthesized generic args"),
2011 #[derive(RustcEncodable, RustcDecodable)]
2012 pub struct Ty<'hir> {
2014 pub kind: TyKind<'hir>,
2018 impl fmt::Debug for Ty<'_> {
2019 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2020 write!(f, "type({})", print::to_string(print::NO_ANN, |s| s.print_type(self)))
2024 /// Not represented directly in the AST; referred to by name through a `ty_path`.
2025 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
2035 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2036 pub struct BareFnTy<'hir> {
2037 pub unsafety: Unsafety,
2039 pub generic_params: &'hir [GenericParam<'hir>],
2040 pub decl: &'hir FnDecl<'hir>,
2041 pub param_names: &'hir [Ident],
2044 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2045 pub struct OpaqueTy<'hir> {
2046 pub generics: Generics<'hir>,
2047 pub bounds: GenericBounds<'hir>,
2048 pub impl_trait_fn: Option<DefId>,
2049 pub origin: OpaqueTyOrigin,
2052 /// From whence the opaque type came.
2053 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2054 pub enum OpaqueTyOrigin {
2055 /// `type Foo = impl Trait;`
2063 /// The various kinds of types recognized by the compiler.
2064 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2065 pub enum TyKind<'hir> {
2066 /// A variable length slice (i.e., `[T]`).
2067 Slice(&'hir Ty<'hir>),
2068 /// A fixed length array (i.e., `[T; n]`).
2069 Array(&'hir Ty<'hir>, AnonConst),
2070 /// A raw pointer (i.e., `*const T` or `*mut T`).
2072 /// A reference (i.e., `&'a T` or `&'a mut T`).
2073 Rptr(Lifetime, MutTy<'hir>),
2074 /// A bare function (e.g., `fn(usize) -> bool`).
2075 BareFn(&'hir BareFnTy<'hir>),
2076 /// The never type (`!`).
2078 /// A tuple (`(A, B, C, D, ...)`).
2079 Tup(&'hir [Ty<'hir>]),
2080 /// A path to a type definition (`module::module::...::Type`), or an
2081 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2083 /// Type parameters may be stored in each `PathSegment`.
2085 /// A type definition itself. This is currently only used for the `type Foo = impl Trait`
2086 /// item that `impl Trait` in return position desugars to.
2088 /// The generic argument list contains the lifetimes (and in the future possibly parameters)
2089 /// that are actually bound on the `impl Trait`.
2090 Def(ItemId, &'hir [GenericArg<'hir>]),
2091 /// A trait object type `Bound1 + Bound2 + Bound3`
2092 /// where `Bound` is a trait or a lifetime.
2093 TraitObject(&'hir [PolyTraitRef<'hir>], Lifetime),
2096 /// `TyKind::Infer` means the type should be inferred instead of it having been
2097 /// specified. This can appear anywhere in a type.
2099 /// Placeholder for a type that has failed to be defined.
2103 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable, PartialEq)]
2104 pub struct InlineAsmOutput {
2105 pub constraint: Symbol,
2107 pub is_indirect: bool,
2111 // NOTE(eddyb) This is used within MIR as well, so unlike the rest of the HIR,
2112 // it needs to be `Clone` and use plain `Vec<T>` instead of arena-allocated slice.
2113 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable, PartialEq)]
2114 pub struct InlineAsmInner {
2116 pub asm_str_style: StrStyle,
2117 pub outputs: Vec<InlineAsmOutput>,
2118 pub inputs: Vec<Symbol>,
2119 pub clobbers: Vec<Symbol>,
2121 pub alignstack: bool,
2122 pub dialect: AsmDialect,
2125 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2126 pub struct InlineAsm<'hir> {
2127 pub inner: InlineAsmInner,
2128 pub outputs_exprs: &'hir [Expr<'hir>],
2129 pub inputs_exprs: &'hir [Expr<'hir>],
2132 /// Represents a parameter in a function header.
2133 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2134 pub struct Param<'hir> {
2135 pub attrs: &'hir [Attribute],
2137 pub pat: &'hir Pat<'hir>,
2141 /// Represents the header (not the body) of a function declaration.
2142 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2143 pub struct FnDecl<'hir> {
2144 /// The types of the function's parameters.
2146 /// Additional argument data is stored in the function's [body](Body::parameters).
2147 pub inputs: &'hir [Ty<'hir>],
2148 pub output: FunctionRetTy<'hir>,
2149 pub c_variadic: bool,
2150 /// Does the function have an implicit self?
2151 pub implicit_self: ImplicitSelfKind,
2154 /// Represents what type of implicit self a function has, if any.
2155 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2156 pub enum ImplicitSelfKind {
2157 /// Represents a `fn x(self);`.
2159 /// Represents a `fn x(mut self);`.
2161 /// Represents a `fn x(&self);`.
2163 /// Represents a `fn x(&mut self);`.
2165 /// Represents when a function does not have a self argument or
2166 /// when a function has a `self: X` argument.
2170 impl ImplicitSelfKind {
2171 /// Does this represent an implicit self?
2172 pub fn has_implicit_self(&self) -> bool {
2174 ImplicitSelfKind::None => false,
2197 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2198 pub enum Defaultness {
2199 Default { has_value: bool },
2204 pub fn has_value(&self) -> bool {
2206 Defaultness::Default { has_value, .. } => has_value,
2207 Defaultness::Final => true,
2211 pub fn is_final(&self) -> bool {
2212 *self == Defaultness::Final
2215 pub fn is_default(&self) -> bool {
2217 Defaultness::Default { .. } => true,
2223 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2224 pub enum FunctionRetTy<'hir> {
2225 /// Return type is not specified.
2227 /// Functions default to `()` and
2228 /// closures default to inference. Span points to where return
2229 /// type would be inserted.
2230 DefaultReturn(Span),
2231 /// Everything else.
2232 Return(&'hir Ty<'hir>),
2235 impl fmt::Display for FunctionRetTy<'_> {
2236 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2238 Return(ref ty) => print::to_string(print::NO_ANN, |s| s.print_type(ty)).fmt(f),
2239 DefaultReturn(_) => "()".fmt(f),
2244 impl FunctionRetTy<'_> {
2245 pub fn span(&self) -> Span {
2247 DefaultReturn(span) => span,
2248 Return(ref ty) => ty.span,
2253 #[derive(RustcEncodable, RustcDecodable, Debug)]
2254 pub struct Mod<'hir> {
2255 /// A span from the first token past `{` to the last token until `}`.
2256 /// For `mod foo;`, the inner span ranges from the first token
2257 /// to the last token in the external file.
2259 pub item_ids: &'hir [ItemId],
2262 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2263 pub struct ForeignMod<'hir> {
2265 pub items: &'hir [ForeignItem<'hir>],
2268 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2269 pub struct GlobalAsm {
2273 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2274 pub struct EnumDef<'hir> {
2275 pub variants: &'hir [Variant<'hir>],
2278 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2279 pub struct Variant<'hir> {
2280 /// Name of the variant.
2281 #[stable_hasher(project(name))]
2283 /// Attributes of the variant.
2284 pub attrs: &'hir [Attribute],
2285 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2287 /// Fields and constructor id of the variant.
2288 pub data: VariantData<'hir>,
2289 /// Explicit discriminant (e.g., `Foo = 1`).
2290 pub disr_expr: Option<AnonConst>,
2295 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2297 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2298 /// Also produced for each element of a list `use`, e.g.
2299 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2302 /// Glob import, e.g., `use foo::*`.
2305 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2306 /// an additional `use foo::{}` for performing checks such as
2307 /// unstable feature gating. May be removed in the future.
2311 /// References to traits in impls.
2313 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2314 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2315 /// trait being referred to but just a unique `HirId` that serves as a key
2316 /// within the resolution map.
2317 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2318 pub struct TraitRef<'hir> {
2319 pub path: &'hir Path<'hir>,
2320 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2321 #[stable_hasher(ignore)]
2322 pub hir_ref_id: HirId,
2326 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2327 pub fn trait_def_id(&self) -> DefId {
2328 match self.path.res {
2329 Res::Def(DefKind::Trait, did) => did,
2330 Res::Def(DefKind::TraitAlias, did) => did,
2334 _ => unreachable!(),
2339 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2340 pub struct PolyTraitRef<'hir> {
2341 /// The `'a` in `<'a> Foo<&'a T>`.
2342 pub bound_generic_params: &'hir [GenericParam<'hir>],
2344 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2345 pub trait_ref: TraitRef<'hir>,
2350 pub type Visibility<'hir> = Spanned<VisibilityKind<'hir>>;
2352 #[derive(RustcEncodable, RustcDecodable, Debug)]
2353 pub enum VisibilityKind<'hir> {
2356 Restricted { path: &'hir Path<'hir>, hir_id: HirId },
2360 impl VisibilityKind<'_> {
2361 pub fn is_pub(&self) -> bool {
2363 VisibilityKind::Public => true,
2368 pub fn is_pub_restricted(&self) -> bool {
2370 VisibilityKind::Public | VisibilityKind::Inherited => false,
2371 VisibilityKind::Crate(..) | VisibilityKind::Restricted { .. } => true,
2375 pub fn descr(&self) -> &'static str {
2377 VisibilityKind::Public => "public",
2378 VisibilityKind::Inherited => "private",
2379 VisibilityKind::Crate(..) => "crate-visible",
2380 VisibilityKind::Restricted { .. } => "restricted",
2385 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2386 pub struct StructField<'hir> {
2388 #[stable_hasher(project(name))]
2390 pub vis: Visibility<'hir>,
2392 pub ty: &'hir Ty<'hir>,
2393 pub attrs: &'hir [Attribute],
2396 impl StructField<'_> {
2397 // Still necessary in couple of places
2398 pub fn is_positional(&self) -> bool {
2399 let first = self.ident.as_str().as_bytes()[0];
2400 first >= b'0' && first <= b'9'
2404 /// Fields and constructor IDs of enum variants and structs.
2405 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2406 pub enum VariantData<'hir> {
2407 /// A struct variant.
2409 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2410 Struct(&'hir [StructField<'hir>], /* recovered */ bool),
2411 /// A tuple variant.
2413 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2414 Tuple(&'hir [StructField<'hir>], HirId),
2417 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2421 impl VariantData<'hir> {
2422 /// Return the fields of this variant.
2423 pub fn fields(&self) -> &'hir [StructField<'hir>] {
2425 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2430 /// Return the `HirId` of this variant's constructor, if it has one.
2431 pub fn ctor_hir_id(&self) -> Option<HirId> {
2433 VariantData::Struct(_, _) => None,
2434 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2439 // The bodies for items are stored "out of line", in a separate
2440 // hashmap in the `Crate`. Here we just record the node-id of the item
2441 // so it can fetched later.
2442 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2449 /// The name might be a dummy name in case of anonymous items
2450 #[derive(RustcEncodable, RustcDecodable, Debug)]
2451 pub struct Item<'hir> {
2454 pub attrs: &'hir [Attribute],
2455 pub kind: ItemKind<'hir>,
2456 pub vis: Visibility<'hir>,
2460 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2461 pub struct FnHeader {
2462 pub unsafety: Unsafety,
2463 pub constness: Constness,
2464 pub asyncness: IsAsync,
2469 pub fn is_const(&self) -> bool {
2470 match &self.constness {
2471 Constness::Const => true,
2477 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2478 pub enum ItemKind<'hir> {
2479 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2481 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2482 ExternCrate(Option<Name>),
2484 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2488 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2489 Use(&'hir Path<'hir>, UseKind),
2491 /// A `static` item.
2492 Static(&'hir Ty<'hir>, Mutability, BodyId),
2494 Const(&'hir Ty<'hir>, BodyId),
2495 /// A function declaration.
2496 Fn(FnSig<'hir>, Generics<'hir>, BodyId),
2499 /// An external module, e.g. `extern { .. }`.
2500 ForeignMod(ForeignMod<'hir>),
2501 /// Module-level inline assembly (from `global_asm!`).
2502 GlobalAsm(&'hir GlobalAsm),
2503 /// A type alias, e.g., `type Foo = Bar<u8>`.
2504 TyAlias(&'hir Ty<'hir>, Generics<'hir>),
2505 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2506 OpaqueTy(OpaqueTy<'hir>),
2507 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2508 Enum(EnumDef<'hir>, Generics<'hir>),
2509 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2510 Struct(VariantData<'hir>, Generics<'hir>),
2511 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2512 Union(VariantData<'hir>, Generics<'hir>),
2513 /// A trait definition.
2514 Trait(IsAuto, Unsafety, Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
2516 TraitAlias(Generics<'hir>, GenericBounds<'hir>),
2518 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2524 Option<TraitRef<'hir>>, // (optional) trait this impl implements
2525 &'hir Ty<'hir>, // self
2526 &'hir [ImplItemRef<'hir>],
2531 pub fn descriptive_variant(&self) -> &str {
2533 ItemKind::ExternCrate(..) => "extern crate",
2534 ItemKind::Use(..) => "use",
2535 ItemKind::Static(..) => "static item",
2536 ItemKind::Const(..) => "constant item",
2537 ItemKind::Fn(..) => "function",
2538 ItemKind::Mod(..) => "module",
2539 ItemKind::ForeignMod(..) => "foreign module",
2540 ItemKind::GlobalAsm(..) => "global asm",
2541 ItemKind::TyAlias(..) => "type alias",
2542 ItemKind::OpaqueTy(..) => "opaque type",
2543 ItemKind::Enum(..) => "enum",
2544 ItemKind::Struct(..) => "struct",
2545 ItemKind::Union(..) => "union",
2546 ItemKind::Trait(..) => "trait",
2547 ItemKind::TraitAlias(..) => "trait alias",
2548 ItemKind::Impl(..) => "impl",
2552 pub fn generics(&self) -> Option<&Generics<'_>> {
2554 ItemKind::Fn(_, ref generics, _)
2555 | ItemKind::TyAlias(_, ref generics)
2556 | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
2557 | ItemKind::Enum(_, ref generics)
2558 | ItemKind::Struct(_, ref generics)
2559 | ItemKind::Union(_, ref generics)
2560 | ItemKind::Trait(_, _, ref generics, _, _)
2561 | ItemKind::Impl(_, _, _, ref generics, _, _, _) => generics,
2567 /// A reference from an trait to one of its associated items. This
2568 /// contains the item's id, naturally, but also the item's name and
2569 /// some other high-level details (like whether it is an associated
2570 /// type or method, and whether it is public). This allows other
2571 /// passes to find the impl they want without loading the ID (which
2572 /// means fewer edges in the incremental compilation graph).
2573 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2574 pub struct TraitItemRef {
2575 pub id: TraitItemId,
2576 #[stable_hasher(project(name))]
2578 pub kind: AssocItemKind,
2580 pub defaultness: Defaultness,
2583 /// A reference from an impl to one of its associated items. This
2584 /// contains the item's ID, naturally, but also the item's name and
2585 /// some other high-level details (like whether it is an associated
2586 /// type or method, and whether it is public). This allows other
2587 /// passes to find the impl they want without loading the ID (which
2588 /// means fewer edges in the incremental compilation graph).
2589 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2590 pub struct ImplItemRef<'hir> {
2592 #[stable_hasher(project(name))]
2594 pub kind: AssocItemKind,
2596 pub vis: Visibility<'hir>,
2597 pub defaultness: Defaultness,
2600 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2601 pub enum AssocItemKind {
2603 Method { has_self: bool },
2608 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2609 pub struct ForeignItem<'hir> {
2610 #[stable_hasher(project(name))]
2612 pub attrs: &'hir [Attribute],
2613 pub kind: ForeignItemKind<'hir>,
2616 pub vis: Visibility<'hir>,
2619 /// An item within an `extern` block.
2620 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2621 pub enum ForeignItemKind<'hir> {
2622 /// A foreign function.
2623 Fn(&'hir FnDecl<'hir>, &'hir [Ident], Generics<'hir>),
2624 /// A foreign static item (`static ext: u8`).
2625 Static(&'hir Ty<'hir>, Mutability),
2630 impl ForeignItemKind<'hir> {
2631 pub fn descriptive_variant(&self) -> &str {
2633 ForeignItemKind::Fn(..) => "foreign function",
2634 ForeignItemKind::Static(..) => "foreign static item",
2635 ForeignItemKind::Type => "foreign type",
2640 /// A variable captured by a closure.
2641 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable, HashStable)]
2643 // First span where it is accessed (there can be multiple).
2647 pub type CaptureModeMap = NodeMap<CaptureBy>;
2649 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2650 // has length > 0 if the trait is found through an chain of imports, starting with the
2651 // import/use statement in the scope where the trait is used.
2652 #[derive(Clone, Debug)]
2653 pub struct TraitCandidate {
2655 pub import_ids: SmallVec<[NodeId; 1]>,
2658 // Trait method resolution
2659 pub type TraitMap = NodeMap<Vec<TraitCandidate>>;
2661 // Map from the NodeId of a glob import to a list of items which are actually
2663 pub type GlobMap = NodeMap<FxHashSet<Name>>;
2665 pub fn provide(providers: &mut Providers<'_>) {
2666 check_attr::provide(providers);
2667 map::provide(providers);
2668 upvars::provide(providers);
2671 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
2672 pub struct CodegenFnAttrs {
2673 pub flags: CodegenFnAttrFlags,
2674 /// Parsed representation of the `#[inline]` attribute
2675 pub inline: InlineAttr,
2676 /// Parsed representation of the `#[optimize]` attribute
2677 pub optimize: OptimizeAttr,
2678 /// The `#[export_name = "..."]` attribute, indicating a custom symbol a
2679 /// function should be exported under
2680 pub export_name: Option<Symbol>,
2681 /// The `#[link_name = "..."]` attribute, indicating a custom symbol an
2682 /// imported function should be imported as. Note that `export_name`
2683 /// probably isn't set when this is set, this is for foreign items while
2684 /// `#[export_name]` is for Rust-defined functions.
2685 pub link_name: Option<Symbol>,
2686 /// The `#[link_ordinal = "..."]` attribute, indicating an ordinal an
2687 /// imported function has in the dynamic library. Note that this must not
2688 /// be set when `link_name` is set. This is for foreign items with the
2689 /// "raw-dylib" kind.
2690 pub link_ordinal: Option<usize>,
2691 /// The `#[target_feature(enable = "...")]` attribute and the enabled
2692 /// features (only enabled features are supported right now).
2693 pub target_features: Vec<Symbol>,
2694 /// The `#[linkage = "..."]` attribute and the value we found.
2695 pub linkage: Option<Linkage>,
2696 /// The `#[link_section = "..."]` attribute, or what executable section this
2697 /// should be placed in.
2698 pub link_section: Option<Symbol>,
2702 #[derive(RustcEncodable, RustcDecodable, HashStable)]
2703 pub struct CodegenFnAttrFlags: u32 {
2704 /// `#[cold]`: a hint to LLVM that this function, when called, is never on
2706 const COLD = 1 << 0;
2707 /// `#[rustc_allocator]`: a hint to LLVM that the pointer returned from this
2708 /// function is never null.
2709 const ALLOCATOR = 1 << 1;
2710 /// `#[unwind]`: an indicator that this function may unwind despite what
2711 /// its ABI signature may otherwise imply.
2712 const UNWIND = 1 << 2;
2713 /// `#[rust_allocator_nounwind]`, an indicator that an imported FFI
2714 /// function will never unwind. Probably obsolete by recent changes with
2715 /// #[unwind], but hasn't been removed/migrated yet
2716 const RUSTC_ALLOCATOR_NOUNWIND = 1 << 3;
2717 /// `#[naked]`: an indicator to LLVM that no function prologue/epilogue
2718 /// should be generated.
2719 const NAKED = 1 << 4;
2720 /// `#[no_mangle]`: an indicator that the function's name should be the same
2722 const NO_MANGLE = 1 << 5;
2723 /// `#[rustc_std_internal_symbol]`: an indicator that this symbol is a
2724 /// "weird symbol" for the standard library in that it has slightly
2725 /// different linkage, visibility, and reachability rules.
2726 const RUSTC_STD_INTERNAL_SYMBOL = 1 << 6;
2727 /// `#[no_debug]`: an indicator that no debugging information should be
2728 /// generated for this function by LLVM.
2729 const NO_DEBUG = 1 << 7;
2730 /// `#[thread_local]`: indicates a static is actually a thread local
2732 const THREAD_LOCAL = 1 << 8;
2733 /// `#[used]`: indicates that LLVM can't eliminate this function (but the
2735 const USED = 1 << 9;
2736 /// `#[ffi_returns_twice]`, indicates that an extern function can return
2738 const FFI_RETURNS_TWICE = 1 << 10;
2739 /// `#[track_caller]`: allow access to the caller location
2740 const TRACK_CALLER = 1 << 11;
2744 impl CodegenFnAttrs {
2745 pub fn new() -> CodegenFnAttrs {
2747 flags: CodegenFnAttrFlags::empty(),
2748 inline: InlineAttr::None,
2749 optimize: OptimizeAttr::None,
2753 target_features: vec![],
2759 /// Returns `true` if `#[inline]` or `#[inline(always)]` is present.
2760 pub fn requests_inline(&self) -> bool {
2762 InlineAttr::Hint | InlineAttr::Always => true,
2763 InlineAttr::None | InlineAttr::Never => false,
2767 /// Returns `true` if it looks like this symbol needs to be exported, for example:
2769 /// * `#[no_mangle]` is present
2770 /// * `#[export_name(...)]` is present
2771 /// * `#[linkage]` is present
2772 pub fn contains_extern_indicator(&self) -> bool {
2773 self.flags.contains(CodegenFnAttrFlags::NO_MANGLE)
2774 || self.export_name.is_some()
2775 || match self.linkage {
2776 // These are private, so make sure we don't try to consider
2778 None | Some(Linkage::Internal) | Some(Linkage::Private) => false,
2784 #[derive(Copy, Clone, Debug)]
2785 pub enum Node<'hir> {
2786 Param(&'hir Param<'hir>),
2787 Item(&'hir Item<'hir>),
2788 ForeignItem(&'hir ForeignItem<'hir>),
2789 TraitItem(&'hir TraitItem<'hir>),
2790 ImplItem(&'hir ImplItem<'hir>),
2791 Variant(&'hir Variant<'hir>),
2792 Field(&'hir StructField<'hir>),
2793 AnonConst(&'hir AnonConst),
2794 Expr(&'hir Expr<'hir>),
2795 Stmt(&'hir Stmt<'hir>),
2796 PathSegment(&'hir PathSegment<'hir>),
2798 TraitRef(&'hir TraitRef<'hir>),
2799 Binding(&'hir Pat<'hir>),
2800 Pat(&'hir Pat<'hir>),
2801 Arm(&'hir Arm<'hir>),
2802 Block(&'hir Block<'hir>),
2803 Local(&'hir Local<'hir>),
2804 MacroDef(&'hir MacroDef<'hir>),
2806 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
2807 /// with synthesized constructors.
2808 Ctor(&'hir VariantData<'hir>),
2810 Lifetime(&'hir Lifetime),
2811 GenericParam(&'hir GenericParam<'hir>),
2812 Visibility(&'hir Visibility<'hir>),
2818 pub fn ident(&self) -> Option<Ident> {
2820 Node::TraitItem(TraitItem { ident, .. })
2821 | Node::ImplItem(ImplItem { ident, .. })
2822 | Node::ForeignItem(ForeignItem { ident, .. })
2823 | Node::Item(Item { ident, .. }) => Some(*ident),