1 //! HIR datatypes. See the [rustc guide] for more info.
3 //! [rustc guide]: https://rust-lang.github.io/rustc-guide/hir.html
5 pub use self::BlockCheckMode::*;
6 pub use self::FunctionRetTy::*;
7 pub use self::PrimTy::*;
9 pub use self::UnsafeSource::*;
11 use crate::hir::def::{DefKind, Res};
12 use crate::hir::def_id::{DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX};
13 use crate::mir::mono::Linkage;
14 use crate::ty::query::Providers;
15 use crate::ty::AdtKind;
16 use crate::util::nodemap::{FxHashSet, NodeMap};
18 use errors::FatalError;
19 use rustc_data_structures::sync::{par_for_each_in, Send, Sync};
20 use rustc_macros::HashStable;
21 use rustc_serialize::{self, Decodable, Decoder, Encodable, Encoder};
22 use rustc_span::source_map::{SourceMap, Spanned};
23 use rustc_span::symbol::{kw, sym, Symbol};
24 use rustc_span::{MultiSpan, Span, DUMMY_SP};
25 use rustc_target::spec::abi::Abi;
26 use smallvec::SmallVec;
27 use std::collections::{BTreeMap, BTreeSet};
29 use syntax::ast::{self, AsmDialect, CrateSugar, Ident, Name, NodeId};
30 use syntax::ast::{AttrVec, Attribute, FloatTy, IntTy, Label, LitKind, StrStyle, UintTy};
31 pub use syntax::ast::{BorrowKind, ImplPolarity, IsAuto};
32 pub use syntax::ast::{CaptureBy, Constness, Movability, Mutability, Unsafety};
33 use syntax::attr::{InlineAttr, OptimizeAttr};
34 use syntax::tokenstream::TokenStream;
35 use syntax::util::parser::ExprPrecedence;
41 pub mod itemlikevisit;
47 /// Uniquely identifies a node in the HIR of the current crate. It is
48 /// composed of the `owner`, which is the `DefIndex` of the directly enclosing
49 /// `hir::Item`, `hir::TraitItem`, or `hir::ImplItem` (i.e., the closest "item-like"),
50 /// and the `local_id` which is unique within the given owner.
52 /// This two-level structure makes for more stable values: One can move an item
53 /// around within the source code, or add or remove stuff before it, without
54 /// the `local_id` part of the `HirId` changing, which is a very useful property in
55 /// incremental compilation where we have to persist things through changes to
57 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)]
60 pub local_id: ItemLocalId,
64 pub fn owner_def_id(self) -> DefId {
65 DefId::local(self.owner)
68 pub fn owner_local_def_id(self) -> LocalDefId {
69 LocalDefId::from_def_id(DefId::local(self.owner))
73 impl rustc_serialize::UseSpecializedEncodable for HirId {
74 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
75 let HirId { owner, local_id } = *self;
83 impl rustc_serialize::UseSpecializedDecodable for HirId {
84 fn default_decode<D: Decoder>(d: &mut D) -> Result<HirId, D::Error> {
85 let owner = DefIndex::decode(d)?;
86 let local_id = ItemLocalId::decode(d)?;
88 Ok(HirId { owner, local_id })
92 impl fmt::Display for HirId {
93 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94 write!(f, "{:?}", self)
98 // Hack to ensure that we don't try to access the private parts of `ItemLocalId` in this module.
99 mod item_local_id_inner {
100 use rustc_index::vec::Idx;
101 use rustc_macros::HashStable;
102 rustc_index::newtype_index! {
103 /// An `ItemLocalId` uniquely identifies something within a given "item-like";
104 /// that is, within a `hir::Item`, `hir::TraitItem`, or `hir::ImplItem`. There is no
105 /// guarantee that the numerical value of a given `ItemLocalId` corresponds to
106 /// the node's position within the owning item in any way, but there is a
107 /// guarantee that the `LocalItemId`s within an owner occupy a dense range of
108 /// integers starting at zero, so a mapping that maps all or most nodes within
109 /// an "item-like" to something else can be implemented by a `Vec` instead of a
110 /// tree or hash map.
111 pub struct ItemLocalId {
117 pub use self::item_local_id_inner::ItemLocalId;
119 /// The `HirId` corresponding to `CRATE_NODE_ID` and `CRATE_DEF_INDEX`.
120 pub const CRATE_HIR_ID: HirId =
121 HirId { owner: CRATE_DEF_INDEX, local_id: ItemLocalId::from_u32_const(0) };
123 pub const DUMMY_HIR_ID: HirId = HirId { owner: CRATE_DEF_INDEX, local_id: DUMMY_ITEM_LOCAL_ID };
125 pub const DUMMY_ITEM_LOCAL_ID: ItemLocalId = ItemLocalId::MAX;
127 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, HashStable)]
128 pub struct Lifetime {
132 /// Either "`'a`", referring to a named lifetime definition,
133 /// or "``" (i.e., `kw::Invalid`), for elision placeholders.
135 /// HIR lowering inserts these placeholders in type paths that
136 /// refer to type definitions needing lifetime parameters,
137 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
138 pub name: LifetimeName,
141 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy, HashStable)]
143 /// Some user-given name like `T` or `'x`.
146 /// Synthetic name generated when user elided a lifetime in an impl header.
148 /// E.g., the lifetimes in cases like these:
150 /// impl Foo for &u32
151 /// impl Foo<'_> for u32
153 /// in that case, we rewrite to
155 /// impl<'f> Foo for &'f u32
156 /// impl<'f> Foo<'f> for u32
158 /// where `'f` is something like `Fresh(0)`. The indices are
159 /// unique per impl, but not necessarily continuous.
162 /// Indicates an illegal name was given and an error has been
163 /// reported (so we should squelch other derived errors). Occurs
164 /// when, e.g., `'_` is used in the wrong place.
169 pub fn ident(&self) -> Ident {
171 ParamName::Plain(ident) => ident,
172 ParamName::Fresh(_) | ParamName::Error => {
173 Ident::with_dummy_span(kw::UnderscoreLifetime)
178 pub fn modern(&self) -> ParamName {
180 ParamName::Plain(ident) => ParamName::Plain(ident.modern()),
181 param_name => param_name,
186 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy, HashStable)]
187 pub enum LifetimeName {
188 /// User-given names or fresh (synthetic) names.
191 /// User wrote nothing (e.g., the lifetime in `&u32`).
194 /// Implicit lifetime in a context like `dyn Foo`. This is
195 /// distinguished from implicit lifetimes elsewhere because the
196 /// lifetime that they default to must appear elsewhere within the
197 /// enclosing type. This means that, in an `impl Trait` context, we
198 /// don't have to create a parameter for them. That is, `impl
199 /// Trait<Item = &u32>` expands to an opaque type like `type
200 /// Foo<'a> = impl Trait<Item = &'a u32>`, but `impl Trait<item =
201 /// dyn Bar>` expands to `type Foo = impl Trait<Item = dyn Bar +
202 /// 'static>`. The latter uses `ImplicitObjectLifetimeDefault` so
203 /// that surrounding code knows not to create a lifetime
205 ImplicitObjectLifetimeDefault,
207 /// Indicates an error during lowering (usually `'_` in wrong place)
208 /// that was already reported.
211 /// User wrote specifies `'_`.
214 /// User wrote `'static`.
219 pub fn ident(&self) -> Ident {
221 LifetimeName::ImplicitObjectLifetimeDefault
222 | LifetimeName::Implicit
223 | LifetimeName::Error => Ident::invalid(),
224 LifetimeName::Underscore => Ident::with_dummy_span(kw::UnderscoreLifetime),
225 LifetimeName::Static => Ident::with_dummy_span(kw::StaticLifetime),
226 LifetimeName::Param(param_name) => param_name.ident(),
230 pub fn is_elided(&self) -> bool {
232 LifetimeName::ImplicitObjectLifetimeDefault
233 | LifetimeName::Implicit
234 | LifetimeName::Underscore => true,
236 // It might seem surprising that `Fresh(_)` counts as
237 // *not* elided -- but this is because, as far as the code
238 // in the compiler is concerned -- `Fresh(_)` variants act
239 // equivalently to "some fresh name". They correspond to
240 // early-bound regions on an impl, in other words.
241 LifetimeName::Error | LifetimeName::Param(_) | LifetimeName::Static => false,
245 fn is_static(&self) -> bool {
246 self == &LifetimeName::Static
249 pub fn modern(&self) -> LifetimeName {
251 LifetimeName::Param(param_name) => LifetimeName::Param(param_name.modern()),
252 lifetime_name => lifetime_name,
257 impl fmt::Display for Lifetime {
258 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
259 self.name.ident().fmt(f)
263 impl fmt::Debug for Lifetime {
264 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
269 print::to_string(print::NO_ANN, |s| s.print_lifetime(self))
275 pub fn is_elided(&self) -> bool {
276 self.name.is_elided()
279 pub fn is_static(&self) -> bool {
280 self.name.is_static()
284 /// A `Path` is essentially Rust's notion of a name; for instance,
285 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
286 /// along with a bunch of supporting information.
287 #[derive(RustcEncodable, RustcDecodable, HashStable)]
288 pub struct Path<'hir> {
290 /// The resolution for the path.
292 /// The segments in the path: the things separated by `::`.
293 pub segments: &'hir [PathSegment<'hir>],
297 pub fn is_global(&self) -> bool {
298 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
302 impl fmt::Debug for Path<'_> {
303 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
304 write!(f, "path({})", self)
308 impl fmt::Display for Path<'_> {
309 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
310 write!(f, "{}", print::to_string(print::NO_ANN, |s| s.print_path(self, false)))
314 /// A segment of a path: an identifier, an optional lifetime, and a set of
316 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
317 pub struct PathSegment<'hir> {
318 /// The identifier portion of this path segment.
319 #[stable_hasher(project(name))]
321 // `id` and `res` are optional. We currently only use these in save-analysis,
322 // any path segments without these will not have save-analysis info and
323 // therefore will not have 'jump to def' in IDEs, but otherwise will not be
324 // affected. (In general, we don't bother to get the defs for synthesized
325 // segments, only for segments which have come from the AST).
326 pub hir_id: Option<HirId>,
327 pub res: Option<Res>,
329 /// Type/lifetime parameters attached to this path. They come in
330 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
331 /// this is more than just simple syntactic sugar; the use of
332 /// parens affects the region binding rules, so we preserve the
334 pub args: Option<&'hir GenericArgs<'hir>>,
336 /// Whether to infer remaining type parameters, if any.
337 /// This only applies to expression and pattern paths, and
338 /// out of those only the segments with no type parameters
339 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
340 pub infer_args: bool,
343 impl<'hir> PathSegment<'hir> {
344 /// Converts an identifier to the corresponding segment.
345 pub fn from_ident(ident: Ident) -> PathSegment<'hir> {
346 PathSegment { ident, hir_id: None, res: None, infer_args: true, args: None }
349 pub fn generic_args(&self) -> &GenericArgs<'hir> {
350 if let Some(ref args) = self.args {
353 const DUMMY: &GenericArgs<'_> = &GenericArgs::none();
359 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
360 pub struct ConstArg {
361 pub value: AnonConst,
365 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
366 pub enum GenericArg<'hir> {
372 impl GenericArg<'_> {
373 pub fn span(&self) -> Span {
375 GenericArg::Lifetime(l) => l.span,
376 GenericArg::Type(t) => t.span,
377 GenericArg::Const(c) => c.span,
381 pub fn id(&self) -> HirId {
383 GenericArg::Lifetime(l) => l.hir_id,
384 GenericArg::Type(t) => t.hir_id,
385 GenericArg::Const(c) => c.value.hir_id,
389 pub fn is_const(&self) -> bool {
391 GenericArg::Const(_) => true,
397 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
398 pub struct GenericArgs<'hir> {
399 /// The generic arguments for this path segment.
400 pub args: &'hir [GenericArg<'hir>],
401 /// Bindings (equality constraints) on associated types, if present.
402 /// E.g., `Foo<A = Bar>`.
403 pub bindings: &'hir [TypeBinding<'hir>],
404 /// Were arguments written in parenthesized form `Fn(T) -> U`?
405 /// This is required mostly for pretty-printing and diagnostics,
406 /// but also for changing lifetime elision rules to be "function-like".
407 pub parenthesized: bool,
410 impl GenericArgs<'_> {
411 pub const fn none() -> Self {
412 Self { args: &[], bindings: &[], parenthesized: false }
415 pub fn is_empty(&self) -> bool {
416 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
419 pub fn inputs(&self) -> &[Ty<'_>] {
420 if self.parenthesized {
421 for arg in self.args {
423 GenericArg::Lifetime(_) => {}
424 GenericArg::Type(ref ty) => {
425 if let TyKind::Tup(ref tys) = ty.kind {
430 GenericArg::Const(_) => {}
434 bug!("GenericArgs::inputs: not a `Fn(T) -> U`");
437 pub fn own_counts(&self) -> GenericParamCount {
438 // We could cache this as a property of `GenericParamCount`, but
439 // the aim is to refactor this away entirely eventually and the
440 // presence of this method will be a constant reminder.
441 let mut own_counts: GenericParamCount = Default::default();
443 for arg in self.args {
445 GenericArg::Lifetime(_) => own_counts.lifetimes += 1,
446 GenericArg::Type(_) => own_counts.types += 1,
447 GenericArg::Const(_) => own_counts.consts += 1,
455 /// A modifier on a bound, currently this is only used for `?Sized`, where the
456 /// modifier is `Maybe`. Negative bounds should also be handled here.
457 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
458 pub enum TraitBoundModifier {
463 /// The AST represents all type param bounds as types.
464 /// `typeck::collect::compute_bounds` matches these against
465 /// the "special" built-in traits (see `middle::lang_items`) and
466 /// detects `Copy`, `Send` and `Sync`.
467 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
468 pub enum GenericBound<'hir> {
469 Trait(PolyTraitRef<'hir>, TraitBoundModifier),
473 impl GenericBound<'_> {
474 pub fn span(&self) -> Span {
476 &GenericBound::Trait(ref t, ..) => t.span,
477 &GenericBound::Outlives(ref l) => l.span,
482 pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
484 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable)]
485 pub enum LifetimeParamKind {
486 // Indicates that the lifetime definition was explicitly declared (e.g., in
487 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
490 // Indicates that the lifetime definition was synthetically added
491 // as a result of an in-band lifetime usage (e.g., in
492 // `fn foo(x: &'a u8) -> &'a u8 { x }`).
495 // Indication that the lifetime was elided (e.g., in both cases in
496 // `fn foo(x: &u8) -> &'_ u8 { x }`).
499 // Indication that the lifetime name was somehow in error.
503 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
504 pub enum GenericParamKind<'hir> {
505 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
507 kind: LifetimeParamKind,
510 default: Option<&'hir Ty<'hir>>,
511 synthetic: Option<SyntheticTyParamKind>,
518 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
519 pub struct GenericParam<'hir> {
522 pub attrs: &'hir [Attribute],
523 pub bounds: GenericBounds<'hir>,
525 pub pure_wrt_drop: bool,
526 pub kind: GenericParamKind<'hir>,
530 pub struct GenericParamCount {
531 pub lifetimes: usize,
536 /// Represents lifetimes and type parameters attached to a declaration
537 /// of a function, enum, trait, etc.
538 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
539 pub struct Generics<'hir> {
540 pub params: &'hir [GenericParam<'hir>],
541 pub where_clause: WhereClause<'hir>,
545 impl Generics<'hir> {
546 pub const fn empty() -> Generics<'hir> {
549 where_clause: WhereClause { predicates: &[], span: DUMMY_SP },
554 pub fn own_counts(&self) -> GenericParamCount {
555 // We could cache this as a property of `GenericParamCount`, but
556 // the aim is to refactor this away entirely eventually and the
557 // presence of this method will be a constant reminder.
558 let mut own_counts: GenericParamCount = Default::default();
560 for param in self.params {
562 GenericParamKind::Lifetime { .. } => own_counts.lifetimes += 1,
563 GenericParamKind::Type { .. } => own_counts.types += 1,
564 GenericParamKind::Const { .. } => own_counts.consts += 1,
571 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'_>> {
572 for param in self.params {
573 if name == param.name.ident().name {
580 pub fn spans(&self) -> MultiSpan {
581 if self.params.is_empty() {
584 self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
589 /// Synthetic type parameters are converted to another form during lowering; this allows
590 /// us to track the original form they had, and is useful for error messages.
591 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
592 pub enum SyntheticTyParamKind {
596 /// A where-clause in a definition.
597 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
598 pub struct WhereClause<'hir> {
599 pub predicates: &'hir [WherePredicate<'hir>],
600 // Only valid if predicates isn't empty.
604 impl WhereClause<'_> {
605 pub fn span(&self) -> Option<Span> {
606 if self.predicates.is_empty() { None } else { Some(self.span) }
609 /// The `WhereClause` under normal circumstances points at either the predicates or the empty
610 /// space where the `where` clause should be. Only of use for diagnostic suggestions.
611 pub fn span_for_predicates_or_empty_place(&self) -> Span {
616 /// A single predicate in a where-clause.
617 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
618 pub enum WherePredicate<'hir> {
619 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
620 BoundPredicate(WhereBoundPredicate<'hir>),
621 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
622 RegionPredicate(WhereRegionPredicate<'hir>),
623 /// An equality predicate (unsupported).
624 EqPredicate(WhereEqPredicate<'hir>),
627 impl WherePredicate<'_> {
628 pub fn span(&self) -> Span {
630 &WherePredicate::BoundPredicate(ref p) => p.span,
631 &WherePredicate::RegionPredicate(ref p) => p.span,
632 &WherePredicate::EqPredicate(ref p) => p.span,
637 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
638 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
639 pub struct WhereBoundPredicate<'hir> {
641 /// Any generics from a `for` binding.
642 pub bound_generic_params: &'hir [GenericParam<'hir>],
643 /// The type being bounded.
644 pub bounded_ty: &'hir Ty<'hir>,
645 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
646 pub bounds: GenericBounds<'hir>,
649 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
650 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
651 pub struct WhereRegionPredicate<'hir> {
653 pub lifetime: Lifetime,
654 pub bounds: GenericBounds<'hir>,
657 /// An equality predicate (e.g., `T = int`); currently unsupported.
658 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
659 pub struct WhereEqPredicate<'hir> {
662 pub lhs_ty: &'hir Ty<'hir>,
663 pub rhs_ty: &'hir Ty<'hir>,
666 #[derive(RustcEncodable, RustcDecodable, Debug)]
667 pub struct ModuleItems {
668 // Use BTreeSets here so items are in the same order as in the
669 // list of all items in Crate
670 pub items: BTreeSet<HirId>,
671 pub trait_items: BTreeSet<TraitItemId>,
672 pub impl_items: BTreeSet<ImplItemId>,
675 /// The top-level data structure that stores the entire contents of
676 /// the crate currently being compiled.
678 /// For more details, see the [rustc guide].
680 /// [rustc guide]: https://rust-lang.github.io/rustc-guide/hir.html
681 #[derive(RustcEncodable, RustcDecodable, Debug)]
682 pub struct Crate<'hir> {
683 pub module: Mod<'hir>,
684 pub attrs: &'hir [Attribute],
686 pub exported_macros: &'hir [MacroDef<'hir>],
687 // Attributes from non-exported macros, kept only for collecting the library feature list.
688 pub non_exported_macro_attrs: &'hir [Attribute],
690 // N.B., we use a `BTreeMap` here so that `visit_all_items` iterates
691 // over the ids in increasing order. In principle it should not
692 // matter what order we visit things in, but in *practice* it
693 // does, because it can affect the order in which errors are
694 // detected, which in turn can make compile-fail tests yield
695 // slightly different results.
696 pub items: BTreeMap<HirId, Item<'hir>>,
698 pub trait_items: BTreeMap<TraitItemId, TraitItem<'hir>>,
699 pub impl_items: BTreeMap<ImplItemId, ImplItem<'hir>>,
700 pub bodies: BTreeMap<BodyId, Body<'hir>>,
701 pub trait_impls: BTreeMap<DefId, Vec<HirId>>,
703 /// A list of the body ids written out in the order in which they
704 /// appear in the crate. If you're going to process all the bodies
705 /// in the crate, you should iterate over this list rather than the keys
707 pub body_ids: Vec<BodyId>,
709 /// A list of modules written out in the order in which they
710 /// appear in the crate. This includes the main crate module.
711 pub modules: BTreeMap<HirId, ModuleItems>,
715 pub fn item(&self, id: HirId) -> &Item<'hir> {
719 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem<'hir> {
720 &self.trait_items[&id]
723 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem<'hir> {
724 &self.impl_items[&id]
727 pub fn body(&self, id: BodyId) -> &Body<'hir> {
733 /// Visits all items in the crate in some deterministic (but
734 /// unspecified) order. If you just need to process every item,
735 /// but don't care about nesting, this method is the best choice.
737 /// If you do care about nesting -- usually because your algorithm
738 /// follows lexical scoping rules -- then you want a different
739 /// approach. You should override `visit_nested_item` in your
740 /// visitor and then call `intravisit::walk_crate` instead.
741 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
743 V: itemlikevisit::ItemLikeVisitor<'hir>,
745 for (_, item) in &self.items {
746 visitor.visit_item(item);
749 for (_, trait_item) in &self.trait_items {
750 visitor.visit_trait_item(trait_item);
753 for (_, impl_item) in &self.impl_items {
754 visitor.visit_impl_item(impl_item);
758 /// A parallel version of `visit_all_item_likes`.
759 pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
761 V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send,
765 par_for_each_in(&self.items, |(_, item)| {
766 visitor.visit_item(item);
770 par_for_each_in(&self.trait_items, |(_, trait_item)| {
771 visitor.visit_trait_item(trait_item);
775 par_for_each_in(&self.impl_items, |(_, impl_item)| {
776 visitor.visit_impl_item(impl_item);
783 /// A macro definition, in this crate or imported from another.
785 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
786 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
787 pub struct MacroDef<'hir> {
789 pub vis: Visibility<'hir>,
790 pub attrs: &'hir [Attribute],
793 pub body: TokenStream,
797 /// A block of statements `{ .. }`, which may have a label (in this case the
798 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
799 /// the `rules` being anything but `DefaultBlock`.
800 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
801 pub struct Block<'hir> {
802 /// Statements in a block.
803 pub stmts: &'hir [Stmt<'hir>],
804 /// An expression at the end of the block
805 /// without a semicolon, if any.
806 pub expr: Option<&'hir Expr<'hir>>,
807 #[stable_hasher(ignore)]
809 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
810 pub rules: BlockCheckMode,
812 /// If true, then there may exist `break 'a` values that aim to
813 /// break out of this block early.
814 /// Used by `'label: {}` blocks and by `try {}` blocks.
815 pub targeted_by_break: bool,
818 #[derive(RustcEncodable, RustcDecodable, HashStable)]
819 pub struct Pat<'hir> {
820 #[stable_hasher(ignore)]
822 pub kind: PatKind<'hir>,
826 impl fmt::Debug for Pat<'_> {
827 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
832 print::to_string(print::NO_ANN, |s| s.print_pat(self))
838 // FIXME(#19596) this is a workaround, but there should be a better way
839 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'_>) -> bool) -> bool {
846 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
847 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
848 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
849 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
850 Slice(before, slice, after) => {
851 before.iter().chain(slice.iter()).chain(after.iter()).all(|p| p.walk_short_(it))
856 /// Walk the pattern in left-to-right order,
857 /// short circuiting (with `.all(..)`) if `false` is returned.
859 /// Note that when visiting e.g. `Tuple(ps)`,
860 /// if visiting `ps[0]` returns `false`,
861 /// then `ps[1]` will not be visited.
862 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'_>) -> bool) -> bool {
863 self.walk_short_(&mut it)
866 // FIXME(#19596) this is a workaround, but there should be a better way
867 fn walk_(&self, it: &mut impl FnMut(&Pat<'_>) -> bool) {
874 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
875 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
876 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
877 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
878 Slice(before, slice, after) => {
879 before.iter().chain(slice.iter()).chain(after.iter()).for_each(|p| p.walk_(it))
884 /// Walk the pattern in left-to-right order.
886 /// If `it(pat)` returns `false`, the children are not visited.
887 pub fn walk(&self, mut it: impl FnMut(&Pat<'_>) -> bool) {
891 /// Walk the pattern in left-to-right order.
893 /// If you always want to recurse, prefer this method over `walk`.
894 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
902 /// A single field in a struct pattern.
904 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
905 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
906 /// except `is_shorthand` is true.
907 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
908 pub struct FieldPat<'hir> {
909 #[stable_hasher(ignore)]
911 /// The identifier for the field.
912 #[stable_hasher(project(name))]
914 /// The pattern the field is destructured to.
915 pub pat: &'hir Pat<'hir>,
916 pub is_shorthand: bool,
920 /// Explicit binding annotations given in the HIR for a binding. Note
921 /// that this is not the final binding *mode* that we infer after type
923 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
924 pub enum BindingAnnotation {
925 /// No binding annotation given: this means that the final binding mode
926 /// will depend on whether we have skipped through a `&` reference
927 /// when matching. For example, the `x` in `Some(x)` will have binding
928 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
929 /// ultimately be inferred to be by-reference.
931 /// Note that implicit reference skipping is not implemented yet (#42640).
934 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
937 /// Annotated as `ref`, like `ref x`
940 /// Annotated as `ref mut x`.
944 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
950 impl fmt::Display for RangeEnd {
951 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
952 f.write_str(match self {
953 RangeEnd::Included => "..=",
954 RangeEnd::Excluded => "..",
959 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
960 pub enum PatKind<'hir> {
961 /// Represents a wildcard pattern (i.e., `_`).
964 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
965 /// The `HirId` is the canonical ID for the variable being bound,
966 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
967 /// which is the pattern ID of the first `x`.
968 Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
970 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
971 /// The `bool` is `true` in the presence of a `..`.
972 Struct(QPath<'hir>, &'hir [FieldPat<'hir>], bool),
974 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
975 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
976 /// `0 <= position <= subpats.len()`
977 TupleStruct(QPath<'hir>, &'hir [&'hir Pat<'hir>], Option<usize>),
979 /// An or-pattern `A | B | C`.
980 /// Invariant: `pats.len() >= 2`.
981 Or(&'hir [&'hir Pat<'hir>]),
983 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
986 /// A tuple pattern (e.g., `(a, b)`).
987 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
988 /// `0 <= position <= subpats.len()`
989 Tuple(&'hir [&'hir Pat<'hir>], Option<usize>),
992 Box(&'hir Pat<'hir>),
994 /// A reference pattern (e.g., `&mut (a, b)`).
995 Ref(&'hir Pat<'hir>, Mutability),
998 Lit(&'hir Expr<'hir>),
1000 /// A range pattern (e.g., `1..=2` or `1..2`).
1001 Range(&'hir Expr<'hir>, &'hir Expr<'hir>, RangeEnd),
1003 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
1005 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
1006 /// If `slice` exists, then `after` can be non-empty.
1008 /// The representation for e.g., `[a, b, .., c, d]` is:
1010 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
1012 Slice(&'hir [&'hir Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [&'hir Pat<'hir>]),
1015 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1016 pub enum BinOpKind {
1017 /// The `+` operator (addition).
1019 /// The `-` operator (subtraction).
1021 /// The `*` operator (multiplication).
1023 /// The `/` operator (division).
1025 /// The `%` operator (modulus).
1027 /// The `&&` operator (logical and).
1029 /// The `||` operator (logical or).
1031 /// The `^` operator (bitwise xor).
1033 /// The `&` operator (bitwise and).
1035 /// The `|` operator (bitwise or).
1037 /// The `<<` operator (shift left).
1039 /// The `>>` operator (shift right).
1041 /// The `==` operator (equality).
1043 /// The `<` operator (less than).
1045 /// The `<=` operator (less than or equal to).
1047 /// The `!=` operator (not equal to).
1049 /// The `>=` operator (greater than or equal to).
1051 /// The `>` operator (greater than).
1056 pub fn as_str(self) -> &'static str {
1058 BinOpKind::Add => "+",
1059 BinOpKind::Sub => "-",
1060 BinOpKind::Mul => "*",
1061 BinOpKind::Div => "/",
1062 BinOpKind::Rem => "%",
1063 BinOpKind::And => "&&",
1064 BinOpKind::Or => "||",
1065 BinOpKind::BitXor => "^",
1066 BinOpKind::BitAnd => "&",
1067 BinOpKind::BitOr => "|",
1068 BinOpKind::Shl => "<<",
1069 BinOpKind::Shr => ">>",
1070 BinOpKind::Eq => "==",
1071 BinOpKind::Lt => "<",
1072 BinOpKind::Le => "<=",
1073 BinOpKind::Ne => "!=",
1074 BinOpKind::Ge => ">=",
1075 BinOpKind::Gt => ">",
1079 pub fn is_lazy(self) -> bool {
1081 BinOpKind::And | BinOpKind::Or => true,
1086 pub fn is_shift(self) -> bool {
1088 BinOpKind::Shl | BinOpKind::Shr => true,
1093 pub fn is_comparison(self) -> bool {
1100 | BinOpKind::Ge => true,
1112 | BinOpKind::Shr => false,
1116 /// Returns `true` if the binary operator takes its arguments by value.
1117 pub fn is_by_value(self) -> bool {
1118 !self.is_comparison()
1122 impl Into<ast::BinOpKind> for BinOpKind {
1123 fn into(self) -> ast::BinOpKind {
1125 BinOpKind::Add => ast::BinOpKind::Add,
1126 BinOpKind::Sub => ast::BinOpKind::Sub,
1127 BinOpKind::Mul => ast::BinOpKind::Mul,
1128 BinOpKind::Div => ast::BinOpKind::Div,
1129 BinOpKind::Rem => ast::BinOpKind::Rem,
1130 BinOpKind::And => ast::BinOpKind::And,
1131 BinOpKind::Or => ast::BinOpKind::Or,
1132 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1133 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1134 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1135 BinOpKind::Shl => ast::BinOpKind::Shl,
1136 BinOpKind::Shr => ast::BinOpKind::Shr,
1137 BinOpKind::Eq => ast::BinOpKind::Eq,
1138 BinOpKind::Lt => ast::BinOpKind::Lt,
1139 BinOpKind::Le => ast::BinOpKind::Le,
1140 BinOpKind::Ne => ast::BinOpKind::Ne,
1141 BinOpKind::Ge => ast::BinOpKind::Ge,
1142 BinOpKind::Gt => ast::BinOpKind::Gt,
1147 pub type BinOp = Spanned<BinOpKind>;
1149 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1151 /// The `*` operator (deferencing).
1153 /// The `!` operator (logical negation).
1155 /// The `-` operator (negation).
1160 pub fn as_str(self) -> &'static str {
1168 /// Returns `true` if the unary operator takes its argument by value.
1169 pub fn is_by_value(self) -> bool {
1171 UnNeg | UnNot => true,
1178 #[derive(RustcEncodable, RustcDecodable, HashStable)]
1179 pub struct Stmt<'hir> {
1181 pub kind: StmtKind<'hir>,
1185 impl fmt::Debug for Stmt<'_> {
1186 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1191 print::to_string(print::NO_ANN, |s| s.print_stmt(self))
1196 /// The contents of a statement.
1197 #[derive(RustcEncodable, RustcDecodable, HashStable)]
1198 pub enum StmtKind<'hir> {
1199 /// A local (`let`) binding.
1200 Local(&'hir Local<'hir>),
1202 /// An item binding.
1205 /// An expression without a trailing semi-colon (must have unit type).
1206 Expr(&'hir Expr<'hir>),
1208 /// An expression with a trailing semi-colon (may have any type).
1209 Semi(&'hir Expr<'hir>),
1212 impl StmtKind<'hir> {
1213 pub fn attrs(&self) -> &'hir [Attribute] {
1215 StmtKind::Local(ref l) => &l.attrs,
1216 StmtKind::Item(_) => &[],
1217 StmtKind::Expr(ref e) | StmtKind::Semi(ref e) => &e.attrs,
1222 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1223 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1224 pub struct Local<'hir> {
1225 pub pat: &'hir Pat<'hir>,
1226 /// Type annotation, if any (otherwise the type will be inferred).
1227 pub ty: Option<&'hir Ty<'hir>>,
1228 /// Initializer expression to set the value, if any.
1229 pub init: Option<&'hir Expr<'hir>>,
1233 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1234 /// desugaring. Otherwise will be `Normal`.
1235 pub source: LocalSource,
1238 /// Represents a single arm of a `match` expression, e.g.
1239 /// `<pat> (if <guard>) => <body>`.
1240 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1241 pub struct Arm<'hir> {
1242 #[stable_hasher(ignore)]
1245 pub attrs: &'hir [Attribute],
1246 /// If this pattern and the optional guard matches, then `body` is evaluated.
1247 pub pat: &'hir Pat<'hir>,
1248 /// Optional guard clause.
1249 pub guard: Option<Guard<'hir>>,
1250 /// The expression the arm evaluates to if this arm matches.
1251 pub body: &'hir Expr<'hir>,
1254 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1255 pub enum Guard<'hir> {
1256 If(&'hir Expr<'hir>),
1259 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1260 pub struct Field<'hir> {
1261 #[stable_hasher(ignore)]
1264 pub expr: &'hir Expr<'hir>,
1266 pub is_shorthand: bool,
1269 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1270 pub enum BlockCheckMode {
1272 UnsafeBlock(UnsafeSource),
1273 PushUnsafeBlock(UnsafeSource),
1274 PopUnsafeBlock(UnsafeSource),
1277 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1278 pub enum UnsafeSource {
1283 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1288 /// The body of a function, closure, or constant value. In the case of
1289 /// a function, the body contains not only the function body itself
1290 /// (which is an expression), but also the argument patterns, since
1291 /// those are something that the caller doesn't really care about.
1296 /// fn foo((x, y): (u32, u32)) -> u32 {
1301 /// Here, the `Body` associated with `foo()` would contain:
1303 /// - an `params` array containing the `(x, y)` pattern
1304 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1305 /// - `generator_kind` would be `None`
1307 /// All bodies have an **owner**, which can be accessed via the HIR
1308 /// map using `body_owner_def_id()`.
1309 #[derive(RustcEncodable, RustcDecodable, Debug)]
1310 pub struct Body<'hir> {
1311 pub params: &'hir [Param<'hir>],
1312 pub value: Expr<'hir>,
1313 pub generator_kind: Option<GeneratorKind>,
1317 pub fn id(&self) -> BodyId {
1318 BodyId { hir_id: self.value.hir_id }
1321 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1326 /// The type of source expression that caused this generator to be created.
1327 #[derive(Clone, PartialEq, Eq, HashStable, RustcEncodable, RustcDecodable, Debug, Copy)]
1328 pub enum GeneratorKind {
1329 /// An explicit `async` block or the body of an async function.
1330 Async(AsyncGeneratorKind),
1332 /// A generator literal created via a `yield` inside a closure.
1336 impl fmt::Display for GeneratorKind {
1337 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1339 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1340 GeneratorKind::Gen => f.write_str("generator"),
1345 /// In the case of a generator created as part of an async construct,
1346 /// which kind of async construct caused it to be created?
1348 /// This helps error messages but is also used to drive coercions in
1349 /// type-checking (see #60424).
1350 #[derive(Clone, PartialEq, Eq, HashStable, RustcEncodable, RustcDecodable, Debug, Copy)]
1351 pub enum AsyncGeneratorKind {
1352 /// An explicit `async` block written by the user.
1355 /// An explicit `async` block written by the user.
1358 /// The `async` block generated as the body of an async function.
1362 impl fmt::Display for AsyncGeneratorKind {
1363 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1364 f.write_str(match self {
1365 AsyncGeneratorKind::Block => "`async` block",
1366 AsyncGeneratorKind::Closure => "`async` closure body",
1367 AsyncGeneratorKind::Fn => "`async fn` body",
1372 #[derive(Copy, Clone, Debug)]
1373 pub enum BodyOwnerKind {
1374 /// Functions and methods.
1380 /// Constants and associated constants.
1383 /// Initializer of a `static` item.
1387 impl BodyOwnerKind {
1388 pub fn is_fn_or_closure(self) -> bool {
1390 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1391 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1397 pub type Lit = Spanned<LitKind>;
1399 /// A constant (expression) that's not an item or associated item,
1400 /// but needs its own `DefId` for type-checking, const-eval, etc.
1401 /// These are usually found nested inside types (e.g., array lengths)
1402 /// or expressions (e.g., repeat counts), and also used to define
1403 /// explicit discriminant values for enum variants.
1404 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1405 pub struct AnonConst {
1411 #[derive(RustcEncodable, RustcDecodable)]
1412 pub struct Expr<'hir> {
1414 pub kind: ExprKind<'hir>,
1419 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1420 #[cfg(target_arch = "x86_64")]
1421 static_assert_size!(Expr<'static>, 64);
1424 pub fn precedence(&self) -> ExprPrecedence {
1426 ExprKind::Box(_) => ExprPrecedence::Box,
1427 ExprKind::Array(_) => ExprPrecedence::Array,
1428 ExprKind::Call(..) => ExprPrecedence::Call,
1429 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1430 ExprKind::Tup(_) => ExprPrecedence::Tup,
1431 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1432 ExprKind::Unary(..) => ExprPrecedence::Unary,
1433 ExprKind::Lit(_) => ExprPrecedence::Lit,
1434 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1435 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1436 ExprKind::Loop(..) => ExprPrecedence::Loop,
1437 ExprKind::Match(..) => ExprPrecedence::Match,
1438 ExprKind::Closure(..) => ExprPrecedence::Closure,
1439 ExprKind::Block(..) => ExprPrecedence::Block,
1440 ExprKind::Assign(..) => ExprPrecedence::Assign,
1441 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1442 ExprKind::Field(..) => ExprPrecedence::Field,
1443 ExprKind::Index(..) => ExprPrecedence::Index,
1444 ExprKind::Path(..) => ExprPrecedence::Path,
1445 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1446 ExprKind::Break(..) => ExprPrecedence::Break,
1447 ExprKind::Continue(..) => ExprPrecedence::Continue,
1448 ExprKind::Ret(..) => ExprPrecedence::Ret,
1449 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1450 ExprKind::Struct(..) => ExprPrecedence::Struct,
1451 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1452 ExprKind::Yield(..) => ExprPrecedence::Yield,
1453 ExprKind::Err => ExprPrecedence::Err,
1457 // Whether this looks like a place expr, without checking for deref
1459 // This will return `true` in some potentially surprising cases such as
1460 // `CONSTANT.field`.
1461 pub fn is_syntactic_place_expr(&self) -> bool {
1462 self.is_place_expr(|_| true)
1465 // Whether this is a place expression.
1466 // `allow_projections_from` should return `true` if indexing a field or
1467 // index expression based on the given expression should be considered a
1468 // place expression.
1469 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1471 ExprKind::Path(QPath::Resolved(_, ref path)) => match path.res {
1472 Res::Local(..) | Res::Def(DefKind::Static, _) | Res::Err => true,
1476 // Type ascription inherits its place expression kind from its
1478 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1479 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1481 ExprKind::Unary(UnDeref, _) => true,
1483 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1484 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1487 // Partially qualified paths in expressions can only legally
1488 // refer to associated items which are always rvalues.
1489 ExprKind::Path(QPath::TypeRelative(..))
1490 | ExprKind::Call(..)
1491 | ExprKind::MethodCall(..)
1492 | ExprKind::Struct(..)
1494 | ExprKind::Match(..)
1495 | ExprKind::Closure(..)
1496 | ExprKind::Block(..)
1497 | ExprKind::Repeat(..)
1498 | ExprKind::Array(..)
1499 | ExprKind::Break(..)
1500 | ExprKind::Continue(..)
1502 | ExprKind::Loop(..)
1503 | ExprKind::Assign(..)
1504 | ExprKind::InlineAsm(..)
1505 | ExprKind::AssignOp(..)
1507 | ExprKind::Unary(..)
1509 | ExprKind::AddrOf(..)
1510 | ExprKind::Binary(..)
1511 | ExprKind::Yield(..)
1512 | ExprKind::Cast(..)
1513 | ExprKind::DropTemps(..)
1514 | ExprKind::Err => false,
1518 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1519 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1520 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1521 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1522 /// beyond remembering to call this function before doing analysis on it.
1523 pub fn peel_drop_temps(&self) -> &Self {
1524 let mut expr = self;
1525 while let ExprKind::DropTemps(inner) = &expr.kind {
1532 impl fmt::Debug for Expr<'_> {
1533 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1538 print::to_string(print::NO_ANN, |s| s.print_expr(self))
1543 /// Checks if the specified expression is a built-in range literal.
1544 /// (See: `LoweringContext::lower_expr()`).
1546 /// FIXME(#60607): This function is a hack. If and when we have `QPath::Lang(...)`,
1547 /// we can use that instead as simpler, more reliable mechanism, as opposed to using `SourceMap`.
1548 pub fn is_range_literal(sm: &SourceMap, expr: &Expr<'_>) -> bool {
1549 // Returns whether the given path represents a (desugared) range,
1550 // either in std or core, i.e. has either a `::std::ops::Range` or
1551 // `::core::ops::Range` prefix.
1552 fn is_range_path(path: &Path<'_>) -> bool {
1553 let segs: Vec<_> = path.segments.iter().map(|seg| seg.ident.to_string()).collect();
1554 let segs: Vec<_> = segs.iter().map(|seg| &**seg).collect();
1556 // "{{root}}" is the equivalent of `::` prefix in `Path`.
1557 if let ["{{root}}", std_core, "ops", range] = segs.as_slice() {
1558 (*std_core == "std" || *std_core == "core") && range.starts_with("Range")
1564 // Check whether a span corresponding to a range expression is a
1565 // range literal, rather than an explicit struct or `new()` call.
1566 fn is_lit(sm: &SourceMap, span: &Span) -> bool {
1567 let end_point = sm.end_point(*span);
1569 if let Ok(end_string) = sm.span_to_snippet(end_point) {
1570 !(end_string.ends_with("}") || end_string.ends_with(")"))
1577 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1578 ExprKind::Struct(ref qpath, _, _) => {
1579 if let QPath::Resolved(None, ref path) = **qpath {
1580 return is_range_path(&path) && is_lit(sm, &expr.span);
1584 // `..` desugars to its struct path.
1585 ExprKind::Path(QPath::Resolved(None, ref path)) => {
1586 return is_range_path(&path) && is_lit(sm, &expr.span);
1589 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1590 ExprKind::Call(ref func, _) => {
1591 if let ExprKind::Path(QPath::TypeRelative(ref ty, ref segment)) = func.kind {
1592 if let TyKind::Path(QPath::Resolved(None, ref path)) = ty.kind {
1593 let new_call = segment.ident.name == sym::new;
1594 return is_range_path(&path) && is_lit(sm, &expr.span) && new_call;
1605 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1606 pub enum ExprKind<'hir> {
1607 /// A `box x` expression.
1608 Box(&'hir Expr<'hir>),
1609 /// An array (e.g., `[a, b, c, d]`).
1610 Array(&'hir [Expr<'hir>]),
1611 /// A function call.
1613 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1614 /// and the second field is the list of arguments.
1615 /// This also represents calling the constructor of
1616 /// tuple-like ADTs such as tuple structs and enum variants.
1617 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1618 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1620 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1621 /// (within the angle brackets).
1622 /// The first element of the vector of `Expr`s is the expression that evaluates
1623 /// to the object on which the method is being called on (the receiver),
1624 /// and the remaining elements are the rest of the arguments.
1625 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1626 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1628 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1629 /// the `hir_id` of the `MethodCall` node itself.
1631 /// [`type_dependent_def_id`]: ../ty/struct.TypeckTables.html#method.type_dependent_def_id
1632 MethodCall(&'hir PathSegment<'hir>, Span, &'hir [Expr<'hir>]),
1633 /// A tuple (e.g., `(a, b, c, d)`).
1634 Tup(&'hir [Expr<'hir>]),
1635 /// A binary operation (e.g., `a + b`, `a * b`).
1636 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1637 /// A unary operation (e.g., `!x`, `*x`).
1638 Unary(UnOp, &'hir Expr<'hir>),
1639 /// A literal (e.g., `1`, `"foo"`).
1641 /// A cast (e.g., `foo as f64`).
1642 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1643 /// A type reference (e.g., `Foo`).
1644 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1645 /// Wraps the expression in a terminating scope.
1646 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1648 /// This construct only exists to tweak the drop order in HIR lowering.
1649 /// An example of that is the desugaring of `for` loops.
1650 DropTemps(&'hir Expr<'hir>),
1651 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1653 /// I.e., `'label: loop { <block> }`.
1654 Loop(&'hir Block<'hir>, Option<Label>, LoopSource),
1655 /// A `match` block, with a source that indicates whether or not it is
1656 /// the result of a desugaring, and if so, which kind.
1657 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1658 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1660 /// The `Span` is the argument block `|...|`.
1662 /// This may also be a generator literal or an `async block` as indicated by the
1663 /// `Option<Movability>`.
1664 Closure(CaptureBy, &'hir FnDecl<'hir>, BodyId, Span, Option<Movability>),
1665 /// A block (e.g., `'label: { ... }`).
1666 Block(&'hir Block<'hir>, Option<Label>),
1668 /// An assignment (e.g., `a = foo()`).
1669 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1670 /// An assignment with an operator.
1673 AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1674 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1675 Field(&'hir Expr<'hir>, Ident),
1676 /// An indexing operation (`foo[2]`).
1677 Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1679 /// Path to a definition, possibly containing lifetime or type parameters.
1682 /// A referencing operation (i.e., `&a` or `&mut a`).
1683 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1684 /// A `break`, with an optional label to break.
1685 Break(Destination, Option<&'hir Expr<'hir>>),
1686 /// A `continue`, with an optional label.
1687 Continue(Destination),
1688 /// A `return`, with an optional value to be returned.
1689 Ret(Option<&'hir Expr<'hir>>),
1691 /// Inline assembly (from `asm!`), with its outputs and inputs.
1692 InlineAsm(&'hir InlineAsm<'hir>),
1694 /// A struct or struct-like variant literal expression.
1696 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1697 /// where `base` is the `Option<Expr>`.
1698 Struct(&'hir QPath<'hir>, &'hir [Field<'hir>], Option<&'hir Expr<'hir>>),
1700 /// An array literal constructed from one repeated element.
1702 /// E.g., `[1; 5]`. The first expression is the element
1703 /// to be repeated; the second is the number of times to repeat it.
1704 Repeat(&'hir Expr<'hir>, AnonConst),
1706 /// A suspension point for generators (i.e., `yield <expr>`).
1707 Yield(&'hir Expr<'hir>, YieldSource),
1709 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1713 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1715 /// To resolve the path to a `DefId`, call [`qpath_res`].
1717 /// [`qpath_res`]: ../ty/struct.TypeckTables.html#method.qpath_res
1718 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1719 pub enum QPath<'hir> {
1720 /// Path to a definition, optionally "fully-qualified" with a `Self`
1721 /// type, if the path points to an associated item in a trait.
1723 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1724 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1725 /// even though they both have the same two-segment `Clone::clone` `Path`.
1726 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
1728 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1729 /// Will be resolved by type-checking to an associated item.
1731 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1732 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1733 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1734 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
1737 /// Hints at the original code for a let statement.
1738 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1739 pub enum LocalSource {
1740 /// A `match _ { .. }`.
1742 /// A desugared `for _ in _ { .. }` loop.
1744 /// When lowering async functions, we create locals within the `async move` so that
1745 /// all parameters are dropped after the future is polled.
1747 /// ```ignore (pseudo-Rust)
1748 /// async fn foo(<pattern> @ x: Type) {
1750 /// let <pattern> = x;
1755 /// A desugared `<expr>.await`.
1759 /// Hints at the original code for a `match _ { .. }`.
1760 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
1761 pub enum MatchSource {
1762 /// A `match _ { .. }`.
1764 /// An `if _ { .. }` (optionally with `else { .. }`).
1765 IfDesugar { contains_else_clause: bool },
1766 /// An `if let _ = _ { .. }` (optionally with `else { .. }`).
1767 IfLetDesugar { contains_else_clause: bool },
1768 /// A `while _ { .. }` (which was desugared to a `loop { match _ { .. } }`).
1770 /// A `while let _ = _ { .. }` (which was desugared to a
1771 /// `loop { match _ { .. } }`).
1773 /// A desugared `for _ in _ { .. }` loop.
1775 /// A desugared `?` operator.
1777 /// A desugared `<expr>.await`.
1782 pub fn name(self) -> &'static str {
1786 IfDesugar { .. } | IfLetDesugar { .. } => "if",
1787 WhileDesugar | WhileLetDesugar => "while",
1788 ForLoopDesugar => "for",
1790 AwaitDesugar => ".await",
1795 /// The loop type that yielded an `ExprKind::Loop`.
1796 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1797 pub enum LoopSource {
1798 /// A `loop { .. }` loop.
1800 /// A `while _ { .. }` loop.
1802 /// A `while let _ = _ { .. }` loop.
1804 /// A `for _ in _ { .. }` loop.
1809 pub fn name(self) -> &'static str {
1811 LoopSource::Loop => "loop",
1812 LoopSource::While | LoopSource::WhileLet => "while",
1813 LoopSource::ForLoop => "for",
1818 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1819 pub enum LoopIdError {
1821 UnlabeledCfInWhileCondition,
1825 impl fmt::Display for LoopIdError {
1826 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1827 f.write_str(match self {
1828 LoopIdError::OutsideLoopScope => "not inside loop scope",
1829 LoopIdError::UnlabeledCfInWhileCondition => {
1830 "unlabeled control flow (break or continue) in while condition"
1832 LoopIdError::UnresolvedLabel => "label not found",
1837 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1838 pub struct Destination {
1839 // This is `Some(_)` iff there is an explicit user-specified `label
1840 pub label: Option<Label>,
1842 // These errors are caught and then reported during the diagnostics pass in
1843 // librustc_passes/loops.rs
1844 pub target_id: Result<HirId, LoopIdError>,
1847 /// The yield kind that caused an `ExprKind::Yield`.
1848 #[derive(Copy, Clone, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable, HashStable)]
1849 pub enum YieldSource {
1850 /// An `<expr>.await`.
1852 /// A plain `yield`.
1856 impl fmt::Display for YieldSource {
1857 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1858 f.write_str(match self {
1859 YieldSource::Await => "`await`",
1860 YieldSource::Yield => "`yield`",
1865 impl From<GeneratorKind> for YieldSource {
1866 fn from(kind: GeneratorKind) -> Self {
1868 // Guess based on the kind of the current generator.
1869 GeneratorKind::Gen => Self::Yield,
1870 GeneratorKind::Async(_) => Self::Await,
1875 // N.B., if you change this, you'll probably want to change the corresponding
1876 // type structure in middle/ty.rs as well.
1877 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1878 pub struct MutTy<'hir> {
1879 pub ty: &'hir Ty<'hir>,
1880 pub mutbl: Mutability,
1883 /// Represents a function's signature in a trait declaration,
1884 /// trait implementation, or a free function.
1885 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1886 pub struct FnSig<'hir> {
1887 pub header: FnHeader,
1888 pub decl: &'hir FnDecl<'hir>,
1891 // The bodies for items are stored "out of line", in a separate
1892 // hashmap in the `Crate`. Here we just record the node-id of the item
1893 // so it can fetched later.
1894 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1895 pub struct TraitItemId {
1899 /// Represents an item declaration within a trait declaration,
1900 /// possibly including a default implementation. A trait item is
1901 /// either required (meaning it doesn't have an implementation, just a
1902 /// signature) or provided (meaning it has a default implementation).
1903 #[derive(RustcEncodable, RustcDecodable, Debug)]
1904 pub struct TraitItem<'hir> {
1907 pub attrs: &'hir [Attribute],
1908 pub generics: Generics<'hir>,
1909 pub kind: TraitItemKind<'hir>,
1913 /// Represents a trait method's body (or just argument names).
1914 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1915 pub enum TraitMethod<'hir> {
1916 /// No default body in the trait, just a signature.
1917 Required(&'hir [Ident]),
1919 /// Both signature and body are provided in the trait.
1923 /// Represents a trait method or associated constant or type
1924 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1925 pub enum TraitItemKind<'hir> {
1926 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
1927 Const(&'hir Ty<'hir>, Option<BodyId>),
1928 /// A method with an optional body.
1929 Method(FnSig<'hir>, TraitMethod<'hir>),
1930 /// An associated type with (possibly empty) bounds and optional concrete
1932 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
1935 // The bodies for items are stored "out of line", in a separate
1936 // hashmap in the `Crate`. Here we just record the node-id of the item
1937 // so it can fetched later.
1938 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1939 pub struct ImplItemId {
1943 /// Represents anything within an `impl` block.
1944 #[derive(RustcEncodable, RustcDecodable, Debug)]
1945 pub struct ImplItem<'hir> {
1948 pub vis: Visibility<'hir>,
1949 pub defaultness: Defaultness,
1950 pub attrs: &'hir [Attribute],
1951 pub generics: Generics<'hir>,
1952 pub kind: ImplItemKind<'hir>,
1956 /// Represents various kinds of content within an `impl`.
1957 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1958 pub enum ImplItemKind<'hir> {
1959 /// An associated constant of the given type, set to the constant result
1960 /// of the expression.
1961 Const(&'hir Ty<'hir>, BodyId),
1962 /// A method implementation with the given signature and body.
1963 Method(FnSig<'hir>, BodyId),
1964 /// An associated type.
1965 TyAlias(&'hir Ty<'hir>),
1966 /// An associated `type = impl Trait`.
1967 OpaqueTy(GenericBounds<'hir>),
1970 /// Bind a type to an associated type (i.e., `A = Foo`).
1972 /// Bindings like `A: Debug` are represented as a special type `A =
1973 /// $::Debug` that is understood by the astconv code.
1975 /// FIXME(alexreg): why have a separate type for the binding case,
1976 /// wouldn't it be better to make the `ty` field an enum like the
1980 /// enum TypeBindingKind {
1985 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1986 pub struct TypeBinding<'hir> {
1988 #[stable_hasher(project(name))]
1990 pub kind: TypeBindingKind<'hir>,
1994 // Represents the two kinds of type bindings.
1995 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1996 pub enum TypeBindingKind<'hir> {
1997 /// E.g., `Foo<Bar: Send>`.
1998 Constraint { bounds: &'hir [GenericBound<'hir>] },
1999 /// E.g., `Foo<Bar = ()>`.
2000 Equality { ty: &'hir Ty<'hir> },
2003 impl TypeBinding<'_> {
2004 pub fn ty(&self) -> &Ty<'_> {
2006 TypeBindingKind::Equality { ref ty } => ty,
2007 _ => bug!("expected equality type binding for parenthesized generic args"),
2012 #[derive(RustcEncodable, RustcDecodable)]
2013 pub struct Ty<'hir> {
2015 pub kind: TyKind<'hir>,
2019 impl fmt::Debug for Ty<'_> {
2020 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2021 write!(f, "type({})", print::to_string(print::NO_ANN, |s| s.print_type(self)))
2025 /// Not represented directly in the AST; referred to by name through a `ty_path`.
2026 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
2036 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2037 pub struct BareFnTy<'hir> {
2038 pub unsafety: Unsafety,
2040 pub generic_params: &'hir [GenericParam<'hir>],
2041 pub decl: &'hir FnDecl<'hir>,
2042 pub param_names: &'hir [Ident],
2045 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2046 pub struct OpaqueTy<'hir> {
2047 pub generics: Generics<'hir>,
2048 pub bounds: GenericBounds<'hir>,
2049 pub impl_trait_fn: Option<DefId>,
2050 pub origin: OpaqueTyOrigin,
2053 /// From whence the opaque type came.
2054 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2055 pub enum OpaqueTyOrigin {
2056 /// `type Foo = impl Trait;`
2064 /// The various kinds of types recognized by the compiler.
2065 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2066 pub enum TyKind<'hir> {
2067 /// A variable length slice (i.e., `[T]`).
2068 Slice(&'hir Ty<'hir>),
2069 /// A fixed length array (i.e., `[T; n]`).
2070 Array(&'hir Ty<'hir>, AnonConst),
2071 /// A raw pointer (i.e., `*const T` or `*mut T`).
2073 /// A reference (i.e., `&'a T` or `&'a mut T`).
2074 Rptr(Lifetime, MutTy<'hir>),
2075 /// A bare function (e.g., `fn(usize) -> bool`).
2076 BareFn(&'hir BareFnTy<'hir>),
2077 /// The never type (`!`).
2079 /// A tuple (`(A, B, C, D, ...)`).
2080 Tup(&'hir [Ty<'hir>]),
2081 /// A path to a type definition (`module::module::...::Type`), or an
2082 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2084 /// Type parameters may be stored in each `PathSegment`.
2086 /// A type definition itself. This is currently only used for the `type Foo = impl Trait`
2087 /// item that `impl Trait` in return position desugars to.
2089 /// The generic argument list contains the lifetimes (and in the future possibly parameters)
2090 /// that are actually bound on the `impl Trait`.
2091 Def(ItemId, &'hir [GenericArg<'hir>]),
2092 /// A trait object type `Bound1 + Bound2 + Bound3`
2093 /// where `Bound` is a trait or a lifetime.
2094 TraitObject(&'hir [PolyTraitRef<'hir>], Lifetime),
2097 /// `TyKind::Infer` means the type should be inferred instead of it having been
2098 /// specified. This can appear anywhere in a type.
2100 /// Placeholder for a type that has failed to be defined.
2104 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable, PartialEq)]
2105 pub struct InlineAsmOutput {
2106 pub constraint: Symbol,
2108 pub is_indirect: bool,
2112 // NOTE(eddyb) This is used within MIR as well, so unlike the rest of the HIR,
2113 // it needs to be `Clone` and use plain `Vec<T>` instead of arena-allocated slice.
2114 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable, PartialEq)]
2115 pub struct InlineAsmInner {
2117 pub asm_str_style: StrStyle,
2118 pub outputs: Vec<InlineAsmOutput>,
2119 pub inputs: Vec<Symbol>,
2120 pub clobbers: Vec<Symbol>,
2122 pub alignstack: bool,
2123 pub dialect: AsmDialect,
2126 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2127 pub struct InlineAsm<'hir> {
2128 pub inner: InlineAsmInner,
2129 pub outputs_exprs: &'hir [Expr<'hir>],
2130 pub inputs_exprs: &'hir [Expr<'hir>],
2133 /// Represents a parameter in a function header.
2134 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2135 pub struct Param<'hir> {
2136 pub attrs: &'hir [Attribute],
2138 pub pat: &'hir Pat<'hir>,
2142 /// Represents the header (not the body) of a function declaration.
2143 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2144 pub struct FnDecl<'hir> {
2145 /// The types of the function's parameters.
2147 /// Additional argument data is stored in the function's [body](Body::parameters).
2148 pub inputs: &'hir [Ty<'hir>],
2149 pub output: FunctionRetTy<'hir>,
2150 pub c_variadic: bool,
2151 /// Does the function have an implicit self?
2152 pub implicit_self: ImplicitSelfKind,
2155 /// Represents what type of implicit self a function has, if any.
2156 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2157 pub enum ImplicitSelfKind {
2158 /// Represents a `fn x(self);`.
2160 /// Represents a `fn x(mut self);`.
2162 /// Represents a `fn x(&self);`.
2164 /// Represents a `fn x(&mut self);`.
2166 /// Represents when a function does not have a self argument or
2167 /// when a function has a `self: X` argument.
2171 impl ImplicitSelfKind {
2172 /// Does this represent an implicit self?
2173 pub fn has_implicit_self(&self) -> bool {
2175 ImplicitSelfKind::None => false,
2198 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2199 pub enum Defaultness {
2200 Default { has_value: bool },
2205 pub fn has_value(&self) -> bool {
2207 Defaultness::Default { has_value, .. } => has_value,
2208 Defaultness::Final => true,
2212 pub fn is_final(&self) -> bool {
2213 *self == Defaultness::Final
2216 pub fn is_default(&self) -> bool {
2218 Defaultness::Default { .. } => true,
2224 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2225 pub enum FunctionRetTy<'hir> {
2226 /// Return type is not specified.
2228 /// Functions default to `()` and
2229 /// closures default to inference. Span points to where return
2230 /// type would be inserted.
2231 DefaultReturn(Span),
2232 /// Everything else.
2233 Return(&'hir Ty<'hir>),
2236 impl fmt::Display for FunctionRetTy<'_> {
2237 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2239 Return(ref ty) => print::to_string(print::NO_ANN, |s| s.print_type(ty)).fmt(f),
2240 DefaultReturn(_) => "()".fmt(f),
2245 impl FunctionRetTy<'_> {
2246 pub fn span(&self) -> Span {
2248 DefaultReturn(span) => span,
2249 Return(ref ty) => ty.span,
2254 #[derive(RustcEncodable, RustcDecodable, Debug)]
2255 pub struct Mod<'hir> {
2256 /// A span from the first token past `{` to the last token until `}`.
2257 /// For `mod foo;`, the inner span ranges from the first token
2258 /// to the last token in the external file.
2260 pub item_ids: &'hir [ItemId],
2263 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2264 pub struct ForeignMod<'hir> {
2266 pub items: &'hir [ForeignItem<'hir>],
2269 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2270 pub struct GlobalAsm {
2274 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2275 pub struct EnumDef<'hir> {
2276 pub variants: &'hir [Variant<'hir>],
2279 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2280 pub struct Variant<'hir> {
2281 /// Name of the variant.
2282 #[stable_hasher(project(name))]
2284 /// Attributes of the variant.
2285 pub attrs: &'hir [Attribute],
2286 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2288 /// Fields and constructor id of the variant.
2289 pub data: VariantData<'hir>,
2290 /// Explicit discriminant (e.g., `Foo = 1`).
2291 pub disr_expr: Option<AnonConst>,
2296 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2298 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2299 /// Also produced for each element of a list `use`, e.g.
2300 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2303 /// Glob import, e.g., `use foo::*`.
2306 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2307 /// an additional `use foo::{}` for performing checks such as
2308 /// unstable feature gating. May be removed in the future.
2312 /// References to traits in impls.
2314 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2315 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2316 /// trait being referred to but just a unique `HirId` that serves as a key
2317 /// within the resolution map.
2318 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2319 pub struct TraitRef<'hir> {
2320 pub path: &'hir Path<'hir>,
2321 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2322 #[stable_hasher(ignore)]
2323 pub hir_ref_id: HirId,
2327 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2328 pub fn trait_def_id(&self) -> DefId {
2329 match self.path.res {
2330 Res::Def(DefKind::Trait, did) => did,
2331 Res::Def(DefKind::TraitAlias, did) => did,
2335 _ => unreachable!(),
2340 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2341 pub struct PolyTraitRef<'hir> {
2342 /// The `'a` in `<'a> Foo<&'a T>`.
2343 pub bound_generic_params: &'hir [GenericParam<'hir>],
2345 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2346 pub trait_ref: TraitRef<'hir>,
2351 pub type Visibility<'hir> = Spanned<VisibilityKind<'hir>>;
2353 #[derive(RustcEncodable, RustcDecodable, Debug)]
2354 pub enum VisibilityKind<'hir> {
2357 Restricted { path: &'hir Path<'hir>, hir_id: HirId },
2361 impl VisibilityKind<'_> {
2362 pub fn is_pub(&self) -> bool {
2364 VisibilityKind::Public => true,
2369 pub fn is_pub_restricted(&self) -> bool {
2371 VisibilityKind::Public | VisibilityKind::Inherited => false,
2372 VisibilityKind::Crate(..) | VisibilityKind::Restricted { .. } => true,
2376 pub fn descr(&self) -> &'static str {
2378 VisibilityKind::Public => "public",
2379 VisibilityKind::Inherited => "private",
2380 VisibilityKind::Crate(..) => "crate-visible",
2381 VisibilityKind::Restricted { .. } => "restricted",
2386 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2387 pub struct StructField<'hir> {
2389 #[stable_hasher(project(name))]
2391 pub vis: Visibility<'hir>,
2393 pub ty: &'hir Ty<'hir>,
2394 pub attrs: &'hir [Attribute],
2397 impl StructField<'_> {
2398 // Still necessary in couple of places
2399 pub fn is_positional(&self) -> bool {
2400 let first = self.ident.as_str().as_bytes()[0];
2401 first >= b'0' && first <= b'9'
2405 /// Fields and constructor IDs of enum variants and structs.
2406 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2407 pub enum VariantData<'hir> {
2408 /// A struct variant.
2410 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2411 Struct(&'hir [StructField<'hir>], /* recovered */ bool),
2412 /// A tuple variant.
2414 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2415 Tuple(&'hir [StructField<'hir>], HirId),
2418 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2422 impl VariantData<'hir> {
2423 /// Return the fields of this variant.
2424 pub fn fields(&self) -> &'hir [StructField<'hir>] {
2426 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2431 /// Return the `HirId` of this variant's constructor, if it has one.
2432 pub fn ctor_hir_id(&self) -> Option<HirId> {
2434 VariantData::Struct(_, _) => None,
2435 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2440 // The bodies for items are stored "out of line", in a separate
2441 // hashmap in the `Crate`. Here we just record the node-id of the item
2442 // so it can fetched later.
2443 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2450 /// The name might be a dummy name in case of anonymous items
2451 #[derive(RustcEncodable, RustcDecodable, Debug)]
2452 pub struct Item<'hir> {
2455 pub attrs: &'hir [Attribute],
2456 pub kind: ItemKind<'hir>,
2457 pub vis: Visibility<'hir>,
2461 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2462 pub struct FnHeader {
2463 pub unsafety: Unsafety,
2464 pub constness: Constness,
2465 pub asyncness: IsAsync,
2470 pub fn is_const(&self) -> bool {
2471 match &self.constness {
2472 Constness::Const => true,
2478 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2479 pub enum ItemKind<'hir> {
2480 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2482 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2483 ExternCrate(Option<Name>),
2485 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2489 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2490 Use(&'hir Path<'hir>, UseKind),
2492 /// A `static` item.
2493 Static(&'hir Ty<'hir>, Mutability, BodyId),
2495 Const(&'hir Ty<'hir>, BodyId),
2496 /// A function declaration.
2497 Fn(FnSig<'hir>, Generics<'hir>, BodyId),
2500 /// An external module, e.g. `extern { .. }`.
2501 ForeignMod(ForeignMod<'hir>),
2502 /// Module-level inline assembly (from `global_asm!`).
2503 GlobalAsm(&'hir GlobalAsm),
2504 /// A type alias, e.g., `type Foo = Bar<u8>`.
2505 TyAlias(&'hir Ty<'hir>, Generics<'hir>),
2506 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2507 OpaqueTy(OpaqueTy<'hir>),
2508 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2509 Enum(EnumDef<'hir>, Generics<'hir>),
2510 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2511 Struct(VariantData<'hir>, Generics<'hir>),
2512 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2513 Union(VariantData<'hir>, Generics<'hir>),
2514 /// A trait definition.
2515 Trait(IsAuto, Unsafety, Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
2517 TraitAlias(Generics<'hir>, GenericBounds<'hir>),
2519 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2525 Option<TraitRef<'hir>>, // (optional) trait this impl implements
2526 &'hir Ty<'hir>, // self
2527 &'hir [ImplItemRef<'hir>],
2532 pub fn descriptive_variant(&self) -> &str {
2534 ItemKind::ExternCrate(..) => "extern crate",
2535 ItemKind::Use(..) => "use",
2536 ItemKind::Static(..) => "static item",
2537 ItemKind::Const(..) => "constant item",
2538 ItemKind::Fn(..) => "function",
2539 ItemKind::Mod(..) => "module",
2540 ItemKind::ForeignMod(..) => "foreign module",
2541 ItemKind::GlobalAsm(..) => "global asm",
2542 ItemKind::TyAlias(..) => "type alias",
2543 ItemKind::OpaqueTy(..) => "opaque type",
2544 ItemKind::Enum(..) => "enum",
2545 ItemKind::Struct(..) => "struct",
2546 ItemKind::Union(..) => "union",
2547 ItemKind::Trait(..) => "trait",
2548 ItemKind::TraitAlias(..) => "trait alias",
2549 ItemKind::Impl(..) => "impl",
2553 pub fn adt_kind(&self) -> Option<AdtKind> {
2555 ItemKind::Struct(..) => Some(AdtKind::Struct),
2556 ItemKind::Union(..) => Some(AdtKind::Union),
2557 ItemKind::Enum(..) => Some(AdtKind::Enum),
2562 pub fn generics(&self) -> Option<&Generics<'_>> {
2564 ItemKind::Fn(_, ref generics, _)
2565 | ItemKind::TyAlias(_, ref generics)
2566 | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
2567 | ItemKind::Enum(_, ref generics)
2568 | ItemKind::Struct(_, ref generics)
2569 | ItemKind::Union(_, ref generics)
2570 | ItemKind::Trait(_, _, ref generics, _, _)
2571 | ItemKind::Impl(_, _, _, ref generics, _, _, _) => generics,
2577 /// A reference from an trait to one of its associated items. This
2578 /// contains the item's id, naturally, but also the item's name and
2579 /// some other high-level details (like whether it is an associated
2580 /// type or method, and whether it is public). This allows other
2581 /// passes to find the impl they want without loading the ID (which
2582 /// means fewer edges in the incremental compilation graph).
2583 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2584 pub struct TraitItemRef {
2585 pub id: TraitItemId,
2586 #[stable_hasher(project(name))]
2588 pub kind: AssocItemKind,
2590 pub defaultness: Defaultness,
2593 /// A reference from an impl to one of its associated items. This
2594 /// contains the item's ID, naturally, but also the item's name and
2595 /// some other high-level details (like whether it is an associated
2596 /// type or method, and whether it is public). This allows other
2597 /// passes to find the impl they want without loading the ID (which
2598 /// means fewer edges in the incremental compilation graph).
2599 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2600 pub struct ImplItemRef<'hir> {
2602 #[stable_hasher(project(name))]
2604 pub kind: AssocItemKind,
2606 pub vis: Visibility<'hir>,
2607 pub defaultness: Defaultness,
2610 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2611 pub enum AssocItemKind {
2613 Method { has_self: bool },
2618 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2619 pub struct ForeignItem<'hir> {
2620 #[stable_hasher(project(name))]
2622 pub attrs: &'hir [Attribute],
2623 pub kind: ForeignItemKind<'hir>,
2626 pub vis: Visibility<'hir>,
2629 /// An item within an `extern` block.
2630 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2631 pub enum ForeignItemKind<'hir> {
2632 /// A foreign function.
2633 Fn(&'hir FnDecl<'hir>, &'hir [Ident], Generics<'hir>),
2634 /// A foreign static item (`static ext: u8`).
2635 Static(&'hir Ty<'hir>, Mutability),
2640 impl ForeignItemKind<'hir> {
2641 pub fn descriptive_variant(&self) -> &str {
2643 ForeignItemKind::Fn(..) => "foreign function",
2644 ForeignItemKind::Static(..) => "foreign static item",
2645 ForeignItemKind::Type => "foreign type",
2650 /// A variable captured by a closure.
2651 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable, HashStable)]
2653 // First span where it is accessed (there can be multiple).
2657 pub type CaptureModeMap = NodeMap<CaptureBy>;
2659 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2660 // has length > 0 if the trait is found through an chain of imports, starting with the
2661 // import/use statement in the scope where the trait is used.
2662 #[derive(Clone, Debug)]
2663 pub struct TraitCandidate {
2665 pub import_ids: SmallVec<[NodeId; 1]>,
2668 // Trait method resolution
2669 pub type TraitMap = NodeMap<Vec<TraitCandidate>>;
2671 // Map from the NodeId of a glob import to a list of items which are actually
2673 pub type GlobMap = NodeMap<FxHashSet<Name>>;
2675 pub fn provide(providers: &mut Providers<'_>) {
2676 check_attr::provide(providers);
2677 map::provide(providers);
2678 upvars::provide(providers);
2681 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
2682 pub struct CodegenFnAttrs {
2683 pub flags: CodegenFnAttrFlags,
2684 /// Parsed representation of the `#[inline]` attribute
2685 pub inline: InlineAttr,
2686 /// Parsed representation of the `#[optimize]` attribute
2687 pub optimize: OptimizeAttr,
2688 /// The `#[export_name = "..."]` attribute, indicating a custom symbol a
2689 /// function should be exported under
2690 pub export_name: Option<Symbol>,
2691 /// The `#[link_name = "..."]` attribute, indicating a custom symbol an
2692 /// imported function should be imported as. Note that `export_name`
2693 /// probably isn't set when this is set, this is for foreign items while
2694 /// `#[export_name]` is for Rust-defined functions.
2695 pub link_name: Option<Symbol>,
2696 /// The `#[link_ordinal = "..."]` attribute, indicating an ordinal an
2697 /// imported function has in the dynamic library. Note that this must not
2698 /// be set when `link_name` is set. This is for foreign items with the
2699 /// "raw-dylib" kind.
2700 pub link_ordinal: Option<usize>,
2701 /// The `#[target_feature(enable = "...")]` attribute and the enabled
2702 /// features (only enabled features are supported right now).
2703 pub target_features: Vec<Symbol>,
2704 /// The `#[linkage = "..."]` attribute and the value we found.
2705 pub linkage: Option<Linkage>,
2706 /// The `#[link_section = "..."]` attribute, or what executable section this
2707 /// should be placed in.
2708 pub link_section: Option<Symbol>,
2712 #[derive(RustcEncodable, RustcDecodable, HashStable)]
2713 pub struct CodegenFnAttrFlags: u32 {
2714 /// `#[cold]`: a hint to LLVM that this function, when called, is never on
2716 const COLD = 1 << 0;
2717 /// `#[rustc_allocator]`: a hint to LLVM that the pointer returned from this
2718 /// function is never null.
2719 const ALLOCATOR = 1 << 1;
2720 /// `#[unwind]`: an indicator that this function may unwind despite what
2721 /// its ABI signature may otherwise imply.
2722 const UNWIND = 1 << 2;
2723 /// `#[rust_allocator_nounwind]`, an indicator that an imported FFI
2724 /// function will never unwind. Probably obsolete by recent changes with
2725 /// #[unwind], but hasn't been removed/migrated yet
2726 const RUSTC_ALLOCATOR_NOUNWIND = 1 << 3;
2727 /// `#[naked]`: an indicator to LLVM that no function prologue/epilogue
2728 /// should be generated.
2729 const NAKED = 1 << 4;
2730 /// `#[no_mangle]`: an indicator that the function's name should be the same
2732 const NO_MANGLE = 1 << 5;
2733 /// `#[rustc_std_internal_symbol]`: an indicator that this symbol is a
2734 /// "weird symbol" for the standard library in that it has slightly
2735 /// different linkage, visibility, and reachability rules.
2736 const RUSTC_STD_INTERNAL_SYMBOL = 1 << 6;
2737 /// `#[no_debug]`: an indicator that no debugging information should be
2738 /// generated for this function by LLVM.
2739 const NO_DEBUG = 1 << 7;
2740 /// `#[thread_local]`: indicates a static is actually a thread local
2742 const THREAD_LOCAL = 1 << 8;
2743 /// `#[used]`: indicates that LLVM can't eliminate this function (but the
2745 const USED = 1 << 9;
2746 /// `#[ffi_returns_twice]`, indicates that an extern function can return
2748 const FFI_RETURNS_TWICE = 1 << 10;
2749 /// `#[track_caller]`: allow access to the caller location
2750 const TRACK_CALLER = 1 << 11;
2754 impl CodegenFnAttrs {
2755 pub fn new() -> CodegenFnAttrs {
2757 flags: CodegenFnAttrFlags::empty(),
2758 inline: InlineAttr::None,
2759 optimize: OptimizeAttr::None,
2763 target_features: vec![],
2769 /// Returns `true` if `#[inline]` or `#[inline(always)]` is present.
2770 pub fn requests_inline(&self) -> bool {
2772 InlineAttr::Hint | InlineAttr::Always => true,
2773 InlineAttr::None | InlineAttr::Never => false,
2777 /// Returns `true` if it looks like this symbol needs to be exported, for example:
2779 /// * `#[no_mangle]` is present
2780 /// * `#[export_name(...)]` is present
2781 /// * `#[linkage]` is present
2782 pub fn contains_extern_indicator(&self) -> bool {
2783 self.flags.contains(CodegenFnAttrFlags::NO_MANGLE)
2784 || self.export_name.is_some()
2785 || match self.linkage {
2786 // These are private, so make sure we don't try to consider
2788 None | Some(Linkage::Internal) | Some(Linkage::Private) => false,
2794 #[derive(Copy, Clone, Debug)]
2795 pub enum Node<'hir> {
2796 Param(&'hir Param<'hir>),
2797 Item(&'hir Item<'hir>),
2798 ForeignItem(&'hir ForeignItem<'hir>),
2799 TraitItem(&'hir TraitItem<'hir>),
2800 ImplItem(&'hir ImplItem<'hir>),
2801 Variant(&'hir Variant<'hir>),
2802 Field(&'hir StructField<'hir>),
2803 AnonConst(&'hir AnonConst),
2804 Expr(&'hir Expr<'hir>),
2805 Stmt(&'hir Stmt<'hir>),
2806 PathSegment(&'hir PathSegment<'hir>),
2808 TraitRef(&'hir TraitRef<'hir>),
2809 Binding(&'hir Pat<'hir>),
2810 Pat(&'hir Pat<'hir>),
2811 Arm(&'hir Arm<'hir>),
2812 Block(&'hir Block<'hir>),
2813 Local(&'hir Local<'hir>),
2814 MacroDef(&'hir MacroDef<'hir>),
2816 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
2817 /// with synthesized constructors.
2818 Ctor(&'hir VariantData<'hir>),
2820 Lifetime(&'hir Lifetime),
2821 GenericParam(&'hir GenericParam<'hir>),
2822 Visibility(&'hir Visibility<'hir>),
2828 pub fn ident(&self) -> Option<Ident> {
2830 Node::TraitItem(TraitItem { ident, .. })
2831 | Node::ImplItem(ImplItem { ident, .. })
2832 | Node::ForeignItem(ForeignItem { ident, .. })
2833 | Node::Item(Item { ident, .. }) => Some(*ident),