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::ty::query::Providers;
15 use errors::FatalError;
16 use rustc_data_structures::fx::FxHashSet;
17 use rustc_data_structures::sync::{par_for_each_in, Send, Sync};
18 use rustc_macros::HashStable;
19 use rustc_serialize::{self, Decodable, Decoder, Encodable, Encoder};
20 use rustc_session::node_id::NodeMap;
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::tokenstream::TokenStream;
33 use syntax::util::parser::ExprPrecedence;
39 pub mod itemlikevisit;
45 /// Uniquely identifies a node in the HIR of the current crate. It is
46 /// composed of the `owner`, which is the `DefIndex` of the directly enclosing
47 /// `hir::Item`, `hir::TraitItem`, or `hir::ImplItem` (i.e., the closest "item-like"),
48 /// and the `local_id` which is unique within the given owner.
50 /// This two-level structure makes for more stable values: One can move an item
51 /// around within the source code, or add or remove stuff before it, without
52 /// the `local_id` part of the `HirId` changing, which is a very useful property in
53 /// incremental compilation where we have to persist things through changes to
55 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)]
58 pub local_id: ItemLocalId,
62 pub fn owner_def_id(self) -> DefId {
63 DefId::local(self.owner)
66 pub fn owner_local_def_id(self) -> LocalDefId {
67 LocalDefId::from_def_id(DefId::local(self.owner))
71 impl rustc_serialize::UseSpecializedEncodable for HirId {
72 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
73 let HirId { owner, local_id } = *self;
81 impl rustc_serialize::UseSpecializedDecodable for HirId {
82 fn default_decode<D: Decoder>(d: &mut D) -> Result<HirId, D::Error> {
83 let owner = DefIndex::decode(d)?;
84 let local_id = ItemLocalId::decode(d)?;
86 Ok(HirId { owner, local_id })
90 impl fmt::Display for HirId {
91 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92 write!(f, "{:?}", self)
96 // Hack to ensure that we don't try to access the private parts of `ItemLocalId` in this module.
97 mod item_local_id_inner {
98 use rustc_index::vec::Idx;
99 use rustc_macros::HashStable;
100 rustc_index::newtype_index! {
101 /// An `ItemLocalId` uniquely identifies something within a given "item-like";
102 /// that is, within a `hir::Item`, `hir::TraitItem`, or `hir::ImplItem`. There is no
103 /// guarantee that the numerical value of a given `ItemLocalId` corresponds to
104 /// the node's position within the owning item in any way, but there is a
105 /// guarantee that the `LocalItemId`s within an owner occupy a dense range of
106 /// integers starting at zero, so a mapping that maps all or most nodes within
107 /// an "item-like" to something else can be implemented by a `Vec` instead of a
108 /// tree or hash map.
109 pub struct ItemLocalId {
115 pub use self::item_local_id_inner::ItemLocalId;
117 /// The `HirId` corresponding to `CRATE_NODE_ID` and `CRATE_DEF_INDEX`.
118 pub const CRATE_HIR_ID: HirId =
119 HirId { owner: CRATE_DEF_INDEX, local_id: ItemLocalId::from_u32_const(0) };
121 pub const DUMMY_HIR_ID: HirId = HirId { owner: CRATE_DEF_INDEX, local_id: DUMMY_ITEM_LOCAL_ID };
123 pub const DUMMY_ITEM_LOCAL_ID: ItemLocalId = ItemLocalId::MAX;
125 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, HashStable)]
126 pub struct Lifetime {
130 /// Either "`'a`", referring to a named lifetime definition,
131 /// or "``" (i.e., `kw::Invalid`), for elision placeholders.
133 /// HIR lowering inserts these placeholders in type paths that
134 /// refer to type definitions needing lifetime parameters,
135 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
136 pub name: LifetimeName,
139 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy, HashStable)]
141 /// Some user-given name like `T` or `'x`.
144 /// Synthetic name generated when user elided a lifetime in an impl header.
146 /// E.g., the lifetimes in cases like these:
148 /// impl Foo for &u32
149 /// impl Foo<'_> for u32
151 /// in that case, we rewrite to
153 /// impl<'f> Foo for &'f u32
154 /// impl<'f> Foo<'f> for u32
156 /// where `'f` is something like `Fresh(0)`. The indices are
157 /// unique per impl, but not necessarily continuous.
160 /// Indicates an illegal name was given and an error has been
161 /// reported (so we should squelch other derived errors). Occurs
162 /// when, e.g., `'_` is used in the wrong place.
167 pub fn ident(&self) -> Ident {
169 ParamName::Plain(ident) => ident,
170 ParamName::Fresh(_) | ParamName::Error => {
171 Ident::with_dummy_span(kw::UnderscoreLifetime)
176 pub fn modern(&self) -> ParamName {
178 ParamName::Plain(ident) => ParamName::Plain(ident.modern()),
179 param_name => param_name,
184 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy, HashStable)]
185 pub enum LifetimeName {
186 /// User-given names or fresh (synthetic) names.
189 /// User wrote nothing (e.g., the lifetime in `&u32`).
192 /// Implicit lifetime in a context like `dyn Foo`. This is
193 /// distinguished from implicit lifetimes elsewhere because the
194 /// lifetime that they default to must appear elsewhere within the
195 /// enclosing type. This means that, in an `impl Trait` context, we
196 /// don't have to create a parameter for them. That is, `impl
197 /// Trait<Item = &u32>` expands to an opaque type like `type
198 /// Foo<'a> = impl Trait<Item = &'a u32>`, but `impl Trait<item =
199 /// dyn Bar>` expands to `type Foo = impl Trait<Item = dyn Bar +
200 /// 'static>`. The latter uses `ImplicitObjectLifetimeDefault` so
201 /// that surrounding code knows not to create a lifetime
203 ImplicitObjectLifetimeDefault,
205 /// Indicates an error during lowering (usually `'_` in wrong place)
206 /// that was already reported.
209 /// User wrote specifies `'_`.
212 /// User wrote `'static`.
217 pub fn ident(&self) -> Ident {
219 LifetimeName::ImplicitObjectLifetimeDefault
220 | LifetimeName::Implicit
221 | LifetimeName::Error => Ident::invalid(),
222 LifetimeName::Underscore => Ident::with_dummy_span(kw::UnderscoreLifetime),
223 LifetimeName::Static => Ident::with_dummy_span(kw::StaticLifetime),
224 LifetimeName::Param(param_name) => param_name.ident(),
228 pub fn is_elided(&self) -> bool {
230 LifetimeName::ImplicitObjectLifetimeDefault
231 | LifetimeName::Implicit
232 | LifetimeName::Underscore => true,
234 // It might seem surprising that `Fresh(_)` counts as
235 // *not* elided -- but this is because, as far as the code
236 // in the compiler is concerned -- `Fresh(_)` variants act
237 // equivalently to "some fresh name". They correspond to
238 // early-bound regions on an impl, in other words.
239 LifetimeName::Error | LifetimeName::Param(_) | LifetimeName::Static => false,
243 fn is_static(&self) -> bool {
244 self == &LifetimeName::Static
247 pub fn modern(&self) -> LifetimeName {
249 LifetimeName::Param(param_name) => LifetimeName::Param(param_name.modern()),
250 lifetime_name => lifetime_name,
255 impl fmt::Display for Lifetime {
256 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
257 self.name.ident().fmt(f)
261 impl fmt::Debug for Lifetime {
262 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
267 print::to_string(print::NO_ANN, |s| s.print_lifetime(self))
273 pub fn is_elided(&self) -> bool {
274 self.name.is_elided()
277 pub fn is_static(&self) -> bool {
278 self.name.is_static()
282 /// A `Path` is essentially Rust's notion of a name; for instance,
283 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
284 /// along with a bunch of supporting information.
285 #[derive(RustcEncodable, RustcDecodable, HashStable)]
286 pub struct Path<'hir> {
288 /// The resolution for the path.
290 /// The segments in the path: the things separated by `::`.
291 pub segments: &'hir [PathSegment<'hir>],
295 pub fn is_global(&self) -> bool {
296 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
300 impl fmt::Debug for Path<'_> {
301 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
302 write!(f, "path({})", self)
306 impl fmt::Display for Path<'_> {
307 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
308 write!(f, "{}", print::to_string(print::NO_ANN, |s| s.print_path(self, false)))
312 /// A segment of a path: an identifier, an optional lifetime, and a set of
314 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
315 pub struct PathSegment<'hir> {
316 /// The identifier portion of this path segment.
317 #[stable_hasher(project(name))]
319 // `id` and `res` are optional. We currently only use these in save-analysis,
320 // any path segments without these will not have save-analysis info and
321 // therefore will not have 'jump to def' in IDEs, but otherwise will not be
322 // affected. (In general, we don't bother to get the defs for synthesized
323 // segments, only for segments which have come from the AST).
324 pub hir_id: Option<HirId>,
325 pub res: Option<Res>,
327 /// Type/lifetime parameters attached to this path. They come in
328 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
329 /// this is more than just simple syntactic sugar; the use of
330 /// parens affects the region binding rules, so we preserve the
332 pub args: Option<&'hir GenericArgs<'hir>>,
334 /// Whether to infer remaining type parameters, if any.
335 /// This only applies to expression and pattern paths, and
336 /// out of those only the segments with no type parameters
337 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
338 pub infer_args: bool,
341 impl<'hir> PathSegment<'hir> {
342 /// Converts an identifier to the corresponding segment.
343 pub fn from_ident(ident: Ident) -> PathSegment<'hir> {
344 PathSegment { ident, hir_id: None, res: None, infer_args: true, args: None }
347 pub fn generic_args(&self) -> &GenericArgs<'hir> {
348 if let Some(ref args) = self.args {
351 const DUMMY: &GenericArgs<'_> = &GenericArgs::none();
357 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
358 pub struct ConstArg {
359 pub value: AnonConst,
363 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
364 pub enum GenericArg<'hir> {
370 impl GenericArg<'_> {
371 pub fn span(&self) -> Span {
373 GenericArg::Lifetime(l) => l.span,
374 GenericArg::Type(t) => t.span,
375 GenericArg::Const(c) => c.span,
379 pub fn id(&self) -> HirId {
381 GenericArg::Lifetime(l) => l.hir_id,
382 GenericArg::Type(t) => t.hir_id,
383 GenericArg::Const(c) => c.value.hir_id,
387 pub fn is_const(&self) -> bool {
389 GenericArg::Const(_) => true,
395 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
396 pub struct GenericArgs<'hir> {
397 /// The generic arguments for this path segment.
398 pub args: &'hir [GenericArg<'hir>],
399 /// Bindings (equality constraints) on associated types, if present.
400 /// E.g., `Foo<A = Bar>`.
401 pub bindings: &'hir [TypeBinding<'hir>],
402 /// Were arguments written in parenthesized form `Fn(T) -> U`?
403 /// This is required mostly for pretty-printing and diagnostics,
404 /// but also for changing lifetime elision rules to be "function-like".
405 pub parenthesized: bool,
408 impl GenericArgs<'_> {
409 pub const fn none() -> Self {
410 Self { args: &[], bindings: &[], parenthesized: false }
413 pub fn is_empty(&self) -> bool {
414 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
417 pub fn inputs(&self) -> &[Ty<'_>] {
418 if self.parenthesized {
419 for arg in self.args {
421 GenericArg::Lifetime(_) => {}
422 GenericArg::Type(ref ty) => {
423 if let TyKind::Tup(ref tys) = ty.kind {
428 GenericArg::Const(_) => {}
432 bug!("GenericArgs::inputs: not a `Fn(T) -> U`");
435 pub fn own_counts(&self) -> GenericParamCount {
436 // We could cache this as a property of `GenericParamCount`, but
437 // the aim is to refactor this away entirely eventually and the
438 // presence of this method will be a constant reminder.
439 let mut own_counts: GenericParamCount = Default::default();
441 for arg in self.args {
443 GenericArg::Lifetime(_) => own_counts.lifetimes += 1,
444 GenericArg::Type(_) => own_counts.types += 1,
445 GenericArg::Const(_) => own_counts.consts += 1,
453 /// A modifier on a bound, currently this is only used for `?Sized`, where the
454 /// modifier is `Maybe`. Negative bounds should also be handled here.
455 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
456 pub enum TraitBoundModifier {
461 /// The AST represents all type param bounds as types.
462 /// `typeck::collect::compute_bounds` matches these against
463 /// the "special" built-in traits (see `middle::lang_items`) and
464 /// detects `Copy`, `Send` and `Sync`.
465 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
466 pub enum GenericBound<'hir> {
467 Trait(PolyTraitRef<'hir>, TraitBoundModifier),
471 impl GenericBound<'_> {
472 pub fn span(&self) -> Span {
474 &GenericBound::Trait(ref t, ..) => t.span,
475 &GenericBound::Outlives(ref l) => l.span,
480 pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
482 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable)]
483 pub enum LifetimeParamKind {
484 // Indicates that the lifetime definition was explicitly declared (e.g., in
485 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
488 // Indicates that the lifetime definition was synthetically added
489 // as a result of an in-band lifetime usage (e.g., in
490 // `fn foo(x: &'a u8) -> &'a u8 { x }`).
493 // Indication that the lifetime was elided (e.g., in both cases in
494 // `fn foo(x: &u8) -> &'_ u8 { x }`).
497 // Indication that the lifetime name was somehow in error.
501 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
502 pub enum GenericParamKind<'hir> {
503 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
505 kind: LifetimeParamKind,
508 default: Option<&'hir Ty<'hir>>,
509 synthetic: Option<SyntheticTyParamKind>,
516 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
517 pub struct GenericParam<'hir> {
520 pub attrs: &'hir [Attribute],
521 pub bounds: GenericBounds<'hir>,
523 pub pure_wrt_drop: bool,
524 pub kind: GenericParamKind<'hir>,
528 pub struct GenericParamCount {
529 pub lifetimes: usize,
534 /// Represents lifetimes and type parameters attached to a declaration
535 /// of a function, enum, trait, etc.
536 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
537 pub struct Generics<'hir> {
538 pub params: &'hir [GenericParam<'hir>],
539 pub where_clause: WhereClause<'hir>,
543 impl Generics<'hir> {
544 pub const fn empty() -> Generics<'hir> {
547 where_clause: WhereClause { predicates: &[], span: DUMMY_SP },
552 pub fn own_counts(&self) -> GenericParamCount {
553 // We could cache this as a property of `GenericParamCount`, but
554 // the aim is to refactor this away entirely eventually and the
555 // presence of this method will be a constant reminder.
556 let mut own_counts: GenericParamCount = Default::default();
558 for param in self.params {
560 GenericParamKind::Lifetime { .. } => own_counts.lifetimes += 1,
561 GenericParamKind::Type { .. } => own_counts.types += 1,
562 GenericParamKind::Const { .. } => own_counts.consts += 1,
569 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'_>> {
570 for param in self.params {
571 if name == param.name.ident().name {
578 pub fn spans(&self) -> MultiSpan {
579 if self.params.is_empty() {
582 self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
587 /// Synthetic type parameters are converted to another form during lowering; this allows
588 /// us to track the original form they had, and is useful for error messages.
589 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
590 pub enum SyntheticTyParamKind {
594 /// A where-clause in a definition.
595 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
596 pub struct WhereClause<'hir> {
597 pub predicates: &'hir [WherePredicate<'hir>],
598 // Only valid if predicates isn't empty.
602 impl WhereClause<'_> {
603 pub fn span(&self) -> Option<Span> {
604 if self.predicates.is_empty() { None } else { Some(self.span) }
607 /// The `WhereClause` under normal circumstances points at either the predicates or the empty
608 /// space where the `where` clause should be. Only of use for diagnostic suggestions.
609 pub fn span_for_predicates_or_empty_place(&self) -> Span {
614 /// A single predicate in a where-clause.
615 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
616 pub enum WherePredicate<'hir> {
617 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
618 BoundPredicate(WhereBoundPredicate<'hir>),
619 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
620 RegionPredicate(WhereRegionPredicate<'hir>),
621 /// An equality predicate (unsupported).
622 EqPredicate(WhereEqPredicate<'hir>),
625 impl WherePredicate<'_> {
626 pub fn span(&self) -> Span {
628 &WherePredicate::BoundPredicate(ref p) => p.span,
629 &WherePredicate::RegionPredicate(ref p) => p.span,
630 &WherePredicate::EqPredicate(ref p) => p.span,
635 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
636 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
637 pub struct WhereBoundPredicate<'hir> {
639 /// Any generics from a `for` binding.
640 pub bound_generic_params: &'hir [GenericParam<'hir>],
641 /// The type being bounded.
642 pub bounded_ty: &'hir Ty<'hir>,
643 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
644 pub bounds: GenericBounds<'hir>,
647 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
648 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
649 pub struct WhereRegionPredicate<'hir> {
651 pub lifetime: Lifetime,
652 pub bounds: GenericBounds<'hir>,
655 /// An equality predicate (e.g., `T = int`); currently unsupported.
656 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
657 pub struct WhereEqPredicate<'hir> {
660 pub lhs_ty: &'hir Ty<'hir>,
661 pub rhs_ty: &'hir Ty<'hir>,
664 #[derive(RustcEncodable, RustcDecodable, Debug)]
665 pub struct ModuleItems {
666 // Use BTreeSets here so items are in the same order as in the
667 // list of all items in Crate
668 pub items: BTreeSet<HirId>,
669 pub trait_items: BTreeSet<TraitItemId>,
670 pub impl_items: BTreeSet<ImplItemId>,
673 /// The top-level data structure that stores the entire contents of
674 /// the crate currently being compiled.
676 /// For more details, see the [rustc guide].
678 /// [rustc guide]: https://rust-lang.github.io/rustc-guide/hir.html
679 #[derive(RustcEncodable, RustcDecodable, Debug)]
680 pub struct Crate<'hir> {
681 pub module: Mod<'hir>,
682 pub attrs: &'hir [Attribute],
684 pub exported_macros: &'hir [MacroDef<'hir>],
685 // Attributes from non-exported macros, kept only for collecting the library feature list.
686 pub non_exported_macro_attrs: &'hir [Attribute],
688 // N.B., we use a `BTreeMap` here so that `visit_all_items` iterates
689 // over the ids in increasing order. In principle it should not
690 // matter what order we visit things in, but in *practice* it
691 // does, because it can affect the order in which errors are
692 // detected, which in turn can make compile-fail tests yield
693 // slightly different results.
694 pub items: BTreeMap<HirId, Item<'hir>>,
696 pub trait_items: BTreeMap<TraitItemId, TraitItem<'hir>>,
697 pub impl_items: BTreeMap<ImplItemId, ImplItem<'hir>>,
698 pub bodies: BTreeMap<BodyId, Body<'hir>>,
699 pub trait_impls: BTreeMap<DefId, Vec<HirId>>,
701 /// A list of the body ids written out in the order in which they
702 /// appear in the crate. If you're going to process all the bodies
703 /// in the crate, you should iterate over this list rather than the keys
705 pub body_ids: Vec<BodyId>,
707 /// A list of modules written out in the order in which they
708 /// appear in the crate. This includes the main crate module.
709 pub modules: BTreeMap<HirId, ModuleItems>,
713 pub fn item(&self, id: HirId) -> &Item<'hir> {
717 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem<'hir> {
718 &self.trait_items[&id]
721 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem<'hir> {
722 &self.impl_items[&id]
725 pub fn body(&self, id: BodyId) -> &Body<'hir> {
731 /// Visits all items in the crate in some deterministic (but
732 /// unspecified) order. If you just need to process every item,
733 /// but don't care about nesting, this method is the best choice.
735 /// If you do care about nesting -- usually because your algorithm
736 /// follows lexical scoping rules -- then you want a different
737 /// approach. You should override `visit_nested_item` in your
738 /// visitor and then call `intravisit::walk_crate` instead.
739 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
741 V: itemlikevisit::ItemLikeVisitor<'hir>,
743 for (_, item) in &self.items {
744 visitor.visit_item(item);
747 for (_, trait_item) in &self.trait_items {
748 visitor.visit_trait_item(trait_item);
751 for (_, impl_item) in &self.impl_items {
752 visitor.visit_impl_item(impl_item);
756 /// A parallel version of `visit_all_item_likes`.
757 pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
759 V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send,
763 par_for_each_in(&self.items, |(_, item)| {
764 visitor.visit_item(item);
768 par_for_each_in(&self.trait_items, |(_, trait_item)| {
769 visitor.visit_trait_item(trait_item);
773 par_for_each_in(&self.impl_items, |(_, impl_item)| {
774 visitor.visit_impl_item(impl_item);
781 /// A macro definition, in this crate or imported from another.
783 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
784 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
785 pub struct MacroDef<'hir> {
787 pub vis: Visibility<'hir>,
788 pub attrs: &'hir [Attribute],
791 pub body: TokenStream,
795 /// A block of statements `{ .. }`, which may have a label (in this case the
796 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
797 /// the `rules` being anything but `DefaultBlock`.
798 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
799 pub struct Block<'hir> {
800 /// Statements in a block.
801 pub stmts: &'hir [Stmt<'hir>],
802 /// An expression at the end of the block
803 /// without a semicolon, if any.
804 pub expr: Option<&'hir Expr<'hir>>,
805 #[stable_hasher(ignore)]
807 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
808 pub rules: BlockCheckMode,
810 /// If true, then there may exist `break 'a` values that aim to
811 /// break out of this block early.
812 /// Used by `'label: {}` blocks and by `try {}` blocks.
813 pub targeted_by_break: bool,
816 #[derive(RustcEncodable, RustcDecodable, HashStable)]
817 pub struct Pat<'hir> {
818 #[stable_hasher(ignore)]
820 pub kind: PatKind<'hir>,
824 impl fmt::Debug for Pat<'_> {
825 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
830 print::to_string(print::NO_ANN, |s| s.print_pat(self))
836 // FIXME(#19596) this is a workaround, but there should be a better way
837 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'_>) -> bool) -> bool {
844 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
845 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
846 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
847 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
848 Slice(before, slice, after) => {
849 before.iter().chain(slice.iter()).chain(after.iter()).all(|p| p.walk_short_(it))
854 /// Walk the pattern in left-to-right order,
855 /// short circuiting (with `.all(..)`) if `false` is returned.
857 /// Note that when visiting e.g. `Tuple(ps)`,
858 /// if visiting `ps[0]` returns `false`,
859 /// then `ps[1]` will not be visited.
860 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'_>) -> bool) -> bool {
861 self.walk_short_(&mut it)
864 // FIXME(#19596) this is a workaround, but there should be a better way
865 fn walk_(&self, it: &mut impl FnMut(&Pat<'_>) -> bool) {
872 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
873 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
874 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
875 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
876 Slice(before, slice, after) => {
877 before.iter().chain(slice.iter()).chain(after.iter()).for_each(|p| p.walk_(it))
882 /// Walk the pattern in left-to-right order.
884 /// If `it(pat)` returns `false`, the children are not visited.
885 pub fn walk(&self, mut it: impl FnMut(&Pat<'_>) -> bool) {
889 /// Walk the pattern in left-to-right order.
891 /// If you always want to recurse, prefer this method over `walk`.
892 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
900 /// A single field in a struct pattern.
902 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
903 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
904 /// except `is_shorthand` is true.
905 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
906 pub struct FieldPat<'hir> {
907 #[stable_hasher(ignore)]
909 /// The identifier for the field.
910 #[stable_hasher(project(name))]
912 /// The pattern the field is destructured to.
913 pub pat: &'hir Pat<'hir>,
914 pub is_shorthand: bool,
918 /// Explicit binding annotations given in the HIR for a binding. Note
919 /// that this is not the final binding *mode* that we infer after type
921 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
922 pub enum BindingAnnotation {
923 /// No binding annotation given: this means that the final binding mode
924 /// will depend on whether we have skipped through a `&` reference
925 /// when matching. For example, the `x` in `Some(x)` will have binding
926 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
927 /// ultimately be inferred to be by-reference.
929 /// Note that implicit reference skipping is not implemented yet (#42640).
932 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
935 /// Annotated as `ref`, like `ref x`
938 /// Annotated as `ref mut x`.
942 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
948 impl fmt::Display for RangeEnd {
949 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
950 f.write_str(match self {
951 RangeEnd::Included => "..=",
952 RangeEnd::Excluded => "..",
957 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
958 pub enum PatKind<'hir> {
959 /// Represents a wildcard pattern (i.e., `_`).
962 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
963 /// The `HirId` is the canonical ID for the variable being bound,
964 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
965 /// which is the pattern ID of the first `x`.
966 Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
968 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
969 /// The `bool` is `true` in the presence of a `..`.
970 Struct(QPath<'hir>, &'hir [FieldPat<'hir>], bool),
972 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
973 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
974 /// `0 <= position <= subpats.len()`
975 TupleStruct(QPath<'hir>, &'hir [&'hir Pat<'hir>], Option<usize>),
977 /// An or-pattern `A | B | C`.
978 /// Invariant: `pats.len() >= 2`.
979 Or(&'hir [&'hir Pat<'hir>]),
981 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
984 /// A tuple pattern (e.g., `(a, b)`).
985 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
986 /// `0 <= position <= subpats.len()`
987 Tuple(&'hir [&'hir Pat<'hir>], Option<usize>),
990 Box(&'hir Pat<'hir>),
992 /// A reference pattern (e.g., `&mut (a, b)`).
993 Ref(&'hir Pat<'hir>, Mutability),
996 Lit(&'hir Expr<'hir>),
998 /// A range pattern (e.g., `1..=2` or `1..2`).
999 Range(&'hir Expr<'hir>, &'hir Expr<'hir>, RangeEnd),
1001 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
1003 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
1004 /// If `slice` exists, then `after` can be non-empty.
1006 /// The representation for e.g., `[a, b, .., c, d]` is:
1008 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
1010 Slice(&'hir [&'hir Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [&'hir Pat<'hir>]),
1013 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1014 pub enum BinOpKind {
1015 /// The `+` operator (addition).
1017 /// The `-` operator (subtraction).
1019 /// The `*` operator (multiplication).
1021 /// The `/` operator (division).
1023 /// The `%` operator (modulus).
1025 /// The `&&` operator (logical and).
1027 /// The `||` operator (logical or).
1029 /// The `^` operator (bitwise xor).
1031 /// The `&` operator (bitwise and).
1033 /// The `|` operator (bitwise or).
1035 /// The `<<` operator (shift left).
1037 /// The `>>` operator (shift right).
1039 /// The `==` operator (equality).
1041 /// The `<` operator (less than).
1043 /// The `<=` operator (less than or equal to).
1045 /// The `!=` operator (not equal to).
1047 /// The `>=` operator (greater than or equal to).
1049 /// The `>` operator (greater than).
1054 pub fn as_str(self) -> &'static str {
1056 BinOpKind::Add => "+",
1057 BinOpKind::Sub => "-",
1058 BinOpKind::Mul => "*",
1059 BinOpKind::Div => "/",
1060 BinOpKind::Rem => "%",
1061 BinOpKind::And => "&&",
1062 BinOpKind::Or => "||",
1063 BinOpKind::BitXor => "^",
1064 BinOpKind::BitAnd => "&",
1065 BinOpKind::BitOr => "|",
1066 BinOpKind::Shl => "<<",
1067 BinOpKind::Shr => ">>",
1068 BinOpKind::Eq => "==",
1069 BinOpKind::Lt => "<",
1070 BinOpKind::Le => "<=",
1071 BinOpKind::Ne => "!=",
1072 BinOpKind::Ge => ">=",
1073 BinOpKind::Gt => ">",
1077 pub fn is_lazy(self) -> bool {
1079 BinOpKind::And | BinOpKind::Or => true,
1084 pub fn is_shift(self) -> bool {
1086 BinOpKind::Shl | BinOpKind::Shr => true,
1091 pub fn is_comparison(self) -> bool {
1098 | BinOpKind::Ge => true,
1110 | BinOpKind::Shr => false,
1114 /// Returns `true` if the binary operator takes its arguments by value.
1115 pub fn is_by_value(self) -> bool {
1116 !self.is_comparison()
1120 impl Into<ast::BinOpKind> for BinOpKind {
1121 fn into(self) -> ast::BinOpKind {
1123 BinOpKind::Add => ast::BinOpKind::Add,
1124 BinOpKind::Sub => ast::BinOpKind::Sub,
1125 BinOpKind::Mul => ast::BinOpKind::Mul,
1126 BinOpKind::Div => ast::BinOpKind::Div,
1127 BinOpKind::Rem => ast::BinOpKind::Rem,
1128 BinOpKind::And => ast::BinOpKind::And,
1129 BinOpKind::Or => ast::BinOpKind::Or,
1130 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1131 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1132 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1133 BinOpKind::Shl => ast::BinOpKind::Shl,
1134 BinOpKind::Shr => ast::BinOpKind::Shr,
1135 BinOpKind::Eq => ast::BinOpKind::Eq,
1136 BinOpKind::Lt => ast::BinOpKind::Lt,
1137 BinOpKind::Le => ast::BinOpKind::Le,
1138 BinOpKind::Ne => ast::BinOpKind::Ne,
1139 BinOpKind::Ge => ast::BinOpKind::Ge,
1140 BinOpKind::Gt => ast::BinOpKind::Gt,
1145 pub type BinOp = Spanned<BinOpKind>;
1147 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1149 /// The `*` operator (deferencing).
1151 /// The `!` operator (logical negation).
1153 /// The `-` operator (negation).
1158 pub fn as_str(self) -> &'static str {
1166 /// Returns `true` if the unary operator takes its argument by value.
1167 pub fn is_by_value(self) -> bool {
1169 UnNeg | UnNot => true,
1176 #[derive(RustcEncodable, RustcDecodable, HashStable)]
1177 pub struct Stmt<'hir> {
1179 pub kind: StmtKind<'hir>,
1183 impl fmt::Debug for Stmt<'_> {
1184 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1189 print::to_string(print::NO_ANN, |s| s.print_stmt(self))
1194 /// The contents of a statement.
1195 #[derive(RustcEncodable, RustcDecodable, HashStable)]
1196 pub enum StmtKind<'hir> {
1197 /// A local (`let`) binding.
1198 Local(&'hir Local<'hir>),
1200 /// An item binding.
1203 /// An expression without a trailing semi-colon (must have unit type).
1204 Expr(&'hir Expr<'hir>),
1206 /// An expression with a trailing semi-colon (may have any type).
1207 Semi(&'hir Expr<'hir>),
1210 impl StmtKind<'hir> {
1211 pub fn attrs(&self) -> &'hir [Attribute] {
1213 StmtKind::Local(ref l) => &l.attrs,
1214 StmtKind::Item(_) => &[],
1215 StmtKind::Expr(ref e) | StmtKind::Semi(ref e) => &e.attrs,
1220 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1221 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1222 pub struct Local<'hir> {
1223 pub pat: &'hir Pat<'hir>,
1224 /// Type annotation, if any (otherwise the type will be inferred).
1225 pub ty: Option<&'hir Ty<'hir>>,
1226 /// Initializer expression to set the value, if any.
1227 pub init: Option<&'hir Expr<'hir>>,
1231 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1232 /// desugaring. Otherwise will be `Normal`.
1233 pub source: LocalSource,
1236 /// Represents a single arm of a `match` expression, e.g.
1237 /// `<pat> (if <guard>) => <body>`.
1238 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1239 pub struct Arm<'hir> {
1240 #[stable_hasher(ignore)]
1243 pub attrs: &'hir [Attribute],
1244 /// If this pattern and the optional guard matches, then `body` is evaluated.
1245 pub pat: &'hir Pat<'hir>,
1246 /// Optional guard clause.
1247 pub guard: Option<Guard<'hir>>,
1248 /// The expression the arm evaluates to if this arm matches.
1249 pub body: &'hir Expr<'hir>,
1252 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1253 pub enum Guard<'hir> {
1254 If(&'hir Expr<'hir>),
1257 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1258 pub struct Field<'hir> {
1259 #[stable_hasher(ignore)]
1262 pub expr: &'hir Expr<'hir>,
1264 pub is_shorthand: bool,
1267 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1268 pub enum BlockCheckMode {
1270 UnsafeBlock(UnsafeSource),
1271 PushUnsafeBlock(UnsafeSource),
1272 PopUnsafeBlock(UnsafeSource),
1275 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1276 pub enum UnsafeSource {
1281 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1286 /// The body of a function, closure, or constant value. In the case of
1287 /// a function, the body contains not only the function body itself
1288 /// (which is an expression), but also the argument patterns, since
1289 /// those are something that the caller doesn't really care about.
1294 /// fn foo((x, y): (u32, u32)) -> u32 {
1299 /// Here, the `Body` associated with `foo()` would contain:
1301 /// - an `params` array containing the `(x, y)` pattern
1302 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1303 /// - `generator_kind` would be `None`
1305 /// All bodies have an **owner**, which can be accessed via the HIR
1306 /// map using `body_owner_def_id()`.
1307 #[derive(RustcEncodable, RustcDecodable, Debug)]
1308 pub struct Body<'hir> {
1309 pub params: &'hir [Param<'hir>],
1310 pub value: Expr<'hir>,
1311 pub generator_kind: Option<GeneratorKind>,
1315 pub fn id(&self) -> BodyId {
1316 BodyId { hir_id: self.value.hir_id }
1319 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1324 /// The type of source expression that caused this generator to be created.
1325 #[derive(Clone, PartialEq, Eq, HashStable, RustcEncodable, RustcDecodable, Debug, Copy)]
1326 pub enum GeneratorKind {
1327 /// An explicit `async` block or the body of an async function.
1328 Async(AsyncGeneratorKind),
1330 /// A generator literal created via a `yield` inside a closure.
1334 impl fmt::Display for GeneratorKind {
1335 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1337 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1338 GeneratorKind::Gen => f.write_str("generator"),
1343 /// In the case of a generator created as part of an async construct,
1344 /// which kind of async construct caused it to be created?
1346 /// This helps error messages but is also used to drive coercions in
1347 /// type-checking (see #60424).
1348 #[derive(Clone, PartialEq, Eq, HashStable, RustcEncodable, RustcDecodable, Debug, Copy)]
1349 pub enum AsyncGeneratorKind {
1350 /// An explicit `async` block written by the user.
1353 /// An explicit `async` block written by the user.
1356 /// The `async` block generated as the body of an async function.
1360 impl fmt::Display for AsyncGeneratorKind {
1361 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1362 f.write_str(match self {
1363 AsyncGeneratorKind::Block => "`async` block",
1364 AsyncGeneratorKind::Closure => "`async` closure body",
1365 AsyncGeneratorKind::Fn => "`async fn` body",
1370 #[derive(Copy, Clone, Debug)]
1371 pub enum BodyOwnerKind {
1372 /// Functions and methods.
1378 /// Constants and associated constants.
1381 /// Initializer of a `static` item.
1385 impl BodyOwnerKind {
1386 pub fn is_fn_or_closure(self) -> bool {
1388 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1389 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1395 pub type Lit = Spanned<LitKind>;
1397 /// A constant (expression) that's not an item or associated item,
1398 /// but needs its own `DefId` for type-checking, const-eval, etc.
1399 /// These are usually found nested inside types (e.g., array lengths)
1400 /// or expressions (e.g., repeat counts), and also used to define
1401 /// explicit discriminant values for enum variants.
1402 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1403 pub struct AnonConst {
1409 #[derive(RustcEncodable, RustcDecodable)]
1410 pub struct Expr<'hir> {
1412 pub kind: ExprKind<'hir>,
1417 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1418 #[cfg(target_arch = "x86_64")]
1419 static_assert_size!(Expr<'static>, 64);
1422 pub fn precedence(&self) -> ExprPrecedence {
1424 ExprKind::Box(_) => ExprPrecedence::Box,
1425 ExprKind::Array(_) => ExprPrecedence::Array,
1426 ExprKind::Call(..) => ExprPrecedence::Call,
1427 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1428 ExprKind::Tup(_) => ExprPrecedence::Tup,
1429 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1430 ExprKind::Unary(..) => ExprPrecedence::Unary,
1431 ExprKind::Lit(_) => ExprPrecedence::Lit,
1432 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1433 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1434 ExprKind::Loop(..) => ExprPrecedence::Loop,
1435 ExprKind::Match(..) => ExprPrecedence::Match,
1436 ExprKind::Closure(..) => ExprPrecedence::Closure,
1437 ExprKind::Block(..) => ExprPrecedence::Block,
1438 ExprKind::Assign(..) => ExprPrecedence::Assign,
1439 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1440 ExprKind::Field(..) => ExprPrecedence::Field,
1441 ExprKind::Index(..) => ExprPrecedence::Index,
1442 ExprKind::Path(..) => ExprPrecedence::Path,
1443 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1444 ExprKind::Break(..) => ExprPrecedence::Break,
1445 ExprKind::Continue(..) => ExprPrecedence::Continue,
1446 ExprKind::Ret(..) => ExprPrecedence::Ret,
1447 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1448 ExprKind::Struct(..) => ExprPrecedence::Struct,
1449 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1450 ExprKind::Yield(..) => ExprPrecedence::Yield,
1451 ExprKind::Err => ExprPrecedence::Err,
1455 // Whether this looks like a place expr, without checking for deref
1457 // This will return `true` in some potentially surprising cases such as
1458 // `CONSTANT.field`.
1459 pub fn is_syntactic_place_expr(&self) -> bool {
1460 self.is_place_expr(|_| true)
1463 // Whether this is a place expression.
1464 // `allow_projections_from` should return `true` if indexing a field or
1465 // index expression based on the given expression should be considered a
1466 // place expression.
1467 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1469 ExprKind::Path(QPath::Resolved(_, ref path)) => match path.res {
1470 Res::Local(..) | Res::Def(DefKind::Static, _) | Res::Err => true,
1474 // Type ascription inherits its place expression kind from its
1476 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1477 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1479 ExprKind::Unary(UnDeref, _) => true,
1481 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1482 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1485 // Partially qualified paths in expressions can only legally
1486 // refer to associated items which are always rvalues.
1487 ExprKind::Path(QPath::TypeRelative(..))
1488 | ExprKind::Call(..)
1489 | ExprKind::MethodCall(..)
1490 | ExprKind::Struct(..)
1492 | ExprKind::Match(..)
1493 | ExprKind::Closure(..)
1494 | ExprKind::Block(..)
1495 | ExprKind::Repeat(..)
1496 | ExprKind::Array(..)
1497 | ExprKind::Break(..)
1498 | ExprKind::Continue(..)
1500 | ExprKind::Loop(..)
1501 | ExprKind::Assign(..)
1502 | ExprKind::InlineAsm(..)
1503 | ExprKind::AssignOp(..)
1505 | ExprKind::Unary(..)
1507 | ExprKind::AddrOf(..)
1508 | ExprKind::Binary(..)
1509 | ExprKind::Yield(..)
1510 | ExprKind::Cast(..)
1511 | ExprKind::DropTemps(..)
1512 | ExprKind::Err => false,
1516 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1517 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1518 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1519 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1520 /// beyond remembering to call this function before doing analysis on it.
1521 pub fn peel_drop_temps(&self) -> &Self {
1522 let mut expr = self;
1523 while let ExprKind::DropTemps(inner) = &expr.kind {
1530 impl fmt::Debug for Expr<'_> {
1531 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1536 print::to_string(print::NO_ANN, |s| s.print_expr(self))
1541 /// Checks if the specified expression is a built-in range literal.
1542 /// (See: `LoweringContext::lower_expr()`).
1544 /// FIXME(#60607): This function is a hack. If and when we have `QPath::Lang(...)`,
1545 /// we can use that instead as simpler, more reliable mechanism, as opposed to using `SourceMap`.
1546 pub fn is_range_literal(sm: &SourceMap, expr: &Expr<'_>) -> bool {
1547 // Returns whether the given path represents a (desugared) range,
1548 // either in std or core, i.e. has either a `::std::ops::Range` or
1549 // `::core::ops::Range` prefix.
1550 fn is_range_path(path: &Path<'_>) -> bool {
1551 let segs: Vec<_> = path.segments.iter().map(|seg| seg.ident.to_string()).collect();
1552 let segs: Vec<_> = segs.iter().map(|seg| &**seg).collect();
1554 // "{{root}}" is the equivalent of `::` prefix in `Path`.
1555 if let ["{{root}}", std_core, "ops", range] = segs.as_slice() {
1556 (*std_core == "std" || *std_core == "core") && range.starts_with("Range")
1562 // Check whether a span corresponding to a range expression is a
1563 // range literal, rather than an explicit struct or `new()` call.
1564 fn is_lit(sm: &SourceMap, span: &Span) -> bool {
1565 let end_point = sm.end_point(*span);
1567 if let Ok(end_string) = sm.span_to_snippet(end_point) {
1568 !(end_string.ends_with("}") || end_string.ends_with(")"))
1575 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1576 ExprKind::Struct(ref qpath, _, _) => {
1577 if let QPath::Resolved(None, ref path) = **qpath {
1578 return is_range_path(&path) && is_lit(sm, &expr.span);
1582 // `..` desugars to its struct path.
1583 ExprKind::Path(QPath::Resolved(None, ref path)) => {
1584 return is_range_path(&path) && is_lit(sm, &expr.span);
1587 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1588 ExprKind::Call(ref func, _) => {
1589 if let ExprKind::Path(QPath::TypeRelative(ref ty, ref segment)) = func.kind {
1590 if let TyKind::Path(QPath::Resolved(None, ref path)) = ty.kind {
1591 let new_call = segment.ident.name == sym::new;
1592 return is_range_path(&path) && is_lit(sm, &expr.span) && new_call;
1603 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1604 pub enum ExprKind<'hir> {
1605 /// A `box x` expression.
1606 Box(&'hir Expr<'hir>),
1607 /// An array (e.g., `[a, b, c, d]`).
1608 Array(&'hir [Expr<'hir>]),
1609 /// A function call.
1611 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1612 /// and the second field is the list of arguments.
1613 /// This also represents calling the constructor of
1614 /// tuple-like ADTs such as tuple structs and enum variants.
1615 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1616 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1618 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1619 /// (within the angle brackets).
1620 /// The first element of the vector of `Expr`s is the expression that evaluates
1621 /// to the object on which the method is being called on (the receiver),
1622 /// and the remaining elements are the rest of the arguments.
1623 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1624 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1626 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1627 /// the `hir_id` of the `MethodCall` node itself.
1629 /// [`type_dependent_def_id`]: ../ty/struct.TypeckTables.html#method.type_dependent_def_id
1630 MethodCall(&'hir PathSegment<'hir>, Span, &'hir [Expr<'hir>]),
1631 /// A tuple (e.g., `(a, b, c, d)`).
1632 Tup(&'hir [Expr<'hir>]),
1633 /// A binary operation (e.g., `a + b`, `a * b`).
1634 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1635 /// A unary operation (e.g., `!x`, `*x`).
1636 Unary(UnOp, &'hir Expr<'hir>),
1637 /// A literal (e.g., `1`, `"foo"`).
1639 /// A cast (e.g., `foo as f64`).
1640 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1641 /// A type reference (e.g., `Foo`).
1642 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1643 /// Wraps the expression in a terminating scope.
1644 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1646 /// This construct only exists to tweak the drop order in HIR lowering.
1647 /// An example of that is the desugaring of `for` loops.
1648 DropTemps(&'hir Expr<'hir>),
1649 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1651 /// I.e., `'label: loop { <block> }`.
1652 Loop(&'hir Block<'hir>, Option<Label>, LoopSource),
1653 /// A `match` block, with a source that indicates whether or not it is
1654 /// the result of a desugaring, and if so, which kind.
1655 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1656 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1658 /// The `Span` is the argument block `|...|`.
1660 /// This may also be a generator literal or an `async block` as indicated by the
1661 /// `Option<Movability>`.
1662 Closure(CaptureBy, &'hir FnDecl<'hir>, BodyId, Span, Option<Movability>),
1663 /// A block (e.g., `'label: { ... }`).
1664 Block(&'hir Block<'hir>, Option<Label>),
1666 /// An assignment (e.g., `a = foo()`).
1667 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1668 /// An assignment with an operator.
1671 AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1672 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1673 Field(&'hir Expr<'hir>, Ident),
1674 /// An indexing operation (`foo[2]`).
1675 Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1677 /// Path to a definition, possibly containing lifetime or type parameters.
1680 /// A referencing operation (i.e., `&a` or `&mut a`).
1681 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1682 /// A `break`, with an optional label to break.
1683 Break(Destination, Option<&'hir Expr<'hir>>),
1684 /// A `continue`, with an optional label.
1685 Continue(Destination),
1686 /// A `return`, with an optional value to be returned.
1687 Ret(Option<&'hir Expr<'hir>>),
1689 /// Inline assembly (from `asm!`), with its outputs and inputs.
1690 InlineAsm(&'hir InlineAsm<'hir>),
1692 /// A struct or struct-like variant literal expression.
1694 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1695 /// where `base` is the `Option<Expr>`.
1696 Struct(&'hir QPath<'hir>, &'hir [Field<'hir>], Option<&'hir Expr<'hir>>),
1698 /// An array literal constructed from one repeated element.
1700 /// E.g., `[1; 5]`. The first expression is the element
1701 /// to be repeated; the second is the number of times to repeat it.
1702 Repeat(&'hir Expr<'hir>, AnonConst),
1704 /// A suspension point for generators (i.e., `yield <expr>`).
1705 Yield(&'hir Expr<'hir>, YieldSource),
1707 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1711 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1713 /// To resolve the path to a `DefId`, call [`qpath_res`].
1715 /// [`qpath_res`]: ../ty/struct.TypeckTables.html#method.qpath_res
1716 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1717 pub enum QPath<'hir> {
1718 /// Path to a definition, optionally "fully-qualified" with a `Self`
1719 /// type, if the path points to an associated item in a trait.
1721 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1722 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1723 /// even though they both have the same two-segment `Clone::clone` `Path`.
1724 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
1726 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1727 /// Will be resolved by type-checking to an associated item.
1729 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1730 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1731 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1732 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
1735 /// Hints at the original code for a let statement.
1736 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1737 pub enum LocalSource {
1738 /// A `match _ { .. }`.
1740 /// A desugared `for _ in _ { .. }` loop.
1742 /// When lowering async functions, we create locals within the `async move` so that
1743 /// all parameters are dropped after the future is polled.
1745 /// ```ignore (pseudo-Rust)
1746 /// async fn foo(<pattern> @ x: Type) {
1748 /// let <pattern> = x;
1753 /// A desugared `<expr>.await`.
1757 /// Hints at the original code for a `match _ { .. }`.
1758 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
1759 pub enum MatchSource {
1760 /// A `match _ { .. }`.
1762 /// An `if _ { .. }` (optionally with `else { .. }`).
1763 IfDesugar { contains_else_clause: bool },
1764 /// An `if let _ = _ { .. }` (optionally with `else { .. }`).
1765 IfLetDesugar { contains_else_clause: bool },
1766 /// A `while _ { .. }` (which was desugared to a `loop { match _ { .. } }`).
1768 /// A `while let _ = _ { .. }` (which was desugared to a
1769 /// `loop { match _ { .. } }`).
1771 /// A desugared `for _ in _ { .. }` loop.
1773 /// A desugared `?` operator.
1775 /// A desugared `<expr>.await`.
1780 pub fn name(self) -> &'static str {
1784 IfDesugar { .. } | IfLetDesugar { .. } => "if",
1785 WhileDesugar | WhileLetDesugar => "while",
1786 ForLoopDesugar => "for",
1788 AwaitDesugar => ".await",
1793 /// The loop type that yielded an `ExprKind::Loop`.
1794 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1795 pub enum LoopSource {
1796 /// A `loop { .. }` loop.
1798 /// A `while _ { .. }` loop.
1800 /// A `while let _ = _ { .. }` loop.
1802 /// A `for _ in _ { .. }` loop.
1807 pub fn name(self) -> &'static str {
1809 LoopSource::Loop => "loop",
1810 LoopSource::While | LoopSource::WhileLet => "while",
1811 LoopSource::ForLoop => "for",
1816 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1817 pub enum LoopIdError {
1819 UnlabeledCfInWhileCondition,
1823 impl fmt::Display for LoopIdError {
1824 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1825 f.write_str(match self {
1826 LoopIdError::OutsideLoopScope => "not inside loop scope",
1827 LoopIdError::UnlabeledCfInWhileCondition => {
1828 "unlabeled control flow (break or continue) in while condition"
1830 LoopIdError::UnresolvedLabel => "label not found",
1835 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1836 pub struct Destination {
1837 // This is `Some(_)` iff there is an explicit user-specified `label
1838 pub label: Option<Label>,
1840 // These errors are caught and then reported during the diagnostics pass in
1841 // librustc_passes/loops.rs
1842 pub target_id: Result<HirId, LoopIdError>,
1845 /// The yield kind that caused an `ExprKind::Yield`.
1846 #[derive(Copy, Clone, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable, HashStable)]
1847 pub enum YieldSource {
1848 /// An `<expr>.await`.
1850 /// A plain `yield`.
1854 impl fmt::Display for YieldSource {
1855 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1856 f.write_str(match self {
1857 YieldSource::Await => "`await`",
1858 YieldSource::Yield => "`yield`",
1863 impl From<GeneratorKind> for YieldSource {
1864 fn from(kind: GeneratorKind) -> Self {
1866 // Guess based on the kind of the current generator.
1867 GeneratorKind::Gen => Self::Yield,
1868 GeneratorKind::Async(_) => Self::Await,
1873 // N.B., if you change this, you'll probably want to change the corresponding
1874 // type structure in middle/ty.rs as well.
1875 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1876 pub struct MutTy<'hir> {
1877 pub ty: &'hir Ty<'hir>,
1878 pub mutbl: Mutability,
1881 /// Represents a function's signature in a trait declaration,
1882 /// trait implementation, or a free function.
1883 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1884 pub struct FnSig<'hir> {
1885 pub header: FnHeader,
1886 pub decl: &'hir FnDecl<'hir>,
1889 // The bodies for items are stored "out of line", in a separate
1890 // hashmap in the `Crate`. Here we just record the node-id of the item
1891 // so it can fetched later.
1892 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1893 pub struct TraitItemId {
1897 /// Represents an item declaration within a trait declaration,
1898 /// possibly including a default implementation. A trait item is
1899 /// either required (meaning it doesn't have an implementation, just a
1900 /// signature) or provided (meaning it has a default implementation).
1901 #[derive(RustcEncodable, RustcDecodable, Debug)]
1902 pub struct TraitItem<'hir> {
1905 pub attrs: &'hir [Attribute],
1906 pub generics: Generics<'hir>,
1907 pub kind: TraitItemKind<'hir>,
1911 /// Represents a trait method's body (or just argument names).
1912 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1913 pub enum TraitMethod<'hir> {
1914 /// No default body in the trait, just a signature.
1915 Required(&'hir [Ident]),
1917 /// Both signature and body are provided in the trait.
1921 /// Represents a trait method or associated constant or type
1922 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1923 pub enum TraitItemKind<'hir> {
1924 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
1925 Const(&'hir Ty<'hir>, Option<BodyId>),
1926 /// A method with an optional body.
1927 Method(FnSig<'hir>, TraitMethod<'hir>),
1928 /// An associated type with (possibly empty) bounds and optional concrete
1930 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
1933 // The bodies for items are stored "out of line", in a separate
1934 // hashmap in the `Crate`. Here we just record the node-id of the item
1935 // so it can fetched later.
1936 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1937 pub struct ImplItemId {
1941 /// Represents anything within an `impl` block.
1942 #[derive(RustcEncodable, RustcDecodable, Debug)]
1943 pub struct ImplItem<'hir> {
1946 pub vis: Visibility<'hir>,
1947 pub defaultness: Defaultness,
1948 pub attrs: &'hir [Attribute],
1949 pub generics: Generics<'hir>,
1950 pub kind: ImplItemKind<'hir>,
1954 /// Represents various kinds of content within an `impl`.
1955 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1956 pub enum ImplItemKind<'hir> {
1957 /// An associated constant of the given type, set to the constant result
1958 /// of the expression.
1959 Const(&'hir Ty<'hir>, BodyId),
1960 /// A method implementation with the given signature and body.
1961 Method(FnSig<'hir>, BodyId),
1962 /// An associated type.
1963 TyAlias(&'hir Ty<'hir>),
1964 /// An associated `type = impl Trait`.
1965 OpaqueTy(GenericBounds<'hir>),
1968 /// Bind a type to an associated type (i.e., `A = Foo`).
1970 /// Bindings like `A: Debug` are represented as a special type `A =
1971 /// $::Debug` that is understood by the astconv code.
1973 /// FIXME(alexreg): why have a separate type for the binding case,
1974 /// wouldn't it be better to make the `ty` field an enum like the
1978 /// enum TypeBindingKind {
1983 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1984 pub struct TypeBinding<'hir> {
1986 #[stable_hasher(project(name))]
1988 pub kind: TypeBindingKind<'hir>,
1992 // Represents the two kinds of type bindings.
1993 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1994 pub enum TypeBindingKind<'hir> {
1995 /// E.g., `Foo<Bar: Send>`.
1996 Constraint { bounds: &'hir [GenericBound<'hir>] },
1997 /// E.g., `Foo<Bar = ()>`.
1998 Equality { ty: &'hir Ty<'hir> },
2001 impl TypeBinding<'_> {
2002 pub fn ty(&self) -> &Ty<'_> {
2004 TypeBindingKind::Equality { ref ty } => ty,
2005 _ => bug!("expected equality type binding for parenthesized generic args"),
2010 #[derive(RustcEncodable, RustcDecodable)]
2011 pub struct Ty<'hir> {
2013 pub kind: TyKind<'hir>,
2017 impl fmt::Debug for Ty<'_> {
2018 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2019 write!(f, "type({})", print::to_string(print::NO_ANN, |s| s.print_type(self)))
2023 /// Not represented directly in the AST; referred to by name through a `ty_path`.
2024 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
2034 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2035 pub struct BareFnTy<'hir> {
2036 pub unsafety: Unsafety,
2038 pub generic_params: &'hir [GenericParam<'hir>],
2039 pub decl: &'hir FnDecl<'hir>,
2040 pub param_names: &'hir [Ident],
2043 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2044 pub struct OpaqueTy<'hir> {
2045 pub generics: Generics<'hir>,
2046 pub bounds: GenericBounds<'hir>,
2047 pub impl_trait_fn: Option<DefId>,
2048 pub origin: OpaqueTyOrigin,
2051 /// From whence the opaque type came.
2052 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2053 pub enum OpaqueTyOrigin {
2054 /// `type Foo = impl Trait;`
2062 /// The various kinds of types recognized by the compiler.
2063 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2064 pub enum TyKind<'hir> {
2065 /// A variable length slice (i.e., `[T]`).
2066 Slice(&'hir Ty<'hir>),
2067 /// A fixed length array (i.e., `[T; n]`).
2068 Array(&'hir Ty<'hir>, AnonConst),
2069 /// A raw pointer (i.e., `*const T` or `*mut T`).
2071 /// A reference (i.e., `&'a T` or `&'a mut T`).
2072 Rptr(Lifetime, MutTy<'hir>),
2073 /// A bare function (e.g., `fn(usize) -> bool`).
2074 BareFn(&'hir BareFnTy<'hir>),
2075 /// The never type (`!`).
2077 /// A tuple (`(A, B, C, D, ...)`).
2078 Tup(&'hir [Ty<'hir>]),
2079 /// A path to a type definition (`module::module::...::Type`), or an
2080 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2082 /// Type parameters may be stored in each `PathSegment`.
2084 /// A type definition itself. This is currently only used for the `type Foo = impl Trait`
2085 /// item that `impl Trait` in return position desugars to.
2087 /// The generic argument list contains the lifetimes (and in the future possibly parameters)
2088 /// that are actually bound on the `impl Trait`.
2089 Def(ItemId, &'hir [GenericArg<'hir>]),
2090 /// A trait object type `Bound1 + Bound2 + Bound3`
2091 /// where `Bound` is a trait or a lifetime.
2092 TraitObject(&'hir [PolyTraitRef<'hir>], Lifetime),
2095 /// `TyKind::Infer` means the type should be inferred instead of it having been
2096 /// specified. This can appear anywhere in a type.
2098 /// Placeholder for a type that has failed to be defined.
2102 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable, PartialEq)]
2103 pub struct InlineAsmOutput {
2104 pub constraint: Symbol,
2106 pub is_indirect: bool,
2110 // NOTE(eddyb) This is used within MIR as well, so unlike the rest of the HIR,
2111 // it needs to be `Clone` and use plain `Vec<T>` instead of arena-allocated slice.
2112 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable, PartialEq)]
2113 pub struct InlineAsmInner {
2115 pub asm_str_style: StrStyle,
2116 pub outputs: Vec<InlineAsmOutput>,
2117 pub inputs: Vec<Symbol>,
2118 pub clobbers: Vec<Symbol>,
2120 pub alignstack: bool,
2121 pub dialect: AsmDialect,
2124 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2125 pub struct InlineAsm<'hir> {
2126 pub inner: InlineAsmInner,
2127 pub outputs_exprs: &'hir [Expr<'hir>],
2128 pub inputs_exprs: &'hir [Expr<'hir>],
2131 /// Represents a parameter in a function header.
2132 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2133 pub struct Param<'hir> {
2134 pub attrs: &'hir [Attribute],
2136 pub pat: &'hir Pat<'hir>,
2140 /// Represents the header (not the body) of a function declaration.
2141 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2142 pub struct FnDecl<'hir> {
2143 /// The types of the function's parameters.
2145 /// Additional argument data is stored in the function's [body](Body::parameters).
2146 pub inputs: &'hir [Ty<'hir>],
2147 pub output: FunctionRetTy<'hir>,
2148 pub c_variadic: bool,
2149 /// Does the function have an implicit self?
2150 pub implicit_self: ImplicitSelfKind,
2153 /// Represents what type of implicit self a function has, if any.
2154 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2155 pub enum ImplicitSelfKind {
2156 /// Represents a `fn x(self);`.
2158 /// Represents a `fn x(mut self);`.
2160 /// Represents a `fn x(&self);`.
2162 /// Represents a `fn x(&mut self);`.
2164 /// Represents when a function does not have a self argument or
2165 /// when a function has a `self: X` argument.
2169 impl ImplicitSelfKind {
2170 /// Does this represent an implicit self?
2171 pub fn has_implicit_self(&self) -> bool {
2173 ImplicitSelfKind::None => false,
2196 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2197 pub enum Defaultness {
2198 Default { has_value: bool },
2203 pub fn has_value(&self) -> bool {
2205 Defaultness::Default { has_value, .. } => has_value,
2206 Defaultness::Final => true,
2210 pub fn is_final(&self) -> bool {
2211 *self == Defaultness::Final
2214 pub fn is_default(&self) -> bool {
2216 Defaultness::Default { .. } => true,
2222 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2223 pub enum FunctionRetTy<'hir> {
2224 /// Return type is not specified.
2226 /// Functions default to `()` and
2227 /// closures default to inference. Span points to where return
2228 /// type would be inserted.
2229 DefaultReturn(Span),
2230 /// Everything else.
2231 Return(&'hir Ty<'hir>),
2234 impl fmt::Display for FunctionRetTy<'_> {
2235 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2237 Return(ref ty) => print::to_string(print::NO_ANN, |s| s.print_type(ty)).fmt(f),
2238 DefaultReturn(_) => "()".fmt(f),
2243 impl FunctionRetTy<'_> {
2244 pub fn span(&self) -> Span {
2246 DefaultReturn(span) => span,
2247 Return(ref ty) => ty.span,
2252 #[derive(RustcEncodable, RustcDecodable, Debug)]
2253 pub struct Mod<'hir> {
2254 /// A span from the first token past `{` to the last token until `}`.
2255 /// For `mod foo;`, the inner span ranges from the first token
2256 /// to the last token in the external file.
2258 pub item_ids: &'hir [ItemId],
2261 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2262 pub struct ForeignMod<'hir> {
2264 pub items: &'hir [ForeignItem<'hir>],
2267 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2268 pub struct GlobalAsm {
2272 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2273 pub struct EnumDef<'hir> {
2274 pub variants: &'hir [Variant<'hir>],
2277 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2278 pub struct Variant<'hir> {
2279 /// Name of the variant.
2280 #[stable_hasher(project(name))]
2282 /// Attributes of the variant.
2283 pub attrs: &'hir [Attribute],
2284 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2286 /// Fields and constructor id of the variant.
2287 pub data: VariantData<'hir>,
2288 /// Explicit discriminant (e.g., `Foo = 1`).
2289 pub disr_expr: Option<AnonConst>,
2294 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2296 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2297 /// Also produced for each element of a list `use`, e.g.
2298 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2301 /// Glob import, e.g., `use foo::*`.
2304 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2305 /// an additional `use foo::{}` for performing checks such as
2306 /// unstable feature gating. May be removed in the future.
2310 /// References to traits in impls.
2312 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2313 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2314 /// trait being referred to but just a unique `HirId` that serves as a key
2315 /// within the resolution map.
2316 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2317 pub struct TraitRef<'hir> {
2318 pub path: &'hir Path<'hir>,
2319 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2320 #[stable_hasher(ignore)]
2321 pub hir_ref_id: HirId,
2325 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2326 pub fn trait_def_id(&self) -> DefId {
2327 match self.path.res {
2328 Res::Def(DefKind::Trait, did) => did,
2329 Res::Def(DefKind::TraitAlias, did) => did,
2333 _ => unreachable!(),
2338 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2339 pub struct PolyTraitRef<'hir> {
2340 /// The `'a` in `<'a> Foo<&'a T>`.
2341 pub bound_generic_params: &'hir [GenericParam<'hir>],
2343 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2344 pub trait_ref: TraitRef<'hir>,
2349 pub type Visibility<'hir> = Spanned<VisibilityKind<'hir>>;
2351 #[derive(RustcEncodable, RustcDecodable, Debug)]
2352 pub enum VisibilityKind<'hir> {
2355 Restricted { path: &'hir Path<'hir>, hir_id: HirId },
2359 impl VisibilityKind<'_> {
2360 pub fn is_pub(&self) -> bool {
2362 VisibilityKind::Public => true,
2367 pub fn is_pub_restricted(&self) -> bool {
2369 VisibilityKind::Public | VisibilityKind::Inherited => false,
2370 VisibilityKind::Crate(..) | VisibilityKind::Restricted { .. } => true,
2374 pub fn descr(&self) -> &'static str {
2376 VisibilityKind::Public => "public",
2377 VisibilityKind::Inherited => "private",
2378 VisibilityKind::Crate(..) => "crate-visible",
2379 VisibilityKind::Restricted { .. } => "restricted",
2384 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2385 pub struct StructField<'hir> {
2387 #[stable_hasher(project(name))]
2389 pub vis: Visibility<'hir>,
2391 pub ty: &'hir Ty<'hir>,
2392 pub attrs: &'hir [Attribute],
2395 impl StructField<'_> {
2396 // Still necessary in couple of places
2397 pub fn is_positional(&self) -> bool {
2398 let first = self.ident.as_str().as_bytes()[0];
2399 first >= b'0' && first <= b'9'
2403 /// Fields and constructor IDs of enum variants and structs.
2404 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2405 pub enum VariantData<'hir> {
2406 /// A struct variant.
2408 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2409 Struct(&'hir [StructField<'hir>], /* recovered */ bool),
2410 /// A tuple variant.
2412 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2413 Tuple(&'hir [StructField<'hir>], HirId),
2416 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2420 impl VariantData<'hir> {
2421 /// Return the fields of this variant.
2422 pub fn fields(&self) -> &'hir [StructField<'hir>] {
2424 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2429 /// Return the `HirId` of this variant's constructor, if it has one.
2430 pub fn ctor_hir_id(&self) -> Option<HirId> {
2432 VariantData::Struct(_, _) => None,
2433 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2438 // The bodies for items are stored "out of line", in a separate
2439 // hashmap in the `Crate`. Here we just record the node-id of the item
2440 // so it can fetched later.
2441 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2448 /// The name might be a dummy name in case of anonymous items
2449 #[derive(RustcEncodable, RustcDecodable, Debug)]
2450 pub struct Item<'hir> {
2453 pub attrs: &'hir [Attribute],
2454 pub kind: ItemKind<'hir>,
2455 pub vis: Visibility<'hir>,
2459 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2460 pub struct FnHeader {
2461 pub unsafety: Unsafety,
2462 pub constness: Constness,
2463 pub asyncness: IsAsync,
2468 pub fn is_const(&self) -> bool {
2469 match &self.constness {
2470 Constness::Const => true,
2476 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2477 pub enum ItemKind<'hir> {
2478 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2480 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2481 ExternCrate(Option<Name>),
2483 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2487 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2488 Use(&'hir Path<'hir>, UseKind),
2490 /// A `static` item.
2491 Static(&'hir Ty<'hir>, Mutability, BodyId),
2493 Const(&'hir Ty<'hir>, BodyId),
2494 /// A function declaration.
2495 Fn(FnSig<'hir>, Generics<'hir>, BodyId),
2498 /// An external module, e.g. `extern { .. }`.
2499 ForeignMod(ForeignMod<'hir>),
2500 /// Module-level inline assembly (from `global_asm!`).
2501 GlobalAsm(&'hir GlobalAsm),
2502 /// A type alias, e.g., `type Foo = Bar<u8>`.
2503 TyAlias(&'hir Ty<'hir>, Generics<'hir>),
2504 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2505 OpaqueTy(OpaqueTy<'hir>),
2506 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2507 Enum(EnumDef<'hir>, Generics<'hir>),
2508 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2509 Struct(VariantData<'hir>, Generics<'hir>),
2510 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2511 Union(VariantData<'hir>, Generics<'hir>),
2512 /// A trait definition.
2513 Trait(IsAuto, Unsafety, Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
2515 TraitAlias(Generics<'hir>, GenericBounds<'hir>),
2517 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2523 Option<TraitRef<'hir>>, // (optional) trait this impl implements
2524 &'hir Ty<'hir>, // self
2525 &'hir [ImplItemRef<'hir>],
2530 pub fn descriptive_variant(&self) -> &str {
2532 ItemKind::ExternCrate(..) => "extern crate",
2533 ItemKind::Use(..) => "use",
2534 ItemKind::Static(..) => "static item",
2535 ItemKind::Const(..) => "constant item",
2536 ItemKind::Fn(..) => "function",
2537 ItemKind::Mod(..) => "module",
2538 ItemKind::ForeignMod(..) => "foreign module",
2539 ItemKind::GlobalAsm(..) => "global asm",
2540 ItemKind::TyAlias(..) => "type alias",
2541 ItemKind::OpaqueTy(..) => "opaque type",
2542 ItemKind::Enum(..) => "enum",
2543 ItemKind::Struct(..) => "struct",
2544 ItemKind::Union(..) => "union",
2545 ItemKind::Trait(..) => "trait",
2546 ItemKind::TraitAlias(..) => "trait alias",
2547 ItemKind::Impl(..) => "impl",
2551 pub fn generics(&self) -> Option<&Generics<'_>> {
2553 ItemKind::Fn(_, ref generics, _)
2554 | ItemKind::TyAlias(_, ref generics)
2555 | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
2556 | ItemKind::Enum(_, ref generics)
2557 | ItemKind::Struct(_, ref generics)
2558 | ItemKind::Union(_, ref generics)
2559 | ItemKind::Trait(_, _, ref generics, _, _)
2560 | ItemKind::Impl(_, _, _, ref generics, _, _, _) => generics,
2566 /// A reference from an trait to one of its associated items. This
2567 /// contains the item's id, naturally, but also the item's name and
2568 /// some other high-level details (like whether it is an associated
2569 /// type or method, and whether it is public). This allows other
2570 /// passes to find the impl they want without loading the ID (which
2571 /// means fewer edges in the incremental compilation graph).
2572 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2573 pub struct TraitItemRef {
2574 pub id: TraitItemId,
2575 #[stable_hasher(project(name))]
2577 pub kind: AssocItemKind,
2579 pub defaultness: Defaultness,
2582 /// A reference from an impl to one of its associated items. This
2583 /// contains the item's ID, naturally, but also the item's name and
2584 /// some other high-level details (like whether it is an associated
2585 /// type or method, and whether it is public). This allows other
2586 /// passes to find the impl they want without loading the ID (which
2587 /// means fewer edges in the incremental compilation graph).
2588 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2589 pub struct ImplItemRef<'hir> {
2591 #[stable_hasher(project(name))]
2593 pub kind: AssocItemKind,
2595 pub vis: Visibility<'hir>,
2596 pub defaultness: Defaultness,
2599 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2600 pub enum AssocItemKind {
2602 Method { has_self: bool },
2607 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2608 pub struct ForeignItem<'hir> {
2609 #[stable_hasher(project(name))]
2611 pub attrs: &'hir [Attribute],
2612 pub kind: ForeignItemKind<'hir>,
2615 pub vis: Visibility<'hir>,
2618 /// An item within an `extern` block.
2619 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2620 pub enum ForeignItemKind<'hir> {
2621 /// A foreign function.
2622 Fn(&'hir FnDecl<'hir>, &'hir [Ident], Generics<'hir>),
2623 /// A foreign static item (`static ext: u8`).
2624 Static(&'hir Ty<'hir>, Mutability),
2629 impl ForeignItemKind<'hir> {
2630 pub fn descriptive_variant(&self) -> &str {
2632 ForeignItemKind::Fn(..) => "foreign function",
2633 ForeignItemKind::Static(..) => "foreign static item",
2634 ForeignItemKind::Type => "foreign type",
2639 /// A variable captured by a closure.
2640 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable, HashStable)]
2642 // First span where it is accessed (there can be multiple).
2646 pub type CaptureModeMap = NodeMap<CaptureBy>;
2648 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2649 // has length > 0 if the trait is found through an chain of imports, starting with the
2650 // import/use statement in the scope where the trait is used.
2651 #[derive(Clone, Debug)]
2652 pub struct TraitCandidate {
2654 pub import_ids: SmallVec<[NodeId; 1]>,
2657 // Trait method resolution
2658 pub type TraitMap = NodeMap<Vec<TraitCandidate>>;
2660 // Map from the NodeId of a glob import to a list of items which are actually
2662 pub type GlobMap = NodeMap<FxHashSet<Name>>;
2664 pub fn provide(providers: &mut Providers<'_>) {
2665 check_attr::provide(providers);
2666 map::provide(providers);
2667 upvars::provide(providers);
2670 #[derive(Copy, Clone, Debug)]
2671 pub enum Node<'hir> {
2672 Param(&'hir Param<'hir>),
2673 Item(&'hir Item<'hir>),
2674 ForeignItem(&'hir ForeignItem<'hir>),
2675 TraitItem(&'hir TraitItem<'hir>),
2676 ImplItem(&'hir ImplItem<'hir>),
2677 Variant(&'hir Variant<'hir>),
2678 Field(&'hir StructField<'hir>),
2679 AnonConst(&'hir AnonConst),
2680 Expr(&'hir Expr<'hir>),
2681 Stmt(&'hir Stmt<'hir>),
2682 PathSegment(&'hir PathSegment<'hir>),
2684 TraitRef(&'hir TraitRef<'hir>),
2685 Binding(&'hir Pat<'hir>),
2686 Pat(&'hir Pat<'hir>),
2687 Arm(&'hir Arm<'hir>),
2688 Block(&'hir Block<'hir>),
2689 Local(&'hir Local<'hir>),
2690 MacroDef(&'hir MacroDef<'hir>),
2692 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
2693 /// with synthesized constructors.
2694 Ctor(&'hir VariantData<'hir>),
2696 Lifetime(&'hir Lifetime),
2697 GenericParam(&'hir GenericParam<'hir>),
2698 Visibility(&'hir Visibility<'hir>),
2704 pub fn ident(&self) -> Option<Ident> {
2706 Node::TraitItem(TraitItem { ident, .. })
2707 | Node::ImplItem(ImplItem { ident, .. })
2708 | Node::ForeignItem(ForeignItem { ident, .. })
2709 | Node::Item(Item { ident, .. }) => Some(*ident),