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;
37 pub use rustc_hir::def_id;
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 rustc_data_structures::define_id_collections!(HirIdMap, HirIdSet, HirId);
97 rustc_data_structures::define_id_collections!(ItemLocalMap, ItemLocalSet, ItemLocalId);
99 // Hack to ensure that we don't try to access the private parts of `ItemLocalId` in this module.
100 mod item_local_id_inner {
101 use rustc_index::vec::Idx;
102 use rustc_macros::HashStable;
103 rustc_index::newtype_index! {
104 /// An `ItemLocalId` uniquely identifies something within a given "item-like";
105 /// that is, within a `hir::Item`, `hir::TraitItem`, or `hir::ImplItem`. There is no
106 /// guarantee that the numerical value of a given `ItemLocalId` corresponds to
107 /// the node's position within the owning item in any way, but there is a
108 /// guarantee that the `LocalItemId`s within an owner occupy a dense range of
109 /// integers starting at zero, so a mapping that maps all or most nodes within
110 /// an "item-like" to something else can be implemented by a `Vec` instead of a
111 /// tree or hash map.
112 pub struct ItemLocalId {
118 pub use self::item_local_id_inner::ItemLocalId;
120 /// The `HirId` corresponding to `CRATE_NODE_ID` and `CRATE_DEF_INDEX`.
121 pub const CRATE_HIR_ID: HirId =
122 HirId { owner: CRATE_DEF_INDEX, local_id: ItemLocalId::from_u32_const(0) };
124 pub const DUMMY_HIR_ID: HirId = HirId { owner: CRATE_DEF_INDEX, local_id: DUMMY_ITEM_LOCAL_ID };
126 pub const DUMMY_ITEM_LOCAL_ID: ItemLocalId = ItemLocalId::MAX;
128 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, HashStable)]
129 pub struct Lifetime {
133 /// Either "`'a`", referring to a named lifetime definition,
134 /// or "``" (i.e., `kw::Invalid`), for elision placeholders.
136 /// HIR lowering inserts these placeholders in type paths that
137 /// refer to type definitions needing lifetime parameters,
138 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
139 pub name: LifetimeName,
142 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy, HashStable)]
144 /// Some user-given name like `T` or `'x`.
147 /// Synthetic name generated when user elided a lifetime in an impl header.
149 /// E.g., the lifetimes in cases like these:
151 /// impl Foo for &u32
152 /// impl Foo<'_> for u32
154 /// in that case, we rewrite to
156 /// impl<'f> Foo for &'f u32
157 /// impl<'f> Foo<'f> for u32
159 /// where `'f` is something like `Fresh(0)`. The indices are
160 /// unique per impl, but not necessarily continuous.
163 /// Indicates an illegal name was given and an error has been
164 /// reported (so we should squelch other derived errors). Occurs
165 /// when, e.g., `'_` is used in the wrong place.
170 pub fn ident(&self) -> Ident {
172 ParamName::Plain(ident) => ident,
173 ParamName::Fresh(_) | ParamName::Error => {
174 Ident::with_dummy_span(kw::UnderscoreLifetime)
179 pub fn modern(&self) -> ParamName {
181 ParamName::Plain(ident) => ParamName::Plain(ident.modern()),
182 param_name => param_name,
187 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy, HashStable)]
188 pub enum LifetimeName {
189 /// User-given names or fresh (synthetic) names.
192 /// User wrote nothing (e.g., the lifetime in `&u32`).
195 /// Implicit lifetime in a context like `dyn Foo`. This is
196 /// distinguished from implicit lifetimes elsewhere because the
197 /// lifetime that they default to must appear elsewhere within the
198 /// enclosing type. This means that, in an `impl Trait` context, we
199 /// don't have to create a parameter for them. That is, `impl
200 /// Trait<Item = &u32>` expands to an opaque type like `type
201 /// Foo<'a> = impl Trait<Item = &'a u32>`, but `impl Trait<item =
202 /// dyn Bar>` expands to `type Foo = impl Trait<Item = dyn Bar +
203 /// 'static>`. The latter uses `ImplicitObjectLifetimeDefault` so
204 /// that surrounding code knows not to create a lifetime
206 ImplicitObjectLifetimeDefault,
208 /// Indicates an error during lowering (usually `'_` in wrong place)
209 /// that was already reported.
212 /// User wrote specifies `'_`.
215 /// User wrote `'static`.
220 pub fn ident(&self) -> Ident {
222 LifetimeName::ImplicitObjectLifetimeDefault
223 | LifetimeName::Implicit
224 | LifetimeName::Error => Ident::invalid(),
225 LifetimeName::Underscore => Ident::with_dummy_span(kw::UnderscoreLifetime),
226 LifetimeName::Static => Ident::with_dummy_span(kw::StaticLifetime),
227 LifetimeName::Param(param_name) => param_name.ident(),
231 pub fn is_elided(&self) -> bool {
233 LifetimeName::ImplicitObjectLifetimeDefault
234 | LifetimeName::Implicit
235 | LifetimeName::Underscore => true,
237 // It might seem surprising that `Fresh(_)` counts as
238 // *not* elided -- but this is because, as far as the code
239 // in the compiler is concerned -- `Fresh(_)` variants act
240 // equivalently to "some fresh name". They correspond to
241 // early-bound regions on an impl, in other words.
242 LifetimeName::Error | LifetimeName::Param(_) | LifetimeName::Static => false,
246 fn is_static(&self) -> bool {
247 self == &LifetimeName::Static
250 pub fn modern(&self) -> LifetimeName {
252 LifetimeName::Param(param_name) => LifetimeName::Param(param_name.modern()),
253 lifetime_name => lifetime_name,
258 impl fmt::Display for Lifetime {
259 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
260 self.name.ident().fmt(f)
264 impl fmt::Debug for Lifetime {
265 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
270 print::to_string(print::NO_ANN, |s| s.print_lifetime(self))
276 pub fn is_elided(&self) -> bool {
277 self.name.is_elided()
280 pub fn is_static(&self) -> bool {
281 self.name.is_static()
285 /// A `Path` is essentially Rust's notion of a name; for instance,
286 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
287 /// along with a bunch of supporting information.
288 #[derive(RustcEncodable, RustcDecodable, HashStable)]
289 pub struct Path<'hir> {
291 /// The resolution for the path.
293 /// The segments in the path: the things separated by `::`.
294 pub segments: &'hir [PathSegment<'hir>],
298 pub fn is_global(&self) -> bool {
299 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
303 impl fmt::Debug for Path<'_> {
304 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
305 write!(f, "path({})", self)
309 impl fmt::Display for Path<'_> {
310 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
311 write!(f, "{}", print::to_string(print::NO_ANN, |s| s.print_path(self, false)))
315 /// A segment of a path: an identifier, an optional lifetime, and a set of
317 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
318 pub struct PathSegment<'hir> {
319 /// The identifier portion of this path segment.
320 #[stable_hasher(project(name))]
322 // `id` and `res` are optional. We currently only use these in save-analysis,
323 // any path segments without these will not have save-analysis info and
324 // therefore will not have 'jump to def' in IDEs, but otherwise will not be
325 // affected. (In general, we don't bother to get the defs for synthesized
326 // segments, only for segments which have come from the AST).
327 pub hir_id: Option<HirId>,
328 pub res: Option<Res>,
330 /// Type/lifetime parameters attached to this path. They come in
331 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
332 /// this is more than just simple syntactic sugar; the use of
333 /// parens affects the region binding rules, so we preserve the
335 pub args: Option<&'hir GenericArgs<'hir>>,
337 /// Whether to infer remaining type parameters, if any.
338 /// This only applies to expression and pattern paths, and
339 /// out of those only the segments with no type parameters
340 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
341 pub infer_args: bool,
344 impl<'hir> PathSegment<'hir> {
345 /// Converts an identifier to the corresponding segment.
346 pub fn from_ident(ident: Ident) -> PathSegment<'hir> {
347 PathSegment { ident, hir_id: None, res: None, infer_args: true, args: None }
350 pub fn generic_args(&self) -> &GenericArgs<'hir> {
351 if let Some(ref args) = self.args {
354 const DUMMY: &GenericArgs<'_> = &GenericArgs::none();
360 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
361 pub struct ConstArg {
362 pub value: AnonConst,
366 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
367 pub enum GenericArg<'hir> {
373 impl GenericArg<'_> {
374 pub fn span(&self) -> Span {
376 GenericArg::Lifetime(l) => l.span,
377 GenericArg::Type(t) => t.span,
378 GenericArg::Const(c) => c.span,
382 pub fn id(&self) -> HirId {
384 GenericArg::Lifetime(l) => l.hir_id,
385 GenericArg::Type(t) => t.hir_id,
386 GenericArg::Const(c) => c.value.hir_id,
390 pub fn is_const(&self) -> bool {
392 GenericArg::Const(_) => true,
398 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
399 pub struct GenericArgs<'hir> {
400 /// The generic arguments for this path segment.
401 pub args: &'hir [GenericArg<'hir>],
402 /// Bindings (equality constraints) on associated types, if present.
403 /// E.g., `Foo<A = Bar>`.
404 pub bindings: &'hir [TypeBinding<'hir>],
405 /// Were arguments written in parenthesized form `Fn(T) -> U`?
406 /// This is required mostly for pretty-printing and diagnostics,
407 /// but also for changing lifetime elision rules to be "function-like".
408 pub parenthesized: bool,
411 impl GenericArgs<'_> {
412 pub const fn none() -> Self {
413 Self { args: &[], bindings: &[], parenthesized: false }
416 pub fn is_empty(&self) -> bool {
417 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
420 pub fn inputs(&self) -> &[Ty<'_>] {
421 if self.parenthesized {
422 for arg in self.args {
424 GenericArg::Lifetime(_) => {}
425 GenericArg::Type(ref ty) => {
426 if let TyKind::Tup(ref tys) = ty.kind {
431 GenericArg::Const(_) => {}
435 bug!("GenericArgs::inputs: not a `Fn(T) -> U`");
438 pub fn own_counts(&self) -> GenericParamCount {
439 // We could cache this as a property of `GenericParamCount`, but
440 // the aim is to refactor this away entirely eventually and the
441 // presence of this method will be a constant reminder.
442 let mut own_counts: GenericParamCount = Default::default();
444 for arg in self.args {
446 GenericArg::Lifetime(_) => own_counts.lifetimes += 1,
447 GenericArg::Type(_) => own_counts.types += 1,
448 GenericArg::Const(_) => own_counts.consts += 1,
456 /// A modifier on a bound, currently this is only used for `?Sized`, where the
457 /// modifier is `Maybe`. Negative bounds should also be handled here.
458 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
459 pub enum TraitBoundModifier {
464 /// The AST represents all type param bounds as types.
465 /// `typeck::collect::compute_bounds` matches these against
466 /// the "special" built-in traits (see `middle::lang_items`) and
467 /// detects `Copy`, `Send` and `Sync`.
468 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
469 pub enum GenericBound<'hir> {
470 Trait(PolyTraitRef<'hir>, TraitBoundModifier),
474 impl GenericBound<'_> {
475 pub fn span(&self) -> Span {
477 &GenericBound::Trait(ref t, ..) => t.span,
478 &GenericBound::Outlives(ref l) => l.span,
483 pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
485 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable)]
486 pub enum LifetimeParamKind {
487 // Indicates that the lifetime definition was explicitly declared (e.g., in
488 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
491 // Indicates that the lifetime definition was synthetically added
492 // as a result of an in-band lifetime usage (e.g., in
493 // `fn foo(x: &'a u8) -> &'a u8 { x }`).
496 // Indication that the lifetime was elided (e.g., in both cases in
497 // `fn foo(x: &u8) -> &'_ u8 { x }`).
500 // Indication that the lifetime name was somehow in error.
504 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
505 pub enum GenericParamKind<'hir> {
506 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
508 kind: LifetimeParamKind,
511 default: Option<&'hir Ty<'hir>>,
512 synthetic: Option<SyntheticTyParamKind>,
519 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
520 pub struct GenericParam<'hir> {
523 pub attrs: &'hir [Attribute],
524 pub bounds: GenericBounds<'hir>,
526 pub pure_wrt_drop: bool,
527 pub kind: GenericParamKind<'hir>,
531 pub struct GenericParamCount {
532 pub lifetimes: usize,
537 /// Represents lifetimes and type parameters attached to a declaration
538 /// of a function, enum, trait, etc.
539 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
540 pub struct Generics<'hir> {
541 pub params: &'hir [GenericParam<'hir>],
542 pub where_clause: WhereClause<'hir>,
546 impl Generics<'hir> {
547 pub const fn empty() -> Generics<'hir> {
550 where_clause: WhereClause { predicates: &[], span: DUMMY_SP },
555 pub fn own_counts(&self) -> GenericParamCount {
556 // We could cache this as a property of `GenericParamCount`, but
557 // the aim is to refactor this away entirely eventually and the
558 // presence of this method will be a constant reminder.
559 let mut own_counts: GenericParamCount = Default::default();
561 for param in self.params {
563 GenericParamKind::Lifetime { .. } => own_counts.lifetimes += 1,
564 GenericParamKind::Type { .. } => own_counts.types += 1,
565 GenericParamKind::Const { .. } => own_counts.consts += 1,
572 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'_>> {
573 for param in self.params {
574 if name == param.name.ident().name {
581 pub fn spans(&self) -> MultiSpan {
582 if self.params.is_empty() {
585 self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
590 /// Synthetic type parameters are converted to another form during lowering; this allows
591 /// us to track the original form they had, and is useful for error messages.
592 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
593 pub enum SyntheticTyParamKind {
597 /// A where-clause in a definition.
598 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
599 pub struct WhereClause<'hir> {
600 pub predicates: &'hir [WherePredicate<'hir>],
601 // Only valid if predicates isn't empty.
605 impl WhereClause<'_> {
606 pub fn span(&self) -> Option<Span> {
607 if self.predicates.is_empty() { None } else { Some(self.span) }
610 /// The `WhereClause` under normal circumstances points at either the predicates or the empty
611 /// space where the `where` clause should be. Only of use for diagnostic suggestions.
612 pub fn span_for_predicates_or_empty_place(&self) -> Span {
617 /// A single predicate in a where-clause.
618 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
619 pub enum WherePredicate<'hir> {
620 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
621 BoundPredicate(WhereBoundPredicate<'hir>),
622 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
623 RegionPredicate(WhereRegionPredicate<'hir>),
624 /// An equality predicate (unsupported).
625 EqPredicate(WhereEqPredicate<'hir>),
628 impl WherePredicate<'_> {
629 pub fn span(&self) -> Span {
631 &WherePredicate::BoundPredicate(ref p) => p.span,
632 &WherePredicate::RegionPredicate(ref p) => p.span,
633 &WherePredicate::EqPredicate(ref p) => p.span,
638 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
639 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
640 pub struct WhereBoundPredicate<'hir> {
642 /// Any generics from a `for` binding.
643 pub bound_generic_params: &'hir [GenericParam<'hir>],
644 /// The type being bounded.
645 pub bounded_ty: &'hir Ty<'hir>,
646 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
647 pub bounds: GenericBounds<'hir>,
650 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
651 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
652 pub struct WhereRegionPredicate<'hir> {
654 pub lifetime: Lifetime,
655 pub bounds: GenericBounds<'hir>,
658 /// An equality predicate (e.g., `T = int`); currently unsupported.
659 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
660 pub struct WhereEqPredicate<'hir> {
663 pub lhs_ty: &'hir Ty<'hir>,
664 pub rhs_ty: &'hir Ty<'hir>,
667 #[derive(RustcEncodable, RustcDecodable, Debug)]
668 pub struct ModuleItems {
669 // Use BTreeSets here so items are in the same order as in the
670 // list of all items in Crate
671 pub items: BTreeSet<HirId>,
672 pub trait_items: BTreeSet<TraitItemId>,
673 pub impl_items: BTreeSet<ImplItemId>,
676 /// The top-level data structure that stores the entire contents of
677 /// the crate currently being compiled.
679 /// For more details, see the [rustc guide].
681 /// [rustc guide]: https://rust-lang.github.io/rustc-guide/hir.html
682 #[derive(RustcEncodable, RustcDecodable, Debug)]
683 pub struct Crate<'hir> {
684 pub module: Mod<'hir>,
685 pub attrs: &'hir [Attribute],
687 pub exported_macros: &'hir [MacroDef<'hir>],
688 // Attributes from non-exported macros, kept only for collecting the library feature list.
689 pub non_exported_macro_attrs: &'hir [Attribute],
691 // N.B., we use a `BTreeMap` here so that `visit_all_items` iterates
692 // over the ids in increasing order. In principle it should not
693 // matter what order we visit things in, but in *practice* it
694 // does, because it can affect the order in which errors are
695 // detected, which in turn can make compile-fail tests yield
696 // slightly different results.
697 pub items: BTreeMap<HirId, Item<'hir>>,
699 pub trait_items: BTreeMap<TraitItemId, TraitItem<'hir>>,
700 pub impl_items: BTreeMap<ImplItemId, ImplItem<'hir>>,
701 pub bodies: BTreeMap<BodyId, Body<'hir>>,
702 pub trait_impls: BTreeMap<DefId, Vec<HirId>>,
704 /// A list of the body ids written out in the order in which they
705 /// appear in the crate. If you're going to process all the bodies
706 /// in the crate, you should iterate over this list rather than the keys
708 pub body_ids: Vec<BodyId>,
710 /// A list of modules written out in the order in which they
711 /// appear in the crate. This includes the main crate module.
712 pub modules: BTreeMap<HirId, ModuleItems>,
716 pub fn item(&self, id: HirId) -> &Item<'hir> {
720 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem<'hir> {
721 &self.trait_items[&id]
724 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem<'hir> {
725 &self.impl_items[&id]
728 pub fn body(&self, id: BodyId) -> &Body<'hir> {
734 /// Visits all items in the crate in some deterministic (but
735 /// unspecified) order. If you just need to process every item,
736 /// but don't care about nesting, this method is the best choice.
738 /// If you do care about nesting -- usually because your algorithm
739 /// follows lexical scoping rules -- then you want a different
740 /// approach. You should override `visit_nested_item` in your
741 /// visitor and then call `intravisit::walk_crate` instead.
742 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
744 V: itemlikevisit::ItemLikeVisitor<'hir>,
746 for (_, item) in &self.items {
747 visitor.visit_item(item);
750 for (_, trait_item) in &self.trait_items {
751 visitor.visit_trait_item(trait_item);
754 for (_, impl_item) in &self.impl_items {
755 visitor.visit_impl_item(impl_item);
759 /// A parallel version of `visit_all_item_likes`.
760 pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
762 V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send,
766 par_for_each_in(&self.items, |(_, item)| {
767 visitor.visit_item(item);
771 par_for_each_in(&self.trait_items, |(_, trait_item)| {
772 visitor.visit_trait_item(trait_item);
776 par_for_each_in(&self.impl_items, |(_, impl_item)| {
777 visitor.visit_impl_item(impl_item);
784 /// A macro definition, in this crate or imported from another.
786 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
787 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
788 pub struct MacroDef<'hir> {
790 pub vis: Visibility<'hir>,
791 pub attrs: &'hir [Attribute],
794 pub body: TokenStream,
798 /// A block of statements `{ .. }`, which may have a label (in this case the
799 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
800 /// the `rules` being anything but `DefaultBlock`.
801 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
802 pub struct Block<'hir> {
803 /// Statements in a block.
804 pub stmts: &'hir [Stmt<'hir>],
805 /// An expression at the end of the block
806 /// without a semicolon, if any.
807 pub expr: Option<&'hir Expr<'hir>>,
808 #[stable_hasher(ignore)]
810 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
811 pub rules: BlockCheckMode,
813 /// If true, then there may exist `break 'a` values that aim to
814 /// break out of this block early.
815 /// Used by `'label: {}` blocks and by `try {}` blocks.
816 pub targeted_by_break: bool,
819 #[derive(RustcEncodable, RustcDecodable, HashStable)]
820 pub struct Pat<'hir> {
821 #[stable_hasher(ignore)]
823 pub kind: PatKind<'hir>,
827 impl fmt::Debug for Pat<'_> {
828 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
833 print::to_string(print::NO_ANN, |s| s.print_pat(self))
839 // FIXME(#19596) this is a workaround, but there should be a better way
840 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'_>) -> bool) -> bool {
847 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
848 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
849 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
850 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
851 Slice(before, slice, after) => {
852 before.iter().chain(slice.iter()).chain(after.iter()).all(|p| p.walk_short_(it))
857 /// Walk the pattern in left-to-right order,
858 /// short circuiting (with `.all(..)`) if `false` is returned.
860 /// Note that when visiting e.g. `Tuple(ps)`,
861 /// if visiting `ps[0]` returns `false`,
862 /// then `ps[1]` will not be visited.
863 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'_>) -> bool) -> bool {
864 self.walk_short_(&mut it)
867 // FIXME(#19596) this is a workaround, but there should be a better way
868 fn walk_(&self, it: &mut impl FnMut(&Pat<'_>) -> bool) {
875 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
876 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
877 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
878 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
879 Slice(before, slice, after) => {
880 before.iter().chain(slice.iter()).chain(after.iter()).for_each(|p| p.walk_(it))
885 /// Walk the pattern in left-to-right order.
887 /// If `it(pat)` returns `false`, the children are not visited.
888 pub fn walk(&self, mut it: impl FnMut(&Pat<'_>) -> bool) {
892 /// Walk the pattern in left-to-right order.
894 /// If you always want to recurse, prefer this method over `walk`.
895 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
903 /// A single field in a struct pattern.
905 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
906 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
907 /// except `is_shorthand` is true.
908 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
909 pub struct FieldPat<'hir> {
910 #[stable_hasher(ignore)]
912 /// The identifier for the field.
913 #[stable_hasher(project(name))]
915 /// The pattern the field is destructured to.
916 pub pat: &'hir Pat<'hir>,
917 pub is_shorthand: bool,
921 /// Explicit binding annotations given in the HIR for a binding. Note
922 /// that this is not the final binding *mode* that we infer after type
924 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
925 pub enum BindingAnnotation {
926 /// No binding annotation given: this means that the final binding mode
927 /// will depend on whether we have skipped through a `&` reference
928 /// when matching. For example, the `x` in `Some(x)` will have binding
929 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
930 /// ultimately be inferred to be by-reference.
932 /// Note that implicit reference skipping is not implemented yet (#42640).
935 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
938 /// Annotated as `ref`, like `ref x`
941 /// Annotated as `ref mut x`.
945 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
951 impl fmt::Display for RangeEnd {
952 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
953 f.write_str(match self {
954 RangeEnd::Included => "..=",
955 RangeEnd::Excluded => "..",
960 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
961 pub enum PatKind<'hir> {
962 /// Represents a wildcard pattern (i.e., `_`).
965 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
966 /// The `HirId` is the canonical ID for the variable being bound,
967 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
968 /// which is the pattern ID of the first `x`.
969 Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
971 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
972 /// The `bool` is `true` in the presence of a `..`.
973 Struct(QPath<'hir>, &'hir [FieldPat<'hir>], bool),
975 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
976 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
977 /// `0 <= position <= subpats.len()`
978 TupleStruct(QPath<'hir>, &'hir [&'hir Pat<'hir>], Option<usize>),
980 /// An or-pattern `A | B | C`.
981 /// Invariant: `pats.len() >= 2`.
982 Or(&'hir [&'hir Pat<'hir>]),
984 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
987 /// A tuple pattern (e.g., `(a, b)`).
988 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
989 /// `0 <= position <= subpats.len()`
990 Tuple(&'hir [&'hir Pat<'hir>], Option<usize>),
993 Box(&'hir Pat<'hir>),
995 /// A reference pattern (e.g., `&mut (a, b)`).
996 Ref(&'hir Pat<'hir>, Mutability),
999 Lit(&'hir Expr<'hir>),
1001 /// A range pattern (e.g., `1..=2` or `1..2`).
1002 Range(&'hir Expr<'hir>, &'hir Expr<'hir>, RangeEnd),
1004 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
1006 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
1007 /// If `slice` exists, then `after` can be non-empty.
1009 /// The representation for e.g., `[a, b, .., c, d]` is:
1011 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
1013 Slice(&'hir [&'hir Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [&'hir Pat<'hir>]),
1016 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1017 pub enum BinOpKind {
1018 /// The `+` operator (addition).
1020 /// The `-` operator (subtraction).
1022 /// The `*` operator (multiplication).
1024 /// The `/` operator (division).
1026 /// The `%` operator (modulus).
1028 /// The `&&` operator (logical and).
1030 /// The `||` operator (logical or).
1032 /// The `^` operator (bitwise xor).
1034 /// The `&` operator (bitwise and).
1036 /// The `|` operator (bitwise or).
1038 /// The `<<` operator (shift left).
1040 /// The `>>` operator (shift right).
1042 /// The `==` operator (equality).
1044 /// The `<` operator (less than).
1046 /// The `<=` operator (less than or equal to).
1048 /// The `!=` operator (not equal to).
1050 /// The `>=` operator (greater than or equal to).
1052 /// The `>` operator (greater than).
1057 pub fn as_str(self) -> &'static str {
1059 BinOpKind::Add => "+",
1060 BinOpKind::Sub => "-",
1061 BinOpKind::Mul => "*",
1062 BinOpKind::Div => "/",
1063 BinOpKind::Rem => "%",
1064 BinOpKind::And => "&&",
1065 BinOpKind::Or => "||",
1066 BinOpKind::BitXor => "^",
1067 BinOpKind::BitAnd => "&",
1068 BinOpKind::BitOr => "|",
1069 BinOpKind::Shl => "<<",
1070 BinOpKind::Shr => ">>",
1071 BinOpKind::Eq => "==",
1072 BinOpKind::Lt => "<",
1073 BinOpKind::Le => "<=",
1074 BinOpKind::Ne => "!=",
1075 BinOpKind::Ge => ">=",
1076 BinOpKind::Gt => ">",
1080 pub fn is_lazy(self) -> bool {
1082 BinOpKind::And | BinOpKind::Or => true,
1087 pub fn is_shift(self) -> bool {
1089 BinOpKind::Shl | BinOpKind::Shr => true,
1094 pub fn is_comparison(self) -> bool {
1101 | BinOpKind::Ge => true,
1113 | BinOpKind::Shr => false,
1117 /// Returns `true` if the binary operator takes its arguments by value.
1118 pub fn is_by_value(self) -> bool {
1119 !self.is_comparison()
1123 impl Into<ast::BinOpKind> for BinOpKind {
1124 fn into(self) -> ast::BinOpKind {
1126 BinOpKind::Add => ast::BinOpKind::Add,
1127 BinOpKind::Sub => ast::BinOpKind::Sub,
1128 BinOpKind::Mul => ast::BinOpKind::Mul,
1129 BinOpKind::Div => ast::BinOpKind::Div,
1130 BinOpKind::Rem => ast::BinOpKind::Rem,
1131 BinOpKind::And => ast::BinOpKind::And,
1132 BinOpKind::Or => ast::BinOpKind::Or,
1133 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1134 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1135 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1136 BinOpKind::Shl => ast::BinOpKind::Shl,
1137 BinOpKind::Shr => ast::BinOpKind::Shr,
1138 BinOpKind::Eq => ast::BinOpKind::Eq,
1139 BinOpKind::Lt => ast::BinOpKind::Lt,
1140 BinOpKind::Le => ast::BinOpKind::Le,
1141 BinOpKind::Ne => ast::BinOpKind::Ne,
1142 BinOpKind::Ge => ast::BinOpKind::Ge,
1143 BinOpKind::Gt => ast::BinOpKind::Gt,
1148 pub type BinOp = Spanned<BinOpKind>;
1150 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1152 /// The `*` operator (deferencing).
1154 /// The `!` operator (logical negation).
1156 /// The `-` operator (negation).
1161 pub fn as_str(self) -> &'static str {
1169 /// Returns `true` if the unary operator takes its argument by value.
1170 pub fn is_by_value(self) -> bool {
1172 UnNeg | UnNot => true,
1179 #[derive(RustcEncodable, RustcDecodable, HashStable)]
1180 pub struct Stmt<'hir> {
1182 pub kind: StmtKind<'hir>,
1186 impl fmt::Debug for Stmt<'_> {
1187 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1192 print::to_string(print::NO_ANN, |s| s.print_stmt(self))
1197 /// The contents of a statement.
1198 #[derive(RustcEncodable, RustcDecodable, HashStable)]
1199 pub enum StmtKind<'hir> {
1200 /// A local (`let`) binding.
1201 Local(&'hir Local<'hir>),
1203 /// An item binding.
1206 /// An expression without a trailing semi-colon (must have unit type).
1207 Expr(&'hir Expr<'hir>),
1209 /// An expression with a trailing semi-colon (may have any type).
1210 Semi(&'hir Expr<'hir>),
1213 impl StmtKind<'hir> {
1214 pub fn attrs(&self) -> &'hir [Attribute] {
1216 StmtKind::Local(ref l) => &l.attrs,
1217 StmtKind::Item(_) => &[],
1218 StmtKind::Expr(ref e) | StmtKind::Semi(ref e) => &e.attrs,
1223 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1224 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1225 pub struct Local<'hir> {
1226 pub pat: &'hir Pat<'hir>,
1227 /// Type annotation, if any (otherwise the type will be inferred).
1228 pub ty: Option<&'hir Ty<'hir>>,
1229 /// Initializer expression to set the value, if any.
1230 pub init: Option<&'hir Expr<'hir>>,
1234 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1235 /// desugaring. Otherwise will be `Normal`.
1236 pub source: LocalSource,
1239 /// Represents a single arm of a `match` expression, e.g.
1240 /// `<pat> (if <guard>) => <body>`.
1241 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1242 pub struct Arm<'hir> {
1243 #[stable_hasher(ignore)]
1246 pub attrs: &'hir [Attribute],
1247 /// If this pattern and the optional guard matches, then `body` is evaluated.
1248 pub pat: &'hir Pat<'hir>,
1249 /// Optional guard clause.
1250 pub guard: Option<Guard<'hir>>,
1251 /// The expression the arm evaluates to if this arm matches.
1252 pub body: &'hir Expr<'hir>,
1255 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1256 pub enum Guard<'hir> {
1257 If(&'hir Expr<'hir>),
1260 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1261 pub struct Field<'hir> {
1262 #[stable_hasher(ignore)]
1265 pub expr: &'hir Expr<'hir>,
1267 pub is_shorthand: bool,
1270 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1271 pub enum BlockCheckMode {
1273 UnsafeBlock(UnsafeSource),
1274 PushUnsafeBlock(UnsafeSource),
1275 PopUnsafeBlock(UnsafeSource),
1278 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1279 pub enum UnsafeSource {
1284 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1289 /// The body of a function, closure, or constant value. In the case of
1290 /// a function, the body contains not only the function body itself
1291 /// (which is an expression), but also the argument patterns, since
1292 /// those are something that the caller doesn't really care about.
1297 /// fn foo((x, y): (u32, u32)) -> u32 {
1302 /// Here, the `Body` associated with `foo()` would contain:
1304 /// - an `params` array containing the `(x, y)` pattern
1305 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1306 /// - `generator_kind` would be `None`
1308 /// All bodies have an **owner**, which can be accessed via the HIR
1309 /// map using `body_owner_def_id()`.
1310 #[derive(RustcEncodable, RustcDecodable, Debug)]
1311 pub struct Body<'hir> {
1312 pub params: &'hir [Param<'hir>],
1313 pub value: Expr<'hir>,
1314 pub generator_kind: Option<GeneratorKind>,
1318 pub fn id(&self) -> BodyId {
1319 BodyId { hir_id: self.value.hir_id }
1322 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1327 /// The type of source expression that caused this generator to be created.
1328 #[derive(Clone, PartialEq, Eq, HashStable, RustcEncodable, RustcDecodable, Debug, Copy)]
1329 pub enum GeneratorKind {
1330 /// An explicit `async` block or the body of an async function.
1331 Async(AsyncGeneratorKind),
1333 /// A generator literal created via a `yield` inside a closure.
1337 impl fmt::Display for GeneratorKind {
1338 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1340 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1341 GeneratorKind::Gen => f.write_str("generator"),
1346 /// In the case of a generator created as part of an async construct,
1347 /// which kind of async construct caused it to be created?
1349 /// This helps error messages but is also used to drive coercions in
1350 /// type-checking (see #60424).
1351 #[derive(Clone, PartialEq, Eq, HashStable, RustcEncodable, RustcDecodable, Debug, Copy)]
1352 pub enum AsyncGeneratorKind {
1353 /// An explicit `async` block written by the user.
1356 /// An explicit `async` block written by the user.
1359 /// The `async` block generated as the body of an async function.
1363 impl fmt::Display for AsyncGeneratorKind {
1364 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1365 f.write_str(match self {
1366 AsyncGeneratorKind::Block => "`async` block",
1367 AsyncGeneratorKind::Closure => "`async` closure body",
1368 AsyncGeneratorKind::Fn => "`async fn` body",
1373 #[derive(Copy, Clone, Debug)]
1374 pub enum BodyOwnerKind {
1375 /// Functions and methods.
1381 /// Constants and associated constants.
1384 /// Initializer of a `static` item.
1388 impl BodyOwnerKind {
1389 pub fn is_fn_or_closure(self) -> bool {
1391 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1392 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1398 pub type Lit = Spanned<LitKind>;
1400 /// A constant (expression) that's not an item or associated item,
1401 /// but needs its own `DefId` for type-checking, const-eval, etc.
1402 /// These are usually found nested inside types (e.g., array lengths)
1403 /// or expressions (e.g., repeat counts), and also used to define
1404 /// explicit discriminant values for enum variants.
1405 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1406 pub struct AnonConst {
1412 #[derive(RustcEncodable, RustcDecodable)]
1413 pub struct Expr<'hir> {
1415 pub kind: ExprKind<'hir>,
1420 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1421 #[cfg(target_arch = "x86_64")]
1422 static_assert_size!(Expr<'static>, 64);
1425 pub fn precedence(&self) -> ExprPrecedence {
1427 ExprKind::Box(_) => ExprPrecedence::Box,
1428 ExprKind::Array(_) => ExprPrecedence::Array,
1429 ExprKind::Call(..) => ExprPrecedence::Call,
1430 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1431 ExprKind::Tup(_) => ExprPrecedence::Tup,
1432 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1433 ExprKind::Unary(..) => ExprPrecedence::Unary,
1434 ExprKind::Lit(_) => ExprPrecedence::Lit,
1435 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1436 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1437 ExprKind::Loop(..) => ExprPrecedence::Loop,
1438 ExprKind::Match(..) => ExprPrecedence::Match,
1439 ExprKind::Closure(..) => ExprPrecedence::Closure,
1440 ExprKind::Block(..) => ExprPrecedence::Block,
1441 ExprKind::Assign(..) => ExprPrecedence::Assign,
1442 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1443 ExprKind::Field(..) => ExprPrecedence::Field,
1444 ExprKind::Index(..) => ExprPrecedence::Index,
1445 ExprKind::Path(..) => ExprPrecedence::Path,
1446 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1447 ExprKind::Break(..) => ExprPrecedence::Break,
1448 ExprKind::Continue(..) => ExprPrecedence::Continue,
1449 ExprKind::Ret(..) => ExprPrecedence::Ret,
1450 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1451 ExprKind::Struct(..) => ExprPrecedence::Struct,
1452 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1453 ExprKind::Yield(..) => ExprPrecedence::Yield,
1454 ExprKind::Err => ExprPrecedence::Err,
1458 // Whether this looks like a place expr, without checking for deref
1460 // This will return `true` in some potentially surprising cases such as
1461 // `CONSTANT.field`.
1462 pub fn is_syntactic_place_expr(&self) -> bool {
1463 self.is_place_expr(|_| true)
1466 // Whether this is a place expression.
1467 // `allow_projections_from` should return `true` if indexing a field or
1468 // index expression based on the given expression should be considered a
1469 // place expression.
1470 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1472 ExprKind::Path(QPath::Resolved(_, ref path)) => match path.res {
1473 Res::Local(..) | Res::Def(DefKind::Static, _) | Res::Err => true,
1477 // Type ascription inherits its place expression kind from its
1479 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1480 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1482 ExprKind::Unary(UnDeref, _) => true,
1484 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1485 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1488 // Partially qualified paths in expressions can only legally
1489 // refer to associated items which are always rvalues.
1490 ExprKind::Path(QPath::TypeRelative(..))
1491 | ExprKind::Call(..)
1492 | ExprKind::MethodCall(..)
1493 | ExprKind::Struct(..)
1495 | ExprKind::Match(..)
1496 | ExprKind::Closure(..)
1497 | ExprKind::Block(..)
1498 | ExprKind::Repeat(..)
1499 | ExprKind::Array(..)
1500 | ExprKind::Break(..)
1501 | ExprKind::Continue(..)
1503 | ExprKind::Loop(..)
1504 | ExprKind::Assign(..)
1505 | ExprKind::InlineAsm(..)
1506 | ExprKind::AssignOp(..)
1508 | ExprKind::Unary(..)
1510 | ExprKind::AddrOf(..)
1511 | ExprKind::Binary(..)
1512 | ExprKind::Yield(..)
1513 | ExprKind::Cast(..)
1514 | ExprKind::DropTemps(..)
1515 | ExprKind::Err => false,
1519 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1520 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1521 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1522 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1523 /// beyond remembering to call this function before doing analysis on it.
1524 pub fn peel_drop_temps(&self) -> &Self {
1525 let mut expr = self;
1526 while let ExprKind::DropTemps(inner) = &expr.kind {
1533 impl fmt::Debug for Expr<'_> {
1534 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1539 print::to_string(print::NO_ANN, |s| s.print_expr(self))
1544 /// Checks if the specified expression is a built-in range literal.
1545 /// (See: `LoweringContext::lower_expr()`).
1547 /// FIXME(#60607): This function is a hack. If and when we have `QPath::Lang(...)`,
1548 /// we can use that instead as simpler, more reliable mechanism, as opposed to using `SourceMap`.
1549 pub fn is_range_literal(sm: &SourceMap, expr: &Expr<'_>) -> bool {
1550 // Returns whether the given path represents a (desugared) range,
1551 // either in std or core, i.e. has either a `::std::ops::Range` or
1552 // `::core::ops::Range` prefix.
1553 fn is_range_path(path: &Path<'_>) -> bool {
1554 let segs: Vec<_> = path.segments.iter().map(|seg| seg.ident.to_string()).collect();
1555 let segs: Vec<_> = segs.iter().map(|seg| &**seg).collect();
1557 // "{{root}}" is the equivalent of `::` prefix in `Path`.
1558 if let ["{{root}}", std_core, "ops", range] = segs.as_slice() {
1559 (*std_core == "std" || *std_core == "core") && range.starts_with("Range")
1565 // Check whether a span corresponding to a range expression is a
1566 // range literal, rather than an explicit struct or `new()` call.
1567 fn is_lit(sm: &SourceMap, span: &Span) -> bool {
1568 let end_point = sm.end_point(*span);
1570 if let Ok(end_string) = sm.span_to_snippet(end_point) {
1571 !(end_string.ends_with("}") || end_string.ends_with(")"))
1578 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1579 ExprKind::Struct(ref qpath, _, _) => {
1580 if let QPath::Resolved(None, ref path) = **qpath {
1581 return is_range_path(&path) && is_lit(sm, &expr.span);
1585 // `..` desugars to its struct path.
1586 ExprKind::Path(QPath::Resolved(None, ref path)) => {
1587 return is_range_path(&path) && is_lit(sm, &expr.span);
1590 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1591 ExprKind::Call(ref func, _) => {
1592 if let ExprKind::Path(QPath::TypeRelative(ref ty, ref segment)) = func.kind {
1593 if let TyKind::Path(QPath::Resolved(None, ref path)) = ty.kind {
1594 let new_call = segment.ident.name == sym::new;
1595 return is_range_path(&path) && is_lit(sm, &expr.span) && new_call;
1606 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1607 pub enum ExprKind<'hir> {
1608 /// A `box x` expression.
1609 Box(&'hir Expr<'hir>),
1610 /// An array (e.g., `[a, b, c, d]`).
1611 Array(&'hir [Expr<'hir>]),
1612 /// A function call.
1614 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1615 /// and the second field is the list of arguments.
1616 /// This also represents calling the constructor of
1617 /// tuple-like ADTs such as tuple structs and enum variants.
1618 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1619 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1621 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1622 /// (within the angle brackets).
1623 /// The first element of the vector of `Expr`s is the expression that evaluates
1624 /// to the object on which the method is being called on (the receiver),
1625 /// and the remaining elements are the rest of the arguments.
1626 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1627 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1629 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1630 /// the `hir_id` of the `MethodCall` node itself.
1632 /// [`type_dependent_def_id`]: ../ty/struct.TypeckTables.html#method.type_dependent_def_id
1633 MethodCall(&'hir PathSegment<'hir>, Span, &'hir [Expr<'hir>]),
1634 /// A tuple (e.g., `(a, b, c, d)`).
1635 Tup(&'hir [Expr<'hir>]),
1636 /// A binary operation (e.g., `a + b`, `a * b`).
1637 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1638 /// A unary operation (e.g., `!x`, `*x`).
1639 Unary(UnOp, &'hir Expr<'hir>),
1640 /// A literal (e.g., `1`, `"foo"`).
1642 /// A cast (e.g., `foo as f64`).
1643 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1644 /// A type reference (e.g., `Foo`).
1645 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1646 /// Wraps the expression in a terminating scope.
1647 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1649 /// This construct only exists to tweak the drop order in HIR lowering.
1650 /// An example of that is the desugaring of `for` loops.
1651 DropTemps(&'hir Expr<'hir>),
1652 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1654 /// I.e., `'label: loop { <block> }`.
1655 Loop(&'hir Block<'hir>, Option<Label>, LoopSource),
1656 /// A `match` block, with a source that indicates whether or not it is
1657 /// the result of a desugaring, and if so, which kind.
1658 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1659 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1661 /// The `Span` is the argument block `|...|`.
1663 /// This may also be a generator literal or an `async block` as indicated by the
1664 /// `Option<Movability>`.
1665 Closure(CaptureBy, &'hir FnDecl<'hir>, BodyId, Span, Option<Movability>),
1666 /// A block (e.g., `'label: { ... }`).
1667 Block(&'hir Block<'hir>, Option<Label>),
1669 /// An assignment (e.g., `a = foo()`).
1670 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1671 /// An assignment with an operator.
1674 AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1675 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1676 Field(&'hir Expr<'hir>, Ident),
1677 /// An indexing operation (`foo[2]`).
1678 Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1680 /// Path to a definition, possibly containing lifetime or type parameters.
1683 /// A referencing operation (i.e., `&a` or `&mut a`).
1684 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1685 /// A `break`, with an optional label to break.
1686 Break(Destination, Option<&'hir Expr<'hir>>),
1687 /// A `continue`, with an optional label.
1688 Continue(Destination),
1689 /// A `return`, with an optional value to be returned.
1690 Ret(Option<&'hir Expr<'hir>>),
1692 /// Inline assembly (from `asm!`), with its outputs and inputs.
1693 InlineAsm(&'hir InlineAsm<'hir>),
1695 /// A struct or struct-like variant literal expression.
1697 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1698 /// where `base` is the `Option<Expr>`.
1699 Struct(&'hir QPath<'hir>, &'hir [Field<'hir>], Option<&'hir Expr<'hir>>),
1701 /// An array literal constructed from one repeated element.
1703 /// E.g., `[1; 5]`. The first expression is the element
1704 /// to be repeated; the second is the number of times to repeat it.
1705 Repeat(&'hir Expr<'hir>, AnonConst),
1707 /// A suspension point for generators (i.e., `yield <expr>`).
1708 Yield(&'hir Expr<'hir>, YieldSource),
1710 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1714 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1716 /// To resolve the path to a `DefId`, call [`qpath_res`].
1718 /// [`qpath_res`]: ../ty/struct.TypeckTables.html#method.qpath_res
1719 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1720 pub enum QPath<'hir> {
1721 /// Path to a definition, optionally "fully-qualified" with a `Self`
1722 /// type, if the path points to an associated item in a trait.
1724 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1725 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1726 /// even though they both have the same two-segment `Clone::clone` `Path`.
1727 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
1729 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1730 /// Will be resolved by type-checking to an associated item.
1732 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1733 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1734 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1735 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
1738 /// Hints at the original code for a let statement.
1739 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1740 pub enum LocalSource {
1741 /// A `match _ { .. }`.
1743 /// A desugared `for _ in _ { .. }` loop.
1745 /// When lowering async functions, we create locals within the `async move` so that
1746 /// all parameters are dropped after the future is polled.
1748 /// ```ignore (pseudo-Rust)
1749 /// async fn foo(<pattern> @ x: Type) {
1751 /// let <pattern> = x;
1756 /// A desugared `<expr>.await`.
1760 /// Hints at the original code for a `match _ { .. }`.
1761 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
1762 pub enum MatchSource {
1763 /// A `match _ { .. }`.
1765 /// An `if _ { .. }` (optionally with `else { .. }`).
1766 IfDesugar { contains_else_clause: bool },
1767 /// An `if let _ = _ { .. }` (optionally with `else { .. }`).
1768 IfLetDesugar { contains_else_clause: bool },
1769 /// A `while _ { .. }` (which was desugared to a `loop { match _ { .. } }`).
1771 /// A `while let _ = _ { .. }` (which was desugared to a
1772 /// `loop { match _ { .. } }`).
1774 /// A desugared `for _ in _ { .. }` loop.
1776 /// A desugared `?` operator.
1778 /// A desugared `<expr>.await`.
1783 pub fn name(self) -> &'static str {
1787 IfDesugar { .. } | IfLetDesugar { .. } => "if",
1788 WhileDesugar | WhileLetDesugar => "while",
1789 ForLoopDesugar => "for",
1791 AwaitDesugar => ".await",
1796 /// The loop type that yielded an `ExprKind::Loop`.
1797 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1798 pub enum LoopSource {
1799 /// A `loop { .. }` loop.
1801 /// A `while _ { .. }` loop.
1803 /// A `while let _ = _ { .. }` loop.
1805 /// A `for _ in _ { .. }` loop.
1810 pub fn name(self) -> &'static str {
1812 LoopSource::Loop => "loop",
1813 LoopSource::While | LoopSource::WhileLet => "while",
1814 LoopSource::ForLoop => "for",
1819 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1820 pub enum LoopIdError {
1822 UnlabeledCfInWhileCondition,
1826 impl fmt::Display for LoopIdError {
1827 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1828 f.write_str(match self {
1829 LoopIdError::OutsideLoopScope => "not inside loop scope",
1830 LoopIdError::UnlabeledCfInWhileCondition => {
1831 "unlabeled control flow (break or continue) in while condition"
1833 LoopIdError::UnresolvedLabel => "label not found",
1838 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1839 pub struct Destination {
1840 // This is `Some(_)` iff there is an explicit user-specified `label
1841 pub label: Option<Label>,
1843 // These errors are caught and then reported during the diagnostics pass in
1844 // librustc_passes/loops.rs
1845 pub target_id: Result<HirId, LoopIdError>,
1848 /// The yield kind that caused an `ExprKind::Yield`.
1849 #[derive(Copy, Clone, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable, HashStable)]
1850 pub enum YieldSource {
1851 /// An `<expr>.await`.
1853 /// A plain `yield`.
1857 impl fmt::Display for YieldSource {
1858 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1859 f.write_str(match self {
1860 YieldSource::Await => "`await`",
1861 YieldSource::Yield => "`yield`",
1866 impl From<GeneratorKind> for YieldSource {
1867 fn from(kind: GeneratorKind) -> Self {
1869 // Guess based on the kind of the current generator.
1870 GeneratorKind::Gen => Self::Yield,
1871 GeneratorKind::Async(_) => Self::Await,
1876 // N.B., if you change this, you'll probably want to change the corresponding
1877 // type structure in middle/ty.rs as well.
1878 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1879 pub struct MutTy<'hir> {
1880 pub ty: &'hir Ty<'hir>,
1881 pub mutbl: Mutability,
1884 /// Represents a function's signature in a trait declaration,
1885 /// trait implementation, or a free function.
1886 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1887 pub struct FnSig<'hir> {
1888 pub header: FnHeader,
1889 pub decl: &'hir FnDecl<'hir>,
1892 // The bodies for items are stored "out of line", in a separate
1893 // hashmap in the `Crate`. Here we just record the node-id of the item
1894 // so it can fetched later.
1895 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1896 pub struct TraitItemId {
1900 /// Represents an item declaration within a trait declaration,
1901 /// possibly including a default implementation. A trait item is
1902 /// either required (meaning it doesn't have an implementation, just a
1903 /// signature) or provided (meaning it has a default implementation).
1904 #[derive(RustcEncodable, RustcDecodable, Debug)]
1905 pub struct TraitItem<'hir> {
1908 pub attrs: &'hir [Attribute],
1909 pub generics: Generics<'hir>,
1910 pub kind: TraitItemKind<'hir>,
1914 /// Represents a trait method's body (or just argument names).
1915 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1916 pub enum TraitMethod<'hir> {
1917 /// No default body in the trait, just a signature.
1918 Required(&'hir [Ident]),
1920 /// Both signature and body are provided in the trait.
1924 /// Represents a trait method or associated constant or type
1925 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1926 pub enum TraitItemKind<'hir> {
1927 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
1928 Const(&'hir Ty<'hir>, Option<BodyId>),
1929 /// A method with an optional body.
1930 Method(FnSig<'hir>, TraitMethod<'hir>),
1931 /// An associated type with (possibly empty) bounds and optional concrete
1933 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
1936 // The bodies for items are stored "out of line", in a separate
1937 // hashmap in the `Crate`. Here we just record the node-id of the item
1938 // so it can fetched later.
1939 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1940 pub struct ImplItemId {
1944 /// Represents anything within an `impl` block.
1945 #[derive(RustcEncodable, RustcDecodable, Debug)]
1946 pub struct ImplItem<'hir> {
1949 pub vis: Visibility<'hir>,
1950 pub defaultness: Defaultness,
1951 pub attrs: &'hir [Attribute],
1952 pub generics: Generics<'hir>,
1953 pub kind: ImplItemKind<'hir>,
1957 /// Represents various kinds of content within an `impl`.
1958 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1959 pub enum ImplItemKind<'hir> {
1960 /// An associated constant of the given type, set to the constant result
1961 /// of the expression.
1962 Const(&'hir Ty<'hir>, BodyId),
1963 /// A method implementation with the given signature and body.
1964 Method(FnSig<'hir>, BodyId),
1965 /// An associated type.
1966 TyAlias(&'hir Ty<'hir>),
1967 /// An associated `type = impl Trait`.
1968 OpaqueTy(GenericBounds<'hir>),
1971 /// Bind a type to an associated type (i.e., `A = Foo`).
1973 /// Bindings like `A: Debug` are represented as a special type `A =
1974 /// $::Debug` that is understood by the astconv code.
1976 /// FIXME(alexreg): why have a separate type for the binding case,
1977 /// wouldn't it be better to make the `ty` field an enum like the
1981 /// enum TypeBindingKind {
1986 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1987 pub struct TypeBinding<'hir> {
1989 #[stable_hasher(project(name))]
1991 pub kind: TypeBindingKind<'hir>,
1995 // Represents the two kinds of type bindings.
1996 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1997 pub enum TypeBindingKind<'hir> {
1998 /// E.g., `Foo<Bar: Send>`.
1999 Constraint { bounds: &'hir [GenericBound<'hir>] },
2000 /// E.g., `Foo<Bar = ()>`.
2001 Equality { ty: &'hir Ty<'hir> },
2004 impl TypeBinding<'_> {
2005 pub fn ty(&self) -> &Ty<'_> {
2007 TypeBindingKind::Equality { ref ty } => ty,
2008 _ => bug!("expected equality type binding for parenthesized generic args"),
2013 #[derive(RustcEncodable, RustcDecodable)]
2014 pub struct Ty<'hir> {
2016 pub kind: TyKind<'hir>,
2020 impl fmt::Debug for Ty<'_> {
2021 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2022 write!(f, "type({})", print::to_string(print::NO_ANN, |s| s.print_type(self)))
2026 /// Not represented directly in the AST; referred to by name through a `ty_path`.
2027 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
2037 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2038 pub struct BareFnTy<'hir> {
2039 pub unsafety: Unsafety,
2041 pub generic_params: &'hir [GenericParam<'hir>],
2042 pub decl: &'hir FnDecl<'hir>,
2043 pub param_names: &'hir [Ident],
2046 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2047 pub struct OpaqueTy<'hir> {
2048 pub generics: Generics<'hir>,
2049 pub bounds: GenericBounds<'hir>,
2050 pub impl_trait_fn: Option<DefId>,
2051 pub origin: OpaqueTyOrigin,
2054 /// From whence the opaque type came.
2055 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2056 pub enum OpaqueTyOrigin {
2057 /// `type Foo = impl Trait;`
2065 /// The various kinds of types recognized by the compiler.
2066 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2067 pub enum TyKind<'hir> {
2068 /// A variable length slice (i.e., `[T]`).
2069 Slice(&'hir Ty<'hir>),
2070 /// A fixed length array (i.e., `[T; n]`).
2071 Array(&'hir Ty<'hir>, AnonConst),
2072 /// A raw pointer (i.e., `*const T` or `*mut T`).
2074 /// A reference (i.e., `&'a T` or `&'a mut T`).
2075 Rptr(Lifetime, MutTy<'hir>),
2076 /// A bare function (e.g., `fn(usize) -> bool`).
2077 BareFn(&'hir BareFnTy<'hir>),
2078 /// The never type (`!`).
2080 /// A tuple (`(A, B, C, D, ...)`).
2081 Tup(&'hir [Ty<'hir>]),
2082 /// A path to a type definition (`module::module::...::Type`), or an
2083 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2085 /// Type parameters may be stored in each `PathSegment`.
2087 /// A type definition itself. This is currently only used for the `type Foo = impl Trait`
2088 /// item that `impl Trait` in return position desugars to.
2090 /// The generic argument list contains the lifetimes (and in the future possibly parameters)
2091 /// that are actually bound on the `impl Trait`.
2092 Def(ItemId, &'hir [GenericArg<'hir>]),
2093 /// A trait object type `Bound1 + Bound2 + Bound3`
2094 /// where `Bound` is a trait or a lifetime.
2095 TraitObject(&'hir [PolyTraitRef<'hir>], Lifetime),
2098 /// `TyKind::Infer` means the type should be inferred instead of it having been
2099 /// specified. This can appear anywhere in a type.
2101 /// Placeholder for a type that has failed to be defined.
2105 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable, PartialEq)]
2106 pub struct InlineAsmOutput {
2107 pub constraint: Symbol,
2109 pub is_indirect: bool,
2113 // NOTE(eddyb) This is used within MIR as well, so unlike the rest of the HIR,
2114 // it needs to be `Clone` and use plain `Vec<T>` instead of arena-allocated slice.
2115 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable, PartialEq)]
2116 pub struct InlineAsmInner {
2118 pub asm_str_style: StrStyle,
2119 pub outputs: Vec<InlineAsmOutput>,
2120 pub inputs: Vec<Symbol>,
2121 pub clobbers: Vec<Symbol>,
2123 pub alignstack: bool,
2124 pub dialect: AsmDialect,
2127 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2128 pub struct InlineAsm<'hir> {
2129 pub inner: InlineAsmInner,
2130 pub outputs_exprs: &'hir [Expr<'hir>],
2131 pub inputs_exprs: &'hir [Expr<'hir>],
2134 /// Represents a parameter in a function header.
2135 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2136 pub struct Param<'hir> {
2137 pub attrs: &'hir [Attribute],
2139 pub pat: &'hir Pat<'hir>,
2143 /// Represents the header (not the body) of a function declaration.
2144 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2145 pub struct FnDecl<'hir> {
2146 /// The types of the function's parameters.
2148 /// Additional argument data is stored in the function's [body](Body::parameters).
2149 pub inputs: &'hir [Ty<'hir>],
2150 pub output: FunctionRetTy<'hir>,
2151 pub c_variadic: bool,
2152 /// Does the function have an implicit self?
2153 pub implicit_self: ImplicitSelfKind,
2156 /// Represents what type of implicit self a function has, if any.
2157 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2158 pub enum ImplicitSelfKind {
2159 /// Represents a `fn x(self);`.
2161 /// Represents a `fn x(mut self);`.
2163 /// Represents a `fn x(&self);`.
2165 /// Represents a `fn x(&mut self);`.
2167 /// Represents when a function does not have a self argument or
2168 /// when a function has a `self: X` argument.
2172 impl ImplicitSelfKind {
2173 /// Does this represent an implicit self?
2174 pub fn has_implicit_self(&self) -> bool {
2176 ImplicitSelfKind::None => false,
2199 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2200 pub enum Defaultness {
2201 Default { has_value: bool },
2206 pub fn has_value(&self) -> bool {
2208 Defaultness::Default { has_value, .. } => has_value,
2209 Defaultness::Final => true,
2213 pub fn is_final(&self) -> bool {
2214 *self == Defaultness::Final
2217 pub fn is_default(&self) -> bool {
2219 Defaultness::Default { .. } => true,
2225 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2226 pub enum FunctionRetTy<'hir> {
2227 /// Return type is not specified.
2229 /// Functions default to `()` and
2230 /// closures default to inference. Span points to where return
2231 /// type would be inserted.
2232 DefaultReturn(Span),
2233 /// Everything else.
2234 Return(&'hir Ty<'hir>),
2237 impl fmt::Display for FunctionRetTy<'_> {
2238 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2240 Return(ref ty) => print::to_string(print::NO_ANN, |s| s.print_type(ty)).fmt(f),
2241 DefaultReturn(_) => "()".fmt(f),
2246 impl FunctionRetTy<'_> {
2247 pub fn span(&self) -> Span {
2249 DefaultReturn(span) => span,
2250 Return(ref ty) => ty.span,
2255 #[derive(RustcEncodable, RustcDecodable, Debug)]
2256 pub struct Mod<'hir> {
2257 /// A span from the first token past `{` to the last token until `}`.
2258 /// For `mod foo;`, the inner span ranges from the first token
2259 /// to the last token in the external file.
2261 pub item_ids: &'hir [ItemId],
2264 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2265 pub struct ForeignMod<'hir> {
2267 pub items: &'hir [ForeignItem<'hir>],
2270 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2271 pub struct GlobalAsm {
2275 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2276 pub struct EnumDef<'hir> {
2277 pub variants: &'hir [Variant<'hir>],
2280 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2281 pub struct Variant<'hir> {
2282 /// Name of the variant.
2283 #[stable_hasher(project(name))]
2285 /// Attributes of the variant.
2286 pub attrs: &'hir [Attribute],
2287 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2289 /// Fields and constructor id of the variant.
2290 pub data: VariantData<'hir>,
2291 /// Explicit discriminant (e.g., `Foo = 1`).
2292 pub disr_expr: Option<AnonConst>,
2297 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2299 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2300 /// Also produced for each element of a list `use`, e.g.
2301 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2304 /// Glob import, e.g., `use foo::*`.
2307 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2308 /// an additional `use foo::{}` for performing checks such as
2309 /// unstable feature gating. May be removed in the future.
2313 /// References to traits in impls.
2315 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2316 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2317 /// trait being referred to but just a unique `HirId` that serves as a key
2318 /// within the resolution map.
2319 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2320 pub struct TraitRef<'hir> {
2321 pub path: &'hir Path<'hir>,
2322 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2323 #[stable_hasher(ignore)]
2324 pub hir_ref_id: HirId,
2328 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2329 pub fn trait_def_id(&self) -> DefId {
2330 match self.path.res {
2331 Res::Def(DefKind::Trait, did) => did,
2332 Res::Def(DefKind::TraitAlias, did) => did,
2336 _ => unreachable!(),
2341 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2342 pub struct PolyTraitRef<'hir> {
2343 /// The `'a` in `<'a> Foo<&'a T>`.
2344 pub bound_generic_params: &'hir [GenericParam<'hir>],
2346 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2347 pub trait_ref: TraitRef<'hir>,
2352 pub type Visibility<'hir> = Spanned<VisibilityKind<'hir>>;
2354 #[derive(RustcEncodable, RustcDecodable, Debug)]
2355 pub enum VisibilityKind<'hir> {
2358 Restricted { path: &'hir Path<'hir>, hir_id: HirId },
2362 impl VisibilityKind<'_> {
2363 pub fn is_pub(&self) -> bool {
2365 VisibilityKind::Public => true,
2370 pub fn is_pub_restricted(&self) -> bool {
2372 VisibilityKind::Public | VisibilityKind::Inherited => false,
2373 VisibilityKind::Crate(..) | VisibilityKind::Restricted { .. } => true,
2377 pub fn descr(&self) -> &'static str {
2379 VisibilityKind::Public => "public",
2380 VisibilityKind::Inherited => "private",
2381 VisibilityKind::Crate(..) => "crate-visible",
2382 VisibilityKind::Restricted { .. } => "restricted",
2387 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2388 pub struct StructField<'hir> {
2390 #[stable_hasher(project(name))]
2392 pub vis: Visibility<'hir>,
2394 pub ty: &'hir Ty<'hir>,
2395 pub attrs: &'hir [Attribute],
2398 impl StructField<'_> {
2399 // Still necessary in couple of places
2400 pub fn is_positional(&self) -> bool {
2401 let first = self.ident.as_str().as_bytes()[0];
2402 first >= b'0' && first <= b'9'
2406 /// Fields and constructor IDs of enum variants and structs.
2407 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2408 pub enum VariantData<'hir> {
2409 /// A struct variant.
2411 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2412 Struct(&'hir [StructField<'hir>], /* recovered */ bool),
2413 /// A tuple variant.
2415 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2416 Tuple(&'hir [StructField<'hir>], HirId),
2419 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2423 impl VariantData<'hir> {
2424 /// Return the fields of this variant.
2425 pub fn fields(&self) -> &'hir [StructField<'hir>] {
2427 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2432 /// Return the `HirId` of this variant's constructor, if it has one.
2433 pub fn ctor_hir_id(&self) -> Option<HirId> {
2435 VariantData::Struct(_, _) => None,
2436 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2441 // The bodies for items are stored "out of line", in a separate
2442 // hashmap in the `Crate`. Here we just record the node-id of the item
2443 // so it can fetched later.
2444 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2451 /// The name might be a dummy name in case of anonymous items
2452 #[derive(RustcEncodable, RustcDecodable, Debug)]
2453 pub struct Item<'hir> {
2456 pub attrs: &'hir [Attribute],
2457 pub kind: ItemKind<'hir>,
2458 pub vis: Visibility<'hir>,
2462 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2463 pub struct FnHeader {
2464 pub unsafety: Unsafety,
2465 pub constness: Constness,
2466 pub asyncness: IsAsync,
2471 pub fn is_const(&self) -> bool {
2472 match &self.constness {
2473 Constness::Const => true,
2479 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2480 pub enum ItemKind<'hir> {
2481 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2483 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2484 ExternCrate(Option<Name>),
2486 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2490 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2491 Use(&'hir Path<'hir>, UseKind),
2493 /// A `static` item.
2494 Static(&'hir Ty<'hir>, Mutability, BodyId),
2496 Const(&'hir Ty<'hir>, BodyId),
2497 /// A function declaration.
2498 Fn(FnSig<'hir>, Generics<'hir>, BodyId),
2501 /// An external module, e.g. `extern { .. }`.
2502 ForeignMod(ForeignMod<'hir>),
2503 /// Module-level inline assembly (from `global_asm!`).
2504 GlobalAsm(&'hir GlobalAsm),
2505 /// A type alias, e.g., `type Foo = Bar<u8>`.
2506 TyAlias(&'hir Ty<'hir>, Generics<'hir>),
2507 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2508 OpaqueTy(OpaqueTy<'hir>),
2509 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2510 Enum(EnumDef<'hir>, Generics<'hir>),
2511 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2512 Struct(VariantData<'hir>, Generics<'hir>),
2513 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2514 Union(VariantData<'hir>, Generics<'hir>),
2515 /// A trait definition.
2516 Trait(IsAuto, Unsafety, Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
2518 TraitAlias(Generics<'hir>, GenericBounds<'hir>),
2520 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2526 Option<TraitRef<'hir>>, // (optional) trait this impl implements
2527 &'hir Ty<'hir>, // self
2528 &'hir [ImplItemRef<'hir>],
2533 pub fn descriptive_variant(&self) -> &str {
2535 ItemKind::ExternCrate(..) => "extern crate",
2536 ItemKind::Use(..) => "use",
2537 ItemKind::Static(..) => "static item",
2538 ItemKind::Const(..) => "constant item",
2539 ItemKind::Fn(..) => "function",
2540 ItemKind::Mod(..) => "module",
2541 ItemKind::ForeignMod(..) => "foreign module",
2542 ItemKind::GlobalAsm(..) => "global asm",
2543 ItemKind::TyAlias(..) => "type alias",
2544 ItemKind::OpaqueTy(..) => "opaque type",
2545 ItemKind::Enum(..) => "enum",
2546 ItemKind::Struct(..) => "struct",
2547 ItemKind::Union(..) => "union",
2548 ItemKind::Trait(..) => "trait",
2549 ItemKind::TraitAlias(..) => "trait alias",
2550 ItemKind::Impl(..) => "impl",
2554 pub fn generics(&self) -> Option<&Generics<'_>> {
2556 ItemKind::Fn(_, ref generics, _)
2557 | ItemKind::TyAlias(_, ref generics)
2558 | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
2559 | ItemKind::Enum(_, ref generics)
2560 | ItemKind::Struct(_, ref generics)
2561 | ItemKind::Union(_, ref generics)
2562 | ItemKind::Trait(_, _, ref generics, _, _)
2563 | ItemKind::Impl(_, _, _, ref generics, _, _, _) => generics,
2569 /// A reference from an trait to one of its associated items. This
2570 /// contains the item's id, naturally, but also the item's name and
2571 /// some other high-level details (like whether it is an associated
2572 /// type or method, and whether it is public). This allows other
2573 /// passes to find the impl they want without loading the ID (which
2574 /// means fewer edges in the incremental compilation graph).
2575 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2576 pub struct TraitItemRef {
2577 pub id: TraitItemId,
2578 #[stable_hasher(project(name))]
2580 pub kind: AssocItemKind,
2582 pub defaultness: Defaultness,
2585 /// A reference from an impl to one of its associated items. This
2586 /// contains the item's ID, naturally, but also the item's name and
2587 /// some other high-level details (like whether it is an associated
2588 /// type or method, and whether it is public). This allows other
2589 /// passes to find the impl they want without loading the ID (which
2590 /// means fewer edges in the incremental compilation graph).
2591 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2592 pub struct ImplItemRef<'hir> {
2594 #[stable_hasher(project(name))]
2596 pub kind: AssocItemKind,
2598 pub vis: Visibility<'hir>,
2599 pub defaultness: Defaultness,
2602 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2603 pub enum AssocItemKind {
2605 Method { has_self: bool },
2610 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2611 pub struct ForeignItem<'hir> {
2612 #[stable_hasher(project(name))]
2614 pub attrs: &'hir [Attribute],
2615 pub kind: ForeignItemKind<'hir>,
2618 pub vis: Visibility<'hir>,
2621 /// An item within an `extern` block.
2622 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2623 pub enum ForeignItemKind<'hir> {
2624 /// A foreign function.
2625 Fn(&'hir FnDecl<'hir>, &'hir [Ident], Generics<'hir>),
2626 /// A foreign static item (`static ext: u8`).
2627 Static(&'hir Ty<'hir>, Mutability),
2632 impl ForeignItemKind<'hir> {
2633 pub fn descriptive_variant(&self) -> &str {
2635 ForeignItemKind::Fn(..) => "foreign function",
2636 ForeignItemKind::Static(..) => "foreign static item",
2637 ForeignItemKind::Type => "foreign type",
2642 /// A variable captured by a closure.
2643 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable, HashStable)]
2645 // First span where it is accessed (there can be multiple).
2649 pub type CaptureModeMap = NodeMap<CaptureBy>;
2651 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2652 // has length > 0 if the trait is found through an chain of imports, starting with the
2653 // import/use statement in the scope where the trait is used.
2654 #[derive(Clone, Debug)]
2655 pub struct TraitCandidate {
2657 pub import_ids: SmallVec<[NodeId; 1]>,
2660 // Trait method resolution
2661 pub type TraitMap = NodeMap<Vec<TraitCandidate>>;
2663 // Map from the NodeId of a glob import to a list of items which are actually
2665 pub type GlobMap = NodeMap<FxHashSet<Name>>;
2667 pub fn provide(providers: &mut Providers<'_>) {
2668 check_attr::provide(providers);
2669 map::provide(providers);
2670 upvars::provide(providers);
2673 #[derive(Copy, Clone, Debug)]
2674 pub enum Node<'hir> {
2675 Param(&'hir Param<'hir>),
2676 Item(&'hir Item<'hir>),
2677 ForeignItem(&'hir ForeignItem<'hir>),
2678 TraitItem(&'hir TraitItem<'hir>),
2679 ImplItem(&'hir ImplItem<'hir>),
2680 Variant(&'hir Variant<'hir>),
2681 Field(&'hir StructField<'hir>),
2682 AnonConst(&'hir AnonConst),
2683 Expr(&'hir Expr<'hir>),
2684 Stmt(&'hir Stmt<'hir>),
2685 PathSegment(&'hir PathSegment<'hir>),
2687 TraitRef(&'hir TraitRef<'hir>),
2688 Binding(&'hir Pat<'hir>),
2689 Pat(&'hir Pat<'hir>),
2690 Arm(&'hir Arm<'hir>),
2691 Block(&'hir Block<'hir>),
2692 Local(&'hir Local<'hir>),
2693 MacroDef(&'hir MacroDef<'hir>),
2695 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
2696 /// with synthesized constructors.
2697 Ctor(&'hir VariantData<'hir>),
2699 Lifetime(&'hir Lifetime),
2700 GenericParam(&'hir GenericParam<'hir>),
2701 Visibility(&'hir Visibility<'hir>),
2707 pub fn ident(&self) -> Option<Ident> {
2709 Node::TraitItem(TraitItem { ident, .. })
2710 | Node::ImplItem(ImplItem { ident, .. })
2711 | Node::ForeignItem(ForeignItem { ident, .. })
2712 | Node::Item(Item { ident, .. }) => Some(*ident),