1 // ignore-tidy-filelength
2 use crate::def::{CtorKind, DefKind, Res};
3 use crate::def_id::DefId;
4 crate use crate::hir_id::HirId;
5 use crate::{itemlikevisit, LangItem};
7 use rustc_ast::util::parser::ExprPrecedence;
8 use rustc_ast::{self as ast, CrateSugar, LlvmAsmDialect};
9 use rustc_ast::{Attribute, FloatTy, IntTy, Label, LitKind, StrStyle, TraitObjectSyntax, UintTy};
10 pub use rustc_ast::{BorrowKind, ImplPolarity, IsAuto};
11 pub use rustc_ast::{CaptureBy, Movability, Mutability};
12 use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
13 use rustc_data_structures::sync::{par_for_each_in, Send, Sync};
14 use rustc_macros::HashStable_Generic;
15 use rustc_span::source_map::Spanned;
16 use rustc_span::symbol::{kw, sym, Ident, Symbol};
17 use rustc_span::{def_id::LocalDefId, BytePos};
18 use rustc_span::{MultiSpan, Span, DUMMY_SP};
19 use rustc_target::asm::InlineAsmRegOrRegClass;
20 use rustc_target::spec::abi::Abi;
22 use smallvec::SmallVec;
23 use std::collections::{BTreeMap, BTreeSet};
26 #[derive(Copy, Clone, Encodable, HashStable_Generic)]
31 /// Either "`'a`", referring to a named lifetime definition,
32 /// or "``" (i.e., `kw::Empty`), for elision placeholders.
34 /// HIR lowering inserts these placeholders in type paths that
35 /// refer to type definitions needing lifetime parameters,
36 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
37 pub name: LifetimeName,
40 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
41 #[derive(HashStable_Generic)]
43 /// Some user-given name like `T` or `'x`.
46 /// Synthetic name generated when user elided a lifetime in an impl header.
48 /// E.g., the lifetimes in cases like these:
51 /// impl Foo<'_> for u32
53 /// in that case, we rewrite to
55 /// impl<'f> Foo for &'f u32
56 /// impl<'f> Foo<'f> for u32
58 /// where `'f` is something like `Fresh(0)`. The indices are
59 /// unique per impl, but not necessarily continuous.
62 /// Indicates an illegal name was given and an error has been
63 /// reported (so we should squelch other derived errors). Occurs
64 /// when, e.g., `'_` is used in the wrong place.
69 pub fn ident(&self) -> Ident {
71 ParamName::Plain(ident) => ident,
72 ParamName::Fresh(_) | ParamName::Error => {
73 Ident::with_dummy_span(kw::UnderscoreLifetime)
78 pub fn normalize_to_macros_2_0(&self) -> ParamName {
80 ParamName::Plain(ident) => ParamName::Plain(ident.normalize_to_macros_2_0()),
81 param_name => param_name,
86 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
87 #[derive(HashStable_Generic)]
88 pub enum LifetimeName {
89 /// User-given names or fresh (synthetic) names.
92 /// User wrote nothing (e.g., the lifetime in `&u32`).
95 /// Implicit lifetime in a context like `dyn Foo`. This is
96 /// distinguished from implicit lifetimes elsewhere because the
97 /// lifetime that they default to must appear elsewhere within the
98 /// enclosing type. This means that, in an `impl Trait` context, we
99 /// don't have to create a parameter for them. That is, `impl
100 /// Trait<Item = &u32>` expands to an opaque type like `type
101 /// Foo<'a> = impl Trait<Item = &'a u32>`, but `impl Trait<item =
102 /// dyn Bar>` expands to `type Foo = impl Trait<Item = dyn Bar +
103 /// 'static>`. The latter uses `ImplicitObjectLifetimeDefault` so
104 /// that surrounding code knows not to create a lifetime
106 ImplicitObjectLifetimeDefault,
108 /// Indicates an error during lowering (usually `'_` in wrong place)
109 /// that was already reported.
112 /// User wrote specifies `'_`.
115 /// User wrote `'static`.
120 pub fn ident(&self) -> Ident {
122 LifetimeName::ImplicitObjectLifetimeDefault
123 | LifetimeName::Implicit
124 | LifetimeName::Error => Ident::invalid(),
125 LifetimeName::Underscore => Ident::with_dummy_span(kw::UnderscoreLifetime),
126 LifetimeName::Static => Ident::with_dummy_span(kw::StaticLifetime),
127 LifetimeName::Param(param_name) => param_name.ident(),
131 pub fn is_elided(&self) -> bool {
133 LifetimeName::ImplicitObjectLifetimeDefault
134 | LifetimeName::Implicit
135 | LifetimeName::Underscore => true,
137 // It might seem surprising that `Fresh(_)` counts as
138 // *not* elided -- but this is because, as far as the code
139 // in the compiler is concerned -- `Fresh(_)` variants act
140 // equivalently to "some fresh name". They correspond to
141 // early-bound regions on an impl, in other words.
142 LifetimeName::Error | LifetimeName::Param(_) | LifetimeName::Static => false,
146 fn is_static(&self) -> bool {
147 self == &LifetimeName::Static
150 pub fn normalize_to_macros_2_0(&self) -> LifetimeName {
152 LifetimeName::Param(param_name) => {
153 LifetimeName::Param(param_name.normalize_to_macros_2_0())
155 lifetime_name => lifetime_name,
160 impl fmt::Display for Lifetime {
161 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162 self.name.ident().fmt(f)
166 impl fmt::Debug for Lifetime {
167 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168 write!(f, "lifetime({}: {})", self.hir_id, self.name.ident())
173 pub fn is_elided(&self) -> bool {
174 self.name.is_elided()
177 pub fn is_static(&self) -> bool {
178 self.name.is_static()
182 /// A `Path` is essentially Rust's notion of a name; for instance,
183 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
184 /// along with a bunch of supporting information.
185 #[derive(Debug, HashStable_Generic)]
186 pub struct Path<'hir> {
188 /// The resolution for the path.
190 /// The segments in the path: the things separated by `::`.
191 pub segments: &'hir [PathSegment<'hir>],
195 pub fn is_global(&self) -> bool {
196 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
200 /// A segment of a path: an identifier, an optional lifetime, and a set of
202 #[derive(Debug, HashStable_Generic)]
203 pub struct PathSegment<'hir> {
204 /// The identifier portion of this path segment.
205 #[stable_hasher(project(name))]
207 // `id` and `res` are optional. We currently only use these in save-analysis,
208 // any path segments without these will not have save-analysis info and
209 // therefore will not have 'jump to def' in IDEs, but otherwise will not be
210 // affected. (In general, we don't bother to get the defs for synthesized
211 // segments, only for segments which have come from the AST).
212 pub hir_id: Option<HirId>,
213 pub res: Option<Res>,
215 /// Type/lifetime parameters attached to this path. They come in
216 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
217 /// this is more than just simple syntactic sugar; the use of
218 /// parens affects the region binding rules, so we preserve the
220 pub args: Option<&'hir GenericArgs<'hir>>,
222 /// Whether to infer remaining type parameters, if any.
223 /// This only applies to expression and pattern paths, and
224 /// out of those only the segments with no type parameters
225 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
226 pub infer_args: bool,
229 impl<'hir> PathSegment<'hir> {
230 /// Converts an identifier to the corresponding segment.
231 pub fn from_ident(ident: Ident) -> PathSegment<'hir> {
232 PathSegment { ident, hir_id: None, res: None, infer_args: true, args: None }
235 pub fn invalid() -> Self {
236 Self::from_ident(Ident::invalid())
239 pub fn args(&self) -> &GenericArgs<'hir> {
240 if let Some(ref args) = self.args {
243 const DUMMY: &GenericArgs<'_> = &GenericArgs::none();
249 #[derive(Encodable, Debug, HashStable_Generic)]
250 pub struct ConstArg {
251 pub value: AnonConst,
255 #[derive(Debug, HashStable_Generic)]
256 pub enum GenericArg<'hir> {
262 impl GenericArg<'_> {
263 pub fn span(&self) -> Span {
265 GenericArg::Lifetime(l) => l.span,
266 GenericArg::Type(t) => t.span,
267 GenericArg::Const(c) => c.span,
271 pub fn id(&self) -> HirId {
273 GenericArg::Lifetime(l) => l.hir_id,
274 GenericArg::Type(t) => t.hir_id,
275 GenericArg::Const(c) => c.value.hir_id,
279 pub fn is_const(&self) -> bool {
280 matches!(self, GenericArg::Const(_))
283 pub fn is_synthetic(&self) -> bool {
284 matches!(self, GenericArg::Lifetime(lifetime) if lifetime.name.ident() == Ident::invalid())
287 pub fn descr(&self) -> &'static str {
289 GenericArg::Lifetime(_) => "lifetime",
290 GenericArg::Type(_) => "type",
291 GenericArg::Const(_) => "constant",
295 pub fn to_ord(&self, feats: &rustc_feature::Features) -> ast::ParamKindOrd {
297 GenericArg::Lifetime(_) => ast::ParamKindOrd::Lifetime,
298 GenericArg::Type(_) => ast::ParamKindOrd::Type,
299 GenericArg::Const(_) => {
300 ast::ParamKindOrd::Const { unordered: feats.unordered_const_ty_params() }
306 #[derive(Debug, HashStable_Generic)]
307 pub struct GenericArgs<'hir> {
308 /// The generic arguments for this path segment.
309 pub args: &'hir [GenericArg<'hir>],
310 /// Bindings (equality constraints) on associated types, if present.
311 /// E.g., `Foo<A = Bar>`.
312 pub bindings: &'hir [TypeBinding<'hir>],
313 /// Were arguments written in parenthesized form `Fn(T) -> U`?
314 /// This is required mostly for pretty-printing and diagnostics,
315 /// but also for changing lifetime elision rules to be "function-like".
316 pub parenthesized: bool,
317 /// The span encompassing arguments and the surrounding brackets `<>` or `()`
318 /// Foo<A, B, AssocTy = D> Fn(T, U, V) -> W
319 /// ^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^
320 /// Note that this may be:
321 /// - empty, if there are no generic brackets (but there may be hidden lifetimes)
322 /// - dummy, if this was generated while desugaring
326 impl GenericArgs<'_> {
327 pub const fn none() -> Self {
328 Self { args: &[], bindings: &[], parenthesized: false, span_ext: DUMMY_SP }
331 pub fn inputs(&self) -> &[Ty<'_>] {
332 if self.parenthesized {
333 for arg in self.args {
335 GenericArg::Lifetime(_) => {}
336 GenericArg::Type(ref ty) => {
337 if let TyKind::Tup(ref tys) = ty.kind {
342 GenericArg::Const(_) => {}
346 panic!("GenericArgs::inputs: not a `Fn(T) -> U`");
349 pub fn own_counts(&self) -> GenericParamCount {
350 // We could cache this as a property of `GenericParamCount`, but
351 // the aim is to refactor this away entirely eventually and the
352 // presence of this method will be a constant reminder.
353 let mut own_counts: GenericParamCount = Default::default();
355 for arg in self.args {
357 GenericArg::Lifetime(_) => own_counts.lifetimes += 1,
358 GenericArg::Type(_) => own_counts.types += 1,
359 GenericArg::Const(_) => own_counts.consts += 1,
366 /// The span encompassing the text inside the surrounding brackets.
367 /// It will also include bindings if they aren't in the form `-> Ret`
368 /// Returns `None` if the span is empty (e.g. no brackets) or dummy
369 pub fn span(&self) -> Option<Span> {
370 let span_ext = self.span_ext()?;
371 Some(span_ext.with_lo(span_ext.lo() + BytePos(1)).with_hi(span_ext.hi() - BytePos(1)))
374 /// Returns span encompassing arguments and their surrounding `<>` or `()`
375 pub fn span_ext(&self) -> Option<Span> {
376 Some(self.span_ext).filter(|span| !span.is_empty())
379 pub fn is_empty(&self) -> bool {
384 /// A modifier on a bound, currently this is only used for `?Sized`, where the
385 /// modifier is `Maybe`. Negative bounds should also be handled here.
386 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
387 #[derive(HashStable_Generic)]
388 pub enum TraitBoundModifier {
394 /// The AST represents all type param bounds as types.
395 /// `typeck::collect::compute_bounds` matches these against
396 /// the "special" built-in traits (see `middle::lang_items`) and
397 /// detects `Copy`, `Send` and `Sync`.
398 #[derive(Clone, Debug, HashStable_Generic)]
399 pub enum GenericBound<'hir> {
400 Trait(PolyTraitRef<'hir>, TraitBoundModifier),
401 // FIXME(davidtwco): Introduce `PolyTraitRef::LangItem`
402 LangItemTrait(LangItem, Span, HirId, &'hir GenericArgs<'hir>),
406 impl GenericBound<'_> {
407 pub fn trait_ref(&self) -> Option<&TraitRef<'_>> {
409 GenericBound::Trait(data, _) => Some(&data.trait_ref),
414 pub fn span(&self) -> Span {
416 GenericBound::Trait(t, ..) => t.span,
417 GenericBound::LangItemTrait(_, span, ..) => *span,
418 GenericBound::Outlives(l) => l.span,
423 pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
425 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
426 pub enum LifetimeParamKind {
427 // Indicates that the lifetime definition was explicitly declared (e.g., in
428 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
431 // Indicates that the lifetime definition was synthetically added
432 // as a result of an in-band lifetime usage (e.g., in
433 // `fn foo(x: &'a u8) -> &'a u8 { x }`).
436 // Indication that the lifetime was elided (e.g., in both cases in
437 // `fn foo(x: &u8) -> &'_ u8 { x }`).
440 // Indication that the lifetime name was somehow in error.
444 #[derive(Debug, HashStable_Generic)]
445 pub enum GenericParamKind<'hir> {
446 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
448 kind: LifetimeParamKind,
451 default: Option<&'hir Ty<'hir>>,
452 synthetic: Option<SyntheticTyParamKind>,
456 /// Optional default value for the const generic param
457 default: Option<AnonConst>,
461 #[derive(Debug, HashStable_Generic)]
462 pub struct GenericParam<'hir> {
465 pub bounds: GenericBounds<'hir>,
467 pub pure_wrt_drop: bool,
468 pub kind: GenericParamKind<'hir>,
471 impl GenericParam<'hir> {
472 pub fn bounds_span(&self) -> Option<Span> {
473 self.bounds.iter().fold(None, |span, bound| {
474 let span = span.map(|s| s.to(bound.span())).unwrap_or_else(|| bound.span());
482 pub struct GenericParamCount {
483 pub lifetimes: usize,
488 /// Represents lifetimes and type parameters attached to a declaration
489 /// of a function, enum, trait, etc.
490 #[derive(Debug, HashStable_Generic)]
491 pub struct Generics<'hir> {
492 pub params: &'hir [GenericParam<'hir>],
493 pub where_clause: WhereClause<'hir>,
497 impl Generics<'hir> {
498 pub const fn empty() -> Generics<'hir> {
501 where_clause: WhereClause { predicates: &[], span: DUMMY_SP },
506 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'_>> {
507 for param in self.params {
508 if name == param.name.ident().name {
515 pub fn spans(&self) -> MultiSpan {
516 if self.params.is_empty() {
519 self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
524 /// Synthetic type parameters are converted to another form during lowering; this allows
525 /// us to track the original form they had, and is useful for error messages.
526 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
527 #[derive(HashStable_Generic)]
528 pub enum SyntheticTyParamKind {
530 // Created by the `#[rustc_synthetic]` attribute.
534 /// A where-clause in a definition.
535 #[derive(Debug, HashStable_Generic)]
536 pub struct WhereClause<'hir> {
537 pub predicates: &'hir [WherePredicate<'hir>],
538 // Only valid if predicates aren't empty.
542 impl WhereClause<'_> {
543 pub fn span(&self) -> Option<Span> {
544 if self.predicates.is_empty() { None } else { Some(self.span) }
547 /// The `WhereClause` under normal circumstances points at either the predicates or the empty
548 /// space where the `where` clause should be. Only of use for diagnostic suggestions.
549 pub fn span_for_predicates_or_empty_place(&self) -> Span {
553 /// `Span` where further predicates would be suggested, accounting for trailing commas, like
554 /// in `fn foo<T>(t: T) where T: Foo,` so we don't suggest two trailing commas.
555 pub fn tail_span_for_suggestion(&self) -> Span {
556 let end = self.span_for_predicates_or_empty_place().shrink_to_hi();
557 self.predicates.last().map_or(end, |p| p.span()).shrink_to_hi().to(end)
561 /// A single predicate in a where-clause.
562 #[derive(Debug, HashStable_Generic)]
563 pub enum WherePredicate<'hir> {
564 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
565 BoundPredicate(WhereBoundPredicate<'hir>),
566 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
567 RegionPredicate(WhereRegionPredicate<'hir>),
568 /// An equality predicate (unsupported).
569 EqPredicate(WhereEqPredicate<'hir>),
572 impl WherePredicate<'_> {
573 pub fn span(&self) -> Span {
575 WherePredicate::BoundPredicate(p) => p.span,
576 WherePredicate::RegionPredicate(p) => p.span,
577 WherePredicate::EqPredicate(p) => p.span,
582 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
583 #[derive(Debug, HashStable_Generic)]
584 pub struct WhereBoundPredicate<'hir> {
586 /// Any generics from a `for` binding.
587 pub bound_generic_params: &'hir [GenericParam<'hir>],
588 /// The type being bounded.
589 pub bounded_ty: &'hir Ty<'hir>,
590 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
591 pub bounds: GenericBounds<'hir>,
594 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
595 #[derive(Debug, HashStable_Generic)]
596 pub struct WhereRegionPredicate<'hir> {
598 pub lifetime: Lifetime,
599 pub bounds: GenericBounds<'hir>,
602 /// An equality predicate (e.g., `T = int`); currently unsupported.
603 #[derive(Debug, HashStable_Generic)]
604 pub struct WhereEqPredicate<'hir> {
607 pub lhs_ty: &'hir Ty<'hir>,
608 pub rhs_ty: &'hir Ty<'hir>,
611 #[derive(Default, Encodable, Debug, HashStable_Generic)]
612 pub struct ModuleItems {
613 // Use BTreeSets here so items are in the same order as in the
614 // list of all items in Crate
615 pub items: BTreeSet<ItemId>,
616 pub trait_items: BTreeSet<TraitItemId>,
617 pub impl_items: BTreeSet<ImplItemId>,
618 pub foreign_items: BTreeSet<ForeignItemId>,
621 /// The top-level data structure that stores the entire contents of
622 /// the crate currently being compiled.
624 /// For more details, see the [rustc dev guide].
626 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
628 pub struct Crate<'hir> {
630 pub exported_macros: &'hir [MacroDef<'hir>],
631 // Attributes from non-exported macros, kept only for collecting the library feature list.
632 pub non_exported_macro_attrs: &'hir [Attribute],
634 // N.B., we use a `BTreeMap` here so that `visit_all_items` iterates
635 // over the ids in increasing order. In principle it should not
636 // matter what order we visit things in, but in *practice* it
637 // does, because it can affect the order in which errors are
638 // detected, which in turn can make UI tests yield
639 // slightly different results.
640 pub items: BTreeMap<ItemId, Item<'hir>>,
642 pub trait_items: BTreeMap<TraitItemId, TraitItem<'hir>>,
643 pub impl_items: BTreeMap<ImplItemId, ImplItem<'hir>>,
644 pub foreign_items: BTreeMap<ForeignItemId, ForeignItem<'hir>>,
645 pub bodies: BTreeMap<BodyId, Body<'hir>>,
646 pub trait_impls: BTreeMap<DefId, Vec<LocalDefId>>,
648 /// A list of the body ids written out in the order in which they
649 /// appear in the crate. If you're going to process all the bodies
650 /// in the crate, you should iterate over this list rather than the keys
652 pub body_ids: Vec<BodyId>,
654 /// A list of modules written out in the order in which they
655 /// appear in the crate. This includes the main crate module.
656 pub modules: BTreeMap<LocalDefId, ModuleItems>,
657 /// A list of proc macro HirIds, written out in the order in which
658 /// they are declared in the static array generated by proc_macro_harness.
659 pub proc_macros: Vec<HirId>,
661 pub trait_map: BTreeMap<HirId, Vec<TraitCandidate>>,
663 /// Collected attributes from HIR nodes.
664 pub attrs: BTreeMap<HirId, &'hir [Attribute]>,
668 pub fn item(&self, id: ItemId) -> &Item<'hir> {
672 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem<'hir> {
673 &self.trait_items[&id]
676 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem<'hir> {
677 &self.impl_items[&id]
680 pub fn foreign_item(&self, id: ForeignItemId) -> &ForeignItem<'hir> {
681 &self.foreign_items[&id]
684 pub fn body(&self, id: BodyId) -> &Body<'hir> {
690 /// Visits all items in the crate in some deterministic (but
691 /// unspecified) order. If you just need to process every item,
692 /// but don't care about nesting, this method is the best choice.
694 /// If you do care about nesting -- usually because your algorithm
695 /// follows lexical scoping rules -- then you want a different
696 /// approach. You should override `visit_nested_item` in your
697 /// visitor and then call `intravisit::walk_crate` instead.
698 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
700 V: itemlikevisit::ItemLikeVisitor<'hir>,
702 for item in self.items.values() {
703 visitor.visit_item(item);
706 for trait_item in self.trait_items.values() {
707 visitor.visit_trait_item(trait_item);
710 for impl_item in self.impl_items.values() {
711 visitor.visit_impl_item(impl_item);
714 for foreign_item in self.foreign_items.values() {
715 visitor.visit_foreign_item(foreign_item);
719 /// A parallel version of `visit_all_item_likes`.
720 pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
722 V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send,
726 par_for_each_in(&self.items, |(_, item)| {
727 visitor.visit_item(item);
731 par_for_each_in(&self.trait_items, |(_, trait_item)| {
732 visitor.visit_trait_item(trait_item);
736 par_for_each_in(&self.impl_items, |(_, impl_item)| {
737 visitor.visit_impl_item(impl_item);
741 par_for_each_in(&self.foreign_items, |(_, foreign_item)| {
742 visitor.visit_foreign_item(foreign_item);
749 /// A macro definition, in this crate or imported from another.
751 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
753 pub struct MacroDef<'hir> {
755 pub vis: Visibility<'hir>,
756 pub def_id: LocalDefId,
758 pub ast: ast::MacroDef,
763 pub fn hir_id(&self) -> HirId {
764 HirId::make_owner(self.def_id)
768 /// A block of statements `{ .. }`, which may have a label (in this case the
769 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
770 /// the `rules` being anything but `DefaultBlock`.
771 #[derive(Debug, HashStable_Generic)]
772 pub struct Block<'hir> {
773 /// Statements in a block.
774 pub stmts: &'hir [Stmt<'hir>],
775 /// An expression at the end of the block
776 /// without a semicolon, if any.
777 pub expr: Option<&'hir Expr<'hir>>,
778 #[stable_hasher(ignore)]
780 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
781 pub rules: BlockCheckMode,
783 /// If true, then there may exist `break 'a` values that aim to
784 /// break out of this block early.
785 /// Used by `'label: {}` blocks and by `try {}` blocks.
786 pub targeted_by_break: bool,
789 #[derive(Debug, HashStable_Generic)]
790 pub struct Pat<'hir> {
791 #[stable_hasher(ignore)]
793 pub kind: PatKind<'hir>,
795 // Whether to use default binding modes.
796 // At present, this is false only for destructuring assignment.
797 pub default_binding_modes: bool,
800 impl<'hir> Pat<'hir> {
801 // FIXME(#19596) this is a workaround, but there should be a better way
802 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) -> bool {
809 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
810 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
811 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
812 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
813 Slice(before, slice, after) => {
814 before.iter().chain(slice.iter()).chain(after.iter()).all(|p| p.walk_short_(it))
819 /// Walk the pattern in left-to-right order,
820 /// short circuiting (with `.all(..)`) if `false` is returned.
822 /// Note that when visiting e.g. `Tuple(ps)`,
823 /// if visiting `ps[0]` returns `false`,
824 /// then `ps[1]` will not be visited.
825 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) -> bool {
826 self.walk_short_(&mut it)
829 // FIXME(#19596) this is a workaround, but there should be a better way
830 fn walk_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) {
837 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
838 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
839 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
840 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
841 Slice(before, slice, after) => {
842 before.iter().chain(slice.iter()).chain(after.iter()).for_each(|p| p.walk_(it))
847 /// Walk the pattern in left-to-right order.
849 /// If `it(pat)` returns `false`, the children are not visited.
850 pub fn walk(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) {
854 /// Walk the pattern in left-to-right order.
856 /// If you always want to recurse, prefer this method over `walk`.
857 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
865 /// A single field in a struct pattern.
867 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
868 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
869 /// except `is_shorthand` is true.
870 #[derive(Debug, HashStable_Generic)]
871 pub struct PatField<'hir> {
872 #[stable_hasher(ignore)]
874 /// The identifier for the field.
875 #[stable_hasher(project(name))]
877 /// The pattern the field is destructured to.
878 pub pat: &'hir Pat<'hir>,
879 pub is_shorthand: bool,
883 /// Explicit binding annotations given in the HIR for a binding. Note
884 /// that this is not the final binding *mode* that we infer after type
886 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
887 pub enum BindingAnnotation {
888 /// No binding annotation given: this means that the final binding mode
889 /// will depend on whether we have skipped through a `&` reference
890 /// when matching. For example, the `x` in `Some(x)` will have binding
891 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
892 /// ultimately be inferred to be by-reference.
894 /// Note that implicit reference skipping is not implemented yet (#42640).
897 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
900 /// Annotated as `ref`, like `ref x`
903 /// Annotated as `ref mut x`.
907 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
913 impl fmt::Display for RangeEnd {
914 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
915 f.write_str(match self {
916 RangeEnd::Included => "..=",
917 RangeEnd::Excluded => "..",
922 #[derive(Debug, HashStable_Generic)]
923 pub enum PatKind<'hir> {
924 /// Represents a wildcard pattern (i.e., `_`).
927 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
928 /// The `HirId` is the canonical ID for the variable being bound,
929 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
930 /// which is the pattern ID of the first `x`.
931 Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
933 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
934 /// The `bool` is `true` in the presence of a `..`.
935 Struct(QPath<'hir>, &'hir [PatField<'hir>], bool),
937 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
938 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
939 /// `0 <= position <= subpats.len()`
940 TupleStruct(QPath<'hir>, &'hir [&'hir Pat<'hir>], Option<usize>),
942 /// An or-pattern `A | B | C`.
943 /// Invariant: `pats.len() >= 2`.
944 Or(&'hir [&'hir Pat<'hir>]),
946 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
949 /// A tuple pattern (e.g., `(a, b)`).
950 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
951 /// `0 <= position <= subpats.len()`
952 Tuple(&'hir [&'hir Pat<'hir>], Option<usize>),
955 Box(&'hir Pat<'hir>),
957 /// A reference pattern (e.g., `&mut (a, b)`).
958 Ref(&'hir Pat<'hir>, Mutability),
961 Lit(&'hir Expr<'hir>),
963 /// A range pattern (e.g., `1..=2` or `1..2`).
964 Range(Option<&'hir Expr<'hir>>, Option<&'hir Expr<'hir>>, RangeEnd),
966 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
968 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
969 /// If `slice` exists, then `after` can be non-empty.
971 /// The representation for e.g., `[a, b, .., c, d]` is:
973 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
975 Slice(&'hir [&'hir Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [&'hir Pat<'hir>]),
978 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
980 /// The `+` operator (addition).
982 /// The `-` operator (subtraction).
984 /// The `*` operator (multiplication).
986 /// The `/` operator (division).
988 /// The `%` operator (modulus).
990 /// The `&&` operator (logical and).
992 /// The `||` operator (logical or).
994 /// The `^` operator (bitwise xor).
996 /// The `&` operator (bitwise and).
998 /// The `|` operator (bitwise or).
1000 /// The `<<` operator (shift left).
1002 /// The `>>` operator (shift right).
1004 /// The `==` operator (equality).
1006 /// The `<` operator (less than).
1008 /// The `<=` operator (less than or equal to).
1010 /// The `!=` operator (not equal to).
1012 /// The `>=` operator (greater than or equal to).
1014 /// The `>` operator (greater than).
1019 pub fn as_str(self) -> &'static str {
1021 BinOpKind::Add => "+",
1022 BinOpKind::Sub => "-",
1023 BinOpKind::Mul => "*",
1024 BinOpKind::Div => "/",
1025 BinOpKind::Rem => "%",
1026 BinOpKind::And => "&&",
1027 BinOpKind::Or => "||",
1028 BinOpKind::BitXor => "^",
1029 BinOpKind::BitAnd => "&",
1030 BinOpKind::BitOr => "|",
1031 BinOpKind::Shl => "<<",
1032 BinOpKind::Shr => ">>",
1033 BinOpKind::Eq => "==",
1034 BinOpKind::Lt => "<",
1035 BinOpKind::Le => "<=",
1036 BinOpKind::Ne => "!=",
1037 BinOpKind::Ge => ">=",
1038 BinOpKind::Gt => ">",
1042 pub fn is_lazy(self) -> bool {
1043 matches!(self, BinOpKind::And | BinOpKind::Or)
1046 pub fn is_shift(self) -> bool {
1047 matches!(self, BinOpKind::Shl | BinOpKind::Shr)
1050 pub fn is_comparison(self) -> bool {
1057 | BinOpKind::Ge => true,
1069 | BinOpKind::Shr => false,
1073 /// Returns `true` if the binary operator takes its arguments by value.
1074 pub fn is_by_value(self) -> bool {
1075 !self.is_comparison()
1079 impl Into<ast::BinOpKind> for BinOpKind {
1080 fn into(self) -> ast::BinOpKind {
1082 BinOpKind::Add => ast::BinOpKind::Add,
1083 BinOpKind::Sub => ast::BinOpKind::Sub,
1084 BinOpKind::Mul => ast::BinOpKind::Mul,
1085 BinOpKind::Div => ast::BinOpKind::Div,
1086 BinOpKind::Rem => ast::BinOpKind::Rem,
1087 BinOpKind::And => ast::BinOpKind::And,
1088 BinOpKind::Or => ast::BinOpKind::Or,
1089 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1090 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1091 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1092 BinOpKind::Shl => ast::BinOpKind::Shl,
1093 BinOpKind::Shr => ast::BinOpKind::Shr,
1094 BinOpKind::Eq => ast::BinOpKind::Eq,
1095 BinOpKind::Lt => ast::BinOpKind::Lt,
1096 BinOpKind::Le => ast::BinOpKind::Le,
1097 BinOpKind::Ne => ast::BinOpKind::Ne,
1098 BinOpKind::Ge => ast::BinOpKind::Ge,
1099 BinOpKind::Gt => ast::BinOpKind::Gt,
1104 pub type BinOp = Spanned<BinOpKind>;
1106 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1108 /// The `*` operator (deferencing).
1110 /// The `!` operator (logical negation).
1112 /// The `-` operator (negation).
1117 pub fn as_str(self) -> &'static str {
1125 /// Returns `true` if the unary operator takes its argument by value.
1126 pub fn is_by_value(self) -> bool {
1127 matches!(self, Self::Neg | Self::Not)
1132 #[derive(Debug, HashStable_Generic)]
1133 pub struct Stmt<'hir> {
1135 pub kind: StmtKind<'hir>,
1139 /// The contents of a statement.
1140 #[derive(Debug, HashStable_Generic)]
1141 pub enum StmtKind<'hir> {
1142 /// A local (`let`) binding.
1143 Local(&'hir Local<'hir>),
1145 /// An item binding.
1148 /// An expression without a trailing semi-colon (must have unit type).
1149 Expr(&'hir Expr<'hir>),
1151 /// An expression with a trailing semi-colon (may have any type).
1152 Semi(&'hir Expr<'hir>),
1155 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1156 #[derive(Debug, HashStable_Generic)]
1157 pub struct Local<'hir> {
1158 pub pat: &'hir Pat<'hir>,
1159 /// Type annotation, if any (otherwise the type will be inferred).
1160 pub ty: Option<&'hir Ty<'hir>>,
1161 /// Initializer expression to set the value, if any.
1162 pub init: Option<&'hir Expr<'hir>>,
1165 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1166 /// desugaring. Otherwise will be `Normal`.
1167 pub source: LocalSource,
1170 /// Represents a single arm of a `match` expression, e.g.
1171 /// `<pat> (if <guard>) => <body>`.
1172 #[derive(Debug, HashStable_Generic)]
1173 pub struct Arm<'hir> {
1174 #[stable_hasher(ignore)]
1177 /// If this pattern and the optional guard matches, then `body` is evaluated.
1178 pub pat: &'hir Pat<'hir>,
1179 /// Optional guard clause.
1180 pub guard: Option<Guard<'hir>>,
1181 /// The expression the arm evaluates to if this arm matches.
1182 pub body: &'hir Expr<'hir>,
1185 #[derive(Debug, HashStable_Generic)]
1186 pub enum Guard<'hir> {
1187 If(&'hir Expr<'hir>),
1188 IfLet(&'hir Pat<'hir>, &'hir Expr<'hir>),
1191 #[derive(Debug, HashStable_Generic)]
1192 pub struct ExprField<'hir> {
1193 #[stable_hasher(ignore)]
1196 pub expr: &'hir Expr<'hir>,
1198 pub is_shorthand: bool,
1201 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1202 pub enum BlockCheckMode {
1204 UnsafeBlock(UnsafeSource),
1205 PushUnsafeBlock(UnsafeSource),
1206 PopUnsafeBlock(UnsafeSource),
1209 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1210 pub enum UnsafeSource {
1215 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Hash, Debug)]
1220 /// The body of a function, closure, or constant value. In the case of
1221 /// a function, the body contains not only the function body itself
1222 /// (which is an expression), but also the argument patterns, since
1223 /// those are something that the caller doesn't really care about.
1228 /// fn foo((x, y): (u32, u32)) -> u32 {
1233 /// Here, the `Body` associated with `foo()` would contain:
1235 /// - an `params` array containing the `(x, y)` pattern
1236 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1237 /// - `generator_kind` would be `None`
1239 /// All bodies have an **owner**, which can be accessed via the HIR
1240 /// map using `body_owner_def_id()`.
1242 pub struct Body<'hir> {
1243 pub params: &'hir [Param<'hir>],
1244 pub value: Expr<'hir>,
1245 pub generator_kind: Option<GeneratorKind>,
1249 pub fn id(&self) -> BodyId {
1250 BodyId { hir_id: self.value.hir_id }
1253 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1258 /// The type of source expression that caused this generator to be created.
1271 pub enum GeneratorKind {
1272 /// An explicit `async` block or the body of an async function.
1273 Async(AsyncGeneratorKind),
1275 /// A generator literal created via a `yield` inside a closure.
1279 impl fmt::Display for GeneratorKind {
1280 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1282 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1283 GeneratorKind::Gen => f.write_str("generator"),
1288 impl GeneratorKind {
1289 pub fn descr(&self) -> &'static str {
1291 GeneratorKind::Async(ask) => ask.descr(),
1292 GeneratorKind::Gen => "generator",
1297 /// In the case of a generator created as part of an async construct,
1298 /// which kind of async construct caused it to be created?
1300 /// This helps error messages but is also used to drive coercions in
1301 /// type-checking (see #60424).
1314 pub enum AsyncGeneratorKind {
1315 /// An explicit `async` block written by the user.
1318 /// An explicit `async` block written by the user.
1321 /// The `async` block generated as the body of an async function.
1325 impl fmt::Display for AsyncGeneratorKind {
1326 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1327 f.write_str(match self {
1328 AsyncGeneratorKind::Block => "`async` block",
1329 AsyncGeneratorKind::Closure => "`async` closure body",
1330 AsyncGeneratorKind::Fn => "`async fn` body",
1335 impl AsyncGeneratorKind {
1336 pub fn descr(&self) -> &'static str {
1338 AsyncGeneratorKind::Block => "`async` block",
1339 AsyncGeneratorKind::Closure => "`async` closure body",
1340 AsyncGeneratorKind::Fn => "`async fn` body",
1345 #[derive(Copy, Clone, Debug)]
1346 pub enum BodyOwnerKind {
1347 /// Functions and methods.
1353 /// Constants and associated constants.
1356 /// Initializer of a `static` item.
1360 impl BodyOwnerKind {
1361 pub fn is_fn_or_closure(self) -> bool {
1363 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1364 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1369 /// The kind of an item that requires const-checking.
1370 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1371 pub enum ConstContext {
1375 /// A `static` or `static mut`.
1378 /// A `const`, associated `const`, or other const context.
1380 /// Other contexts include:
1381 /// - Array length expressions
1382 /// - Enum discriminants
1383 /// - Const generics
1385 /// For the most part, other contexts are treated just like a regular `const`, so they are
1386 /// lumped into the same category.
1391 /// A description of this const context that can appear between backticks in an error message.
1393 /// E.g. `const` or `static mut`.
1394 pub fn keyword_name(self) -> &'static str {
1396 Self::Const => "const",
1397 Self::Static(Mutability::Not) => "static",
1398 Self::Static(Mutability::Mut) => "static mut",
1399 Self::ConstFn => "const fn",
1404 /// A colloquial, trivially pluralizable description of this const context for use in error
1406 impl fmt::Display for ConstContext {
1407 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1409 Self::Const => write!(f, "constant"),
1410 Self::Static(_) => write!(f, "static"),
1411 Self::ConstFn => write!(f, "constant function"),
1417 pub type Lit = Spanned<LitKind>;
1419 /// A constant (expression) that's not an item or associated item,
1420 /// but needs its own `DefId` for type-checking, const-eval, etc.
1421 /// These are usually found nested inside types (e.g., array lengths)
1422 /// or expressions (e.g., repeat counts), and also used to define
1423 /// explicit discriminant values for enum variants.
1424 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1425 pub struct AnonConst {
1432 pub struct Expr<'hir> {
1434 pub kind: ExprKind<'hir>,
1439 pub fn precedence(&self) -> ExprPrecedence {
1441 ExprKind::Box(_) => ExprPrecedence::Box,
1442 ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1443 ExprKind::Array(_) => ExprPrecedence::Array,
1444 ExprKind::Call(..) => ExprPrecedence::Call,
1445 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1446 ExprKind::Tup(_) => ExprPrecedence::Tup,
1447 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1448 ExprKind::Unary(..) => ExprPrecedence::Unary,
1449 ExprKind::Lit(_) => ExprPrecedence::Lit,
1450 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1451 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1452 ExprKind::If(..) => ExprPrecedence::If,
1453 ExprKind::Loop(..) => ExprPrecedence::Loop,
1454 ExprKind::Match(..) => ExprPrecedence::Match,
1455 ExprKind::Closure(..) => ExprPrecedence::Closure,
1456 ExprKind::Block(..) => ExprPrecedence::Block,
1457 ExprKind::Assign(..) => ExprPrecedence::Assign,
1458 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1459 ExprKind::Field(..) => ExprPrecedence::Field,
1460 ExprKind::Index(..) => ExprPrecedence::Index,
1461 ExprKind::Path(..) => ExprPrecedence::Path,
1462 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1463 ExprKind::Break(..) => ExprPrecedence::Break,
1464 ExprKind::Continue(..) => ExprPrecedence::Continue,
1465 ExprKind::Ret(..) => ExprPrecedence::Ret,
1466 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1467 ExprKind::LlvmInlineAsm(..) => ExprPrecedence::InlineAsm,
1468 ExprKind::Struct(..) => ExprPrecedence::Struct,
1469 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1470 ExprKind::Yield(..) => ExprPrecedence::Yield,
1471 ExprKind::Err => ExprPrecedence::Err,
1475 // Whether this looks like a place expr, without checking for deref
1477 // This will return `true` in some potentially surprising cases such as
1478 // `CONSTANT.field`.
1479 pub fn is_syntactic_place_expr(&self) -> bool {
1480 self.is_place_expr(|_| true)
1483 /// Whether this is a place expression.
1485 /// `allow_projections_from` should return `true` if indexing a field or index expression based
1486 /// on the given expression should be considered a place expression.
1487 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1489 ExprKind::Path(QPath::Resolved(_, ref path)) => {
1490 matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static, _) | Res::Err)
1493 // Type ascription inherits its place expression kind from its
1495 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1496 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1498 ExprKind::Unary(UnOp::Deref, _) => true,
1500 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1501 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1504 // Lang item paths cannot currently be local variables or statics.
1505 ExprKind::Path(QPath::LangItem(..)) => false,
1507 // Partially qualified paths in expressions can only legally
1508 // refer to associated items which are always rvalues.
1509 ExprKind::Path(QPath::TypeRelative(..))
1510 | ExprKind::Call(..)
1511 | ExprKind::MethodCall(..)
1512 | ExprKind::Struct(..)
1515 | ExprKind::Match(..)
1516 | ExprKind::Closure(..)
1517 | ExprKind::Block(..)
1518 | ExprKind::Repeat(..)
1519 | ExprKind::Array(..)
1520 | ExprKind::Break(..)
1521 | ExprKind::Continue(..)
1523 | ExprKind::Loop(..)
1524 | ExprKind::Assign(..)
1525 | ExprKind::InlineAsm(..)
1526 | ExprKind::LlvmInlineAsm(..)
1527 | ExprKind::AssignOp(..)
1529 | ExprKind::ConstBlock(..)
1530 | ExprKind::Unary(..)
1532 | ExprKind::AddrOf(..)
1533 | ExprKind::Binary(..)
1534 | ExprKind::Yield(..)
1535 | ExprKind::Cast(..)
1536 | ExprKind::DropTemps(..)
1537 | ExprKind::Err => false,
1541 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1542 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1543 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1544 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1545 /// beyond remembering to call this function before doing analysis on it.
1546 pub fn peel_drop_temps(&self) -> &Self {
1547 let mut expr = self;
1548 while let ExprKind::DropTemps(inner) = &expr.kind {
1554 pub fn peel_blocks(&self) -> &Self {
1555 let mut expr = self;
1556 while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind {
1562 pub fn can_have_side_effects(&self) -> bool {
1563 match self.peel_drop_temps().kind {
1564 ExprKind::Path(_) | ExprKind::Lit(_) => false,
1565 ExprKind::Type(base, _)
1566 | ExprKind::Unary(_, base)
1567 | ExprKind::Field(base, _)
1568 | ExprKind::Index(base, _)
1569 | ExprKind::AddrOf(.., base)
1570 | ExprKind::Cast(base, _) => {
1571 // This isn't exactly true for `Index` and all `Unnary`, but we are using this
1572 // method exclusively for diagnostics and there's a *cultural* pressure against
1573 // them being used only for its side-effects.
1574 base.can_have_side_effects()
1576 ExprKind::Struct(_, fields, init) => fields
1578 .map(|field| field.expr)
1579 .chain(init.into_iter())
1580 .all(|e| e.can_have_side_effects()),
1582 ExprKind::Array(args)
1583 | ExprKind::Tup(args)
1587 ExprKind::Path(QPath::Resolved(
1589 Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. },
1594 ) => args.iter().all(|arg| arg.can_have_side_effects()),
1596 | ExprKind::Match(..)
1597 | ExprKind::MethodCall(..)
1598 | ExprKind::Call(..)
1599 | ExprKind::Closure(..)
1600 | ExprKind::Block(..)
1601 | ExprKind::Repeat(..)
1602 | ExprKind::Break(..)
1603 | ExprKind::Continue(..)
1605 | ExprKind::Loop(..)
1606 | ExprKind::Assign(..)
1607 | ExprKind::InlineAsm(..)
1608 | ExprKind::LlvmInlineAsm(..)
1609 | ExprKind::AssignOp(..)
1610 | ExprKind::ConstBlock(..)
1612 | ExprKind::Binary(..)
1613 | ExprKind::Yield(..)
1614 | ExprKind::DropTemps(..)
1615 | ExprKind::Err => true,
1620 /// Checks if the specified expression is a built-in range literal.
1621 /// (See: `LoweringContext::lower_expr()`).
1622 pub fn is_range_literal(expr: &Expr<'_>) -> bool {
1624 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1625 ExprKind::Struct(ref qpath, _, _) => matches!(
1630 | LangItem::RangeFrom
1631 | LangItem::RangeFull
1632 | LangItem::RangeToInclusive,
1637 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1638 ExprKind::Call(ref func, _) => {
1639 matches!(func.kind, ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, _)))
1646 #[derive(Debug, HashStable_Generic)]
1647 pub enum ExprKind<'hir> {
1648 /// A `box x` expression.
1649 Box(&'hir Expr<'hir>),
1650 /// Allow anonymous constants from an inline `const` block
1651 ConstBlock(AnonConst),
1652 /// An array (e.g., `[a, b, c, d]`).
1653 Array(&'hir [Expr<'hir>]),
1654 /// A function call.
1656 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1657 /// and the second field is the list of arguments.
1658 /// This also represents calling the constructor of
1659 /// tuple-like ADTs such as tuple structs and enum variants.
1660 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1661 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1663 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1664 /// (within the angle brackets).
1665 /// The first element of the vector of `Expr`s is the expression that evaluates
1666 /// to the object on which the method is being called on (the receiver),
1667 /// and the remaining elements are the rest of the arguments.
1668 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1669 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1670 /// The final `Span` represents the span of the function and arguments
1671 /// (e.g. `foo::<Bar, Baz>(a, b, c, d)` in `x.foo::<Bar, Baz>(a, b, c, d)`
1673 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1674 /// the `hir_id` of the `MethodCall` node itself.
1676 /// [`type_dependent_def_id`]: ../ty/struct.TypeckResults.html#method.type_dependent_def_id
1677 MethodCall(&'hir PathSegment<'hir>, Span, &'hir [Expr<'hir>], Span),
1678 /// A tuple (e.g., `(a, b, c, d)`).
1679 Tup(&'hir [Expr<'hir>]),
1680 /// A binary operation (e.g., `a + b`, `a * b`).
1681 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1682 /// A unary operation (e.g., `!x`, `*x`).
1683 Unary(UnOp, &'hir Expr<'hir>),
1684 /// A literal (e.g., `1`, `"foo"`).
1686 /// A cast (e.g., `foo as f64`).
1687 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1688 /// A type reference (e.g., `Foo`).
1689 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1690 /// Wraps the expression in a terminating scope.
1691 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1693 /// This construct only exists to tweak the drop order in HIR lowering.
1694 /// An example of that is the desugaring of `for` loops.
1695 DropTemps(&'hir Expr<'hir>),
1696 /// An `if` block, with an optional else block.
1698 /// I.e., `if <expr> { <expr> } else { <expr> }`.
1699 If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
1700 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1702 /// I.e., `'label: loop { <block> }`.
1704 /// The `Span` is the loop header (`for x in y`/`while let pat = expr`).
1705 Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span),
1706 /// A `match` block, with a source that indicates whether or not it is
1707 /// the result of a desugaring, and if so, which kind.
1708 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1709 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1711 /// The `Span` is the argument block `|...|`.
1713 /// This may also be a generator literal or an `async block` as indicated by the
1714 /// `Option<Movability>`.
1715 Closure(CaptureBy, &'hir FnDecl<'hir>, BodyId, Span, Option<Movability>),
1716 /// A block (e.g., `'label: { ... }`).
1717 Block(&'hir Block<'hir>, Option<Label>),
1719 /// An assignment (e.g., `a = foo()`).
1720 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1721 /// An assignment with an operator.
1724 AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1725 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1726 Field(&'hir Expr<'hir>, Ident),
1727 /// An indexing operation (`foo[2]`).
1728 Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1730 /// Path to a definition, possibly containing lifetime or type parameters.
1733 /// A referencing operation (i.e., `&a` or `&mut a`).
1734 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1735 /// A `break`, with an optional label to break.
1736 Break(Destination, Option<&'hir Expr<'hir>>),
1737 /// A `continue`, with an optional label.
1738 Continue(Destination),
1739 /// A `return`, with an optional value to be returned.
1740 Ret(Option<&'hir Expr<'hir>>),
1742 /// Inline assembly (from `asm!`), with its outputs and inputs.
1743 InlineAsm(&'hir InlineAsm<'hir>),
1744 /// Inline assembly (from `llvm_asm!`), with its outputs and inputs.
1745 LlvmInlineAsm(&'hir LlvmInlineAsm<'hir>),
1747 /// A struct or struct-like variant literal expression.
1749 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1750 /// where `base` is the `Option<Expr>`.
1751 Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], Option<&'hir Expr<'hir>>),
1753 /// An array literal constructed from one repeated element.
1755 /// E.g., `[1; 5]`. The first expression is the element
1756 /// to be repeated; the second is the number of times to repeat it.
1757 Repeat(&'hir Expr<'hir>, AnonConst),
1759 /// A suspension point for generators (i.e., `yield <expr>`).
1760 Yield(&'hir Expr<'hir>, YieldSource),
1762 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1766 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1768 /// To resolve the path to a `DefId`, call [`qpath_res`].
1770 /// [`qpath_res`]: ../rustc_middle/ty/struct.TypeckResults.html#method.qpath_res
1771 #[derive(Debug, HashStable_Generic)]
1772 pub enum QPath<'hir> {
1773 /// Path to a definition, optionally "fully-qualified" with a `Self`
1774 /// type, if the path points to an associated item in a trait.
1776 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1777 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1778 /// even though they both have the same two-segment `Clone::clone` `Path`.
1779 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
1781 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1782 /// Will be resolved by type-checking to an associated item.
1784 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1785 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1786 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1787 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
1789 /// Reference to a `#[lang = "foo"]` item.
1790 LangItem(LangItem, Span),
1793 impl<'hir> QPath<'hir> {
1794 /// Returns the span of this `QPath`.
1795 pub fn span(&self) -> Span {
1797 QPath::Resolved(_, path) => path.span,
1798 QPath::TypeRelative(qself, ps) => qself.span.to(ps.ident.span),
1799 QPath::LangItem(_, span) => span,
1803 /// Returns the span of the qself of this `QPath`. For example, `()` in
1804 /// `<() as Trait>::method`.
1805 pub fn qself_span(&self) -> Span {
1807 QPath::Resolved(_, path) => path.span,
1808 QPath::TypeRelative(qself, _) => qself.span,
1809 QPath::LangItem(_, span) => span,
1813 /// Returns the span of the last segment of this `QPath`. For example, `method` in
1814 /// `<() as Trait>::method`.
1815 pub fn last_segment_span(&self) -> Span {
1817 QPath::Resolved(_, path) => path.segments.last().unwrap().ident.span,
1818 QPath::TypeRelative(_, segment) => segment.ident.span,
1819 QPath::LangItem(_, span) => span,
1824 /// Hints at the original code for a let statement.
1825 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1826 pub enum LocalSource {
1827 /// A `match _ { .. }`.
1829 /// A desugared `for _ in _ { .. }` loop.
1831 /// When lowering async functions, we create locals within the `async move` so that
1832 /// all parameters are dropped after the future is polled.
1834 /// ```ignore (pseudo-Rust)
1835 /// async fn foo(<pattern> @ x: Type) {
1837 /// let <pattern> = x;
1842 /// A desugared `<expr>.await`.
1844 /// A desugared `expr = expr`, where the LHS is a tuple, struct or array.
1845 /// The span is that of the `=` sign.
1846 AssignDesugar(Span),
1849 /// Hints at the original code for a `match _ { .. }`.
1850 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
1851 #[derive(HashStable_Generic)]
1852 pub enum MatchSource {
1853 /// A `match _ { .. }`.
1855 /// An `if let _ = _ { .. }` (optionally with `else { .. }`).
1856 IfLetDesugar { contains_else_clause: bool },
1857 /// An `if let _ = _ => { .. }` match guard.
1859 /// A `while _ { .. }` (which was desugared to a `loop { match _ { .. } }`).
1861 /// A `while let _ = _ { .. }` (which was desugared to a
1862 /// `loop { match _ { .. } }`).
1864 /// A desugared `for _ in _ { .. }` loop.
1866 /// A desugared `?` operator.
1868 /// A desugared `<expr>.await`.
1873 pub fn name(self) -> &'static str {
1877 IfLetDesugar { .. } | IfLetGuardDesugar => "if",
1878 WhileDesugar | WhileLetDesugar => "while",
1879 ForLoopDesugar => "for",
1881 AwaitDesugar => ".await",
1886 /// The loop type that yielded an `ExprKind::Loop`.
1887 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1888 pub enum LoopSource {
1889 /// A `loop { .. }` loop.
1891 /// A `while _ { .. }` loop.
1893 /// A `while let _ = _ { .. }` loop.
1895 /// A `for _ in _ { .. }` loop.
1900 pub fn name(self) -> &'static str {
1902 LoopSource::Loop => "loop",
1903 LoopSource::While | LoopSource::WhileLet => "while",
1904 LoopSource::ForLoop => "for",
1909 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1910 pub enum LoopIdError {
1912 UnlabeledCfInWhileCondition,
1916 impl fmt::Display for LoopIdError {
1917 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1918 f.write_str(match self {
1919 LoopIdError::OutsideLoopScope => "not inside loop scope",
1920 LoopIdError::UnlabeledCfInWhileCondition => {
1921 "unlabeled control flow (break or continue) in while condition"
1923 LoopIdError::UnresolvedLabel => "label not found",
1928 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1929 pub struct Destination {
1930 // This is `Some(_)` iff there is an explicit user-specified `label
1931 pub label: Option<Label>,
1933 // These errors are caught and then reported during the diagnostics pass in
1934 // librustc_passes/loops.rs
1935 pub target_id: Result<HirId, LoopIdError>,
1938 /// The yield kind that caused an `ExprKind::Yield`.
1939 #[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
1940 pub enum YieldSource {
1941 /// An `<expr>.await`.
1942 Await { expr: Option<HirId> },
1943 /// A plain `yield`.
1948 pub fn is_await(&self) -> bool {
1950 YieldSource::Await { .. } => true,
1951 YieldSource::Yield => false,
1956 impl fmt::Display for YieldSource {
1957 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1958 f.write_str(match self {
1959 YieldSource::Await { .. } => "`await`",
1960 YieldSource::Yield => "`yield`",
1965 impl From<GeneratorKind> for YieldSource {
1966 fn from(kind: GeneratorKind) -> Self {
1968 // Guess based on the kind of the current generator.
1969 GeneratorKind::Gen => Self::Yield,
1970 GeneratorKind::Async(_) => Self::Await { expr: None },
1975 // N.B., if you change this, you'll probably want to change the corresponding
1976 // type structure in middle/ty.rs as well.
1977 #[derive(Debug, HashStable_Generic)]
1978 pub struct MutTy<'hir> {
1979 pub ty: &'hir Ty<'hir>,
1980 pub mutbl: Mutability,
1983 /// Represents a function's signature in a trait declaration,
1984 /// trait implementation, or a free function.
1985 #[derive(Debug, HashStable_Generic)]
1986 pub struct FnSig<'hir> {
1987 pub header: FnHeader,
1988 pub decl: &'hir FnDecl<'hir>,
1992 // The bodies for items are stored "out of line", in a separate
1993 // hashmap in the `Crate`. Here we just record the hir-id of the item
1994 // so it can fetched later.
1995 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
1996 pub struct TraitItemId {
1997 pub def_id: LocalDefId,
2002 pub fn hir_id(&self) -> HirId {
2003 // Items are always HIR owners.
2004 HirId::make_owner(self.def_id)
2008 /// Represents an item declaration within a trait declaration,
2009 /// possibly including a default implementation. A trait item is
2010 /// either required (meaning it doesn't have an implementation, just a
2011 /// signature) or provided (meaning it has a default implementation).
2013 pub struct TraitItem<'hir> {
2015 pub def_id: LocalDefId,
2016 pub generics: Generics<'hir>,
2017 pub kind: TraitItemKind<'hir>,
2021 impl TraitItem<'_> {
2023 pub fn hir_id(&self) -> HirId {
2024 // Items are always HIR owners.
2025 HirId::make_owner(self.def_id)
2028 pub fn trait_item_id(&self) -> TraitItemId {
2029 TraitItemId { def_id: self.def_id }
2033 /// Represents a trait method's body (or just argument names).
2034 #[derive(Encodable, Debug, HashStable_Generic)]
2035 pub enum TraitFn<'hir> {
2036 /// No default body in the trait, just a signature.
2037 Required(&'hir [Ident]),
2039 /// Both signature and body are provided in the trait.
2043 /// Represents a trait method or associated constant or type
2044 #[derive(Debug, HashStable_Generic)]
2045 pub enum TraitItemKind<'hir> {
2046 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
2047 Const(&'hir Ty<'hir>, Option<BodyId>),
2048 /// An associated function with an optional body.
2049 Fn(FnSig<'hir>, TraitFn<'hir>),
2050 /// An associated type with (possibly empty) bounds and optional concrete
2052 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
2055 // The bodies for items are stored "out of line", in a separate
2056 // hashmap in the `Crate`. Here we just record the hir-id of the item
2057 // so it can fetched later.
2058 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
2059 pub struct ImplItemId {
2060 pub def_id: LocalDefId,
2065 pub fn hir_id(&self) -> HirId {
2066 // Items are always HIR owners.
2067 HirId::make_owner(self.def_id)
2071 /// Represents anything within an `impl` block.
2073 pub struct ImplItem<'hir> {
2075 pub def_id: LocalDefId,
2076 pub vis: Visibility<'hir>,
2077 pub defaultness: Defaultness,
2078 pub generics: Generics<'hir>,
2079 pub kind: ImplItemKind<'hir>,
2085 pub fn hir_id(&self) -> HirId {
2086 // Items are always HIR owners.
2087 HirId::make_owner(self.def_id)
2090 pub fn impl_item_id(&self) -> ImplItemId {
2091 ImplItemId { def_id: self.def_id }
2095 /// Represents various kinds of content within an `impl`.
2096 #[derive(Debug, HashStable_Generic)]
2097 pub enum ImplItemKind<'hir> {
2098 /// An associated constant of the given type, set to the constant result
2099 /// of the expression.
2100 Const(&'hir Ty<'hir>, BodyId),
2101 /// An associated function implementation with the given signature and body.
2102 Fn(FnSig<'hir>, BodyId),
2103 /// An associated type.
2104 TyAlias(&'hir Ty<'hir>),
2107 // The name of the associated type for `Fn` return types.
2108 pub const FN_OUTPUT_NAME: Symbol = sym::Output;
2110 /// Bind a type to an associated type (i.e., `A = Foo`).
2112 /// Bindings like `A: Debug` are represented as a special type `A =
2113 /// $::Debug` that is understood by the astconv code.
2115 /// FIXME(alexreg): why have a separate type for the binding case,
2116 /// wouldn't it be better to make the `ty` field an enum like the
2120 /// enum TypeBindingKind {
2125 #[derive(Debug, HashStable_Generic)]
2126 pub struct TypeBinding<'hir> {
2128 #[stable_hasher(project(name))]
2130 pub gen_args: &'hir GenericArgs<'hir>,
2131 pub kind: TypeBindingKind<'hir>,
2135 // Represents the two kinds of type bindings.
2136 #[derive(Debug, HashStable_Generic)]
2137 pub enum TypeBindingKind<'hir> {
2138 /// E.g., `Foo<Bar: Send>`.
2139 Constraint { bounds: &'hir [GenericBound<'hir>] },
2140 /// E.g., `Foo<Bar = ()>`.
2141 Equality { ty: &'hir Ty<'hir> },
2144 impl TypeBinding<'_> {
2145 pub fn ty(&self) -> &Ty<'_> {
2147 TypeBindingKind::Equality { ref ty } => ty,
2148 _ => panic!("expected equality type binding for parenthesized generic args"),
2154 pub struct Ty<'hir> {
2156 pub kind: TyKind<'hir>,
2160 /// Not represented directly in the AST; referred to by name through a `ty_path`.
2161 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
2162 #[derive(HashStable_Generic)]
2173 /// All of the primitive types
2174 pub const ALL: [Self; 17] = [
2175 // any changes here should also be reflected in `PrimTy::from_name`
2176 Self::Int(IntTy::I8),
2177 Self::Int(IntTy::I16),
2178 Self::Int(IntTy::I32),
2179 Self::Int(IntTy::I64),
2180 Self::Int(IntTy::I128),
2181 Self::Int(IntTy::Isize),
2182 Self::Uint(UintTy::U8),
2183 Self::Uint(UintTy::U16),
2184 Self::Uint(UintTy::U32),
2185 Self::Uint(UintTy::U64),
2186 Self::Uint(UintTy::U128),
2187 Self::Uint(UintTy::Usize),
2188 Self::Float(FloatTy::F32),
2189 Self::Float(FloatTy::F64),
2195 /// Like [`PrimTy::name`], but returns a &str instead of a symbol.
2198 pub fn name_str(self) -> &'static str {
2200 PrimTy::Int(i) => i.name_str(),
2201 PrimTy::Uint(u) => u.name_str(),
2202 PrimTy::Float(f) => f.name_str(),
2203 PrimTy::Str => "str",
2204 PrimTy::Bool => "bool",
2205 PrimTy::Char => "char",
2209 pub fn name(self) -> Symbol {
2211 PrimTy::Int(i) => i.name(),
2212 PrimTy::Uint(u) => u.name(),
2213 PrimTy::Float(f) => f.name(),
2214 PrimTy::Str => sym::str,
2215 PrimTy::Bool => sym::bool,
2216 PrimTy::Char => sym::char,
2220 /// Returns the matching `PrimTy` for a `Symbol` such as "str" or "i32".
2221 /// Returns `None` if no matching type is found.
2222 pub fn from_name(name: Symbol) -> Option<Self> {
2223 let ty = match name {
2224 // any changes here should also be reflected in `PrimTy::ALL`
2225 sym::i8 => Self::Int(IntTy::I8),
2226 sym::i16 => Self::Int(IntTy::I16),
2227 sym::i32 => Self::Int(IntTy::I32),
2228 sym::i64 => Self::Int(IntTy::I64),
2229 sym::i128 => Self::Int(IntTy::I128),
2230 sym::isize => Self::Int(IntTy::Isize),
2231 sym::u8 => Self::Uint(UintTy::U8),
2232 sym::u16 => Self::Uint(UintTy::U16),
2233 sym::u32 => Self::Uint(UintTy::U32),
2234 sym::u64 => Self::Uint(UintTy::U64),
2235 sym::u128 => Self::Uint(UintTy::U128),
2236 sym::usize => Self::Uint(UintTy::Usize),
2237 sym::f32 => Self::Float(FloatTy::F32),
2238 sym::f64 => Self::Float(FloatTy::F64),
2239 sym::bool => Self::Bool,
2240 sym::char => Self::Char,
2241 sym::str => Self::Str,
2248 #[derive(Debug, HashStable_Generic)]
2249 pub struct BareFnTy<'hir> {
2250 pub unsafety: Unsafety,
2252 pub generic_params: &'hir [GenericParam<'hir>],
2253 pub decl: &'hir FnDecl<'hir>,
2254 pub param_names: &'hir [Ident],
2257 #[derive(Debug, HashStable_Generic)]
2258 pub struct OpaqueTy<'hir> {
2259 pub generics: Generics<'hir>,
2260 pub bounds: GenericBounds<'hir>,
2261 pub impl_trait_fn: Option<DefId>,
2262 pub origin: OpaqueTyOrigin,
2265 /// From whence the opaque type came.
2266 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2267 pub enum OpaqueTyOrigin {
2272 /// `let _: impl Trait = ...`
2274 /// type aliases: `type Foo = impl Trait;`
2276 /// Impl trait consts, statics, bounds.
2280 /// The various kinds of types recognized by the compiler.
2281 #[derive(Debug, HashStable_Generic)]
2282 pub enum TyKind<'hir> {
2283 /// A variable length slice (i.e., `[T]`).
2284 Slice(&'hir Ty<'hir>),
2285 /// A fixed length array (i.e., `[T; n]`).
2286 Array(&'hir Ty<'hir>, AnonConst),
2287 /// A raw pointer (i.e., `*const T` or `*mut T`).
2289 /// A reference (i.e., `&'a T` or `&'a mut T`).
2290 Rptr(Lifetime, MutTy<'hir>),
2291 /// A bare function (e.g., `fn(usize) -> bool`).
2292 BareFn(&'hir BareFnTy<'hir>),
2293 /// The never type (`!`).
2295 /// A tuple (`(A, B, C, D, ...)`).
2296 Tup(&'hir [Ty<'hir>]),
2297 /// A path to a type definition (`module::module::...::Type`), or an
2298 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2300 /// Type parameters may be stored in each `PathSegment`.
2302 /// A opaque type definition itself. This is currently only used for the
2303 /// `opaque type Foo: Trait` item that `impl Trait` in desugars to.
2305 /// The generic argument list contains the lifetimes (and in the future
2306 /// possibly parameters) that are actually bound on the `impl Trait`.
2307 OpaqueDef(ItemId, &'hir [GenericArg<'hir>]),
2308 /// A trait object type `Bound1 + Bound2 + Bound3`
2309 /// where `Bound` is a trait or a lifetime.
2310 TraitObject(&'hir [PolyTraitRef<'hir>], Lifetime, TraitObjectSyntax),
2313 /// `TyKind::Infer` means the type should be inferred instead of it having been
2314 /// specified. This can appear anywhere in a type.
2316 /// Placeholder for a type that has failed to be defined.
2320 #[derive(Debug, HashStable_Generic)]
2321 pub enum InlineAsmOperand<'hir> {
2323 reg: InlineAsmRegOrRegClass,
2327 reg: InlineAsmRegOrRegClass,
2329 expr: Option<Expr<'hir>>,
2332 reg: InlineAsmRegOrRegClass,
2337 reg: InlineAsmRegOrRegClass,
2339 in_expr: Expr<'hir>,
2340 out_expr: Option<Expr<'hir>>,
2343 anon_const: AnonConst,
2350 impl<'hir> InlineAsmOperand<'hir> {
2351 pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
2353 Self::In { reg, .. }
2354 | Self::Out { reg, .. }
2355 | Self::InOut { reg, .. }
2356 | Self::SplitInOut { reg, .. } => Some(reg),
2357 Self::Const { .. } | Self::Sym { .. } => None,
2362 #[derive(Debug, HashStable_Generic)]
2363 pub struct InlineAsm<'hir> {
2364 pub template: &'hir [InlineAsmTemplatePiece],
2365 pub operands: &'hir [(InlineAsmOperand<'hir>, Span)],
2366 pub options: InlineAsmOptions,
2367 pub line_spans: &'hir [Span],
2370 #[derive(Copy, Clone, Encodable, Decodable, Debug, Hash, HashStable_Generic, PartialEq)]
2371 pub struct LlvmInlineAsmOutput {
2372 pub constraint: Symbol,
2374 pub is_indirect: bool,
2378 // NOTE(eddyb) This is used within MIR as well, so unlike the rest of the HIR,
2379 // it needs to be `Clone` and `Decodable` and use plain `Vec<T>` instead of
2380 // arena-allocated slice.
2381 #[derive(Clone, Encodable, Decodable, Debug, Hash, HashStable_Generic, PartialEq)]
2382 pub struct LlvmInlineAsmInner {
2384 pub asm_str_style: StrStyle,
2385 pub outputs: Vec<LlvmInlineAsmOutput>,
2386 pub inputs: Vec<Symbol>,
2387 pub clobbers: Vec<Symbol>,
2389 pub alignstack: bool,
2390 pub dialect: LlvmAsmDialect,
2393 #[derive(Debug, HashStable_Generic)]
2394 pub struct LlvmInlineAsm<'hir> {
2395 pub inner: LlvmInlineAsmInner,
2396 pub outputs_exprs: &'hir [Expr<'hir>],
2397 pub inputs_exprs: &'hir [Expr<'hir>],
2400 /// Represents a parameter in a function header.
2401 #[derive(Debug, HashStable_Generic)]
2402 pub struct Param<'hir> {
2404 pub pat: &'hir Pat<'hir>,
2409 /// Represents the header (not the body) of a function declaration.
2410 #[derive(Debug, HashStable_Generic)]
2411 pub struct FnDecl<'hir> {
2412 /// The types of the function's parameters.
2414 /// Additional argument data is stored in the function's [body](Body::params).
2415 pub inputs: &'hir [Ty<'hir>],
2416 pub output: FnRetTy<'hir>,
2417 pub c_variadic: bool,
2418 /// Does the function have an implicit self?
2419 pub implicit_self: ImplicitSelfKind,
2422 /// Represents what type of implicit self a function has, if any.
2423 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2424 pub enum ImplicitSelfKind {
2425 /// Represents a `fn x(self);`.
2427 /// Represents a `fn x(mut self);`.
2429 /// Represents a `fn x(&self);`.
2431 /// Represents a `fn x(&mut self);`.
2433 /// Represents when a function does not have a self argument or
2434 /// when a function has a `self: X` argument.
2438 impl ImplicitSelfKind {
2439 /// Does this represent an implicit self?
2440 pub fn has_implicit_self(&self) -> bool {
2441 !matches!(*self, ImplicitSelfKind::None)
2445 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable, Debug)]
2446 #[derive(HashStable_Generic)]
2452 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable, HashStable_Generic)]
2453 pub enum Defaultness {
2454 Default { has_value: bool },
2459 pub fn has_value(&self) -> bool {
2461 Defaultness::Default { has_value } => has_value,
2462 Defaultness::Final => true,
2466 pub fn is_final(&self) -> bool {
2467 *self == Defaultness::Final
2470 pub fn is_default(&self) -> bool {
2471 matches!(*self, Defaultness::Default { .. })
2475 #[derive(Debug, HashStable_Generic)]
2476 pub enum FnRetTy<'hir> {
2477 /// Return type is not specified.
2479 /// Functions default to `()` and
2480 /// closures default to inference. Span points to where return
2481 /// type would be inserted.
2482 DefaultReturn(Span),
2483 /// Everything else.
2484 Return(&'hir Ty<'hir>),
2488 pub fn span(&self) -> Span {
2490 Self::DefaultReturn(span) => span,
2491 Self::Return(ref ty) => ty.span,
2496 #[derive(Encodable, Debug)]
2497 pub struct Mod<'hir> {
2498 /// A span from the first token past `{` to the last token until `}`.
2499 /// For `mod foo;`, the inner span ranges from the first token
2500 /// to the last token in the external file.
2502 pub item_ids: &'hir [ItemId],
2505 #[derive(Debug, HashStable_Generic)]
2506 pub struct EnumDef<'hir> {
2507 pub variants: &'hir [Variant<'hir>],
2510 #[derive(Debug, HashStable_Generic)]
2511 pub struct Variant<'hir> {
2512 /// Name of the variant.
2513 #[stable_hasher(project(name))]
2515 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2517 /// Fields and constructor id of the variant.
2518 pub data: VariantData<'hir>,
2519 /// Explicit discriminant (e.g., `Foo = 1`).
2520 pub disr_expr: Option<AnonConst>,
2525 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2527 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2528 /// Also produced for each element of a list `use`, e.g.
2529 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2532 /// Glob import, e.g., `use foo::*`.
2535 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2536 /// an additional `use foo::{}` for performing checks such as
2537 /// unstable feature gating. May be removed in the future.
2541 /// References to traits in impls.
2543 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2544 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2545 /// trait being referred to but just a unique `HirId` that serves as a key
2546 /// within the resolution map.
2547 #[derive(Clone, Debug, HashStable_Generic)]
2548 pub struct TraitRef<'hir> {
2549 pub path: &'hir Path<'hir>,
2550 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2551 #[stable_hasher(ignore)]
2552 pub hir_ref_id: HirId,
2556 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2557 pub fn trait_def_id(&self) -> Option<DefId> {
2558 match self.path.res {
2559 Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
2561 _ => unreachable!(),
2566 #[derive(Clone, Debug, HashStable_Generic)]
2567 pub struct PolyTraitRef<'hir> {
2568 /// The `'a` in `for<'a> Foo<&'a T>`.
2569 pub bound_generic_params: &'hir [GenericParam<'hir>],
2571 /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
2572 pub trait_ref: TraitRef<'hir>,
2577 pub type Visibility<'hir> = Spanned<VisibilityKind<'hir>>;
2580 pub enum VisibilityKind<'hir> {
2583 Restricted { path: &'hir Path<'hir>, hir_id: HirId },
2587 impl VisibilityKind<'_> {
2588 pub fn is_pub(&self) -> bool {
2589 matches!(*self, VisibilityKind::Public)
2592 pub fn is_pub_restricted(&self) -> bool {
2594 VisibilityKind::Public | VisibilityKind::Inherited => false,
2595 VisibilityKind::Crate(..) | VisibilityKind::Restricted { .. } => true,
2600 #[derive(Debug, HashStable_Generic)]
2601 pub struct FieldDef<'hir> {
2603 #[stable_hasher(project(name))]
2605 pub vis: Visibility<'hir>,
2607 pub ty: &'hir Ty<'hir>,
2611 // Still necessary in couple of places
2612 pub fn is_positional(&self) -> bool {
2613 let first = self.ident.as_str().as_bytes()[0];
2614 (b'0'..=b'9').contains(&first)
2618 /// Fields and constructor IDs of enum variants and structs.
2619 #[derive(Debug, HashStable_Generic)]
2620 pub enum VariantData<'hir> {
2621 /// A struct variant.
2623 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2624 Struct(&'hir [FieldDef<'hir>], /* recovered */ bool),
2625 /// A tuple variant.
2627 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2628 Tuple(&'hir [FieldDef<'hir>], HirId),
2631 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2635 impl VariantData<'hir> {
2636 /// Return the fields of this variant.
2637 pub fn fields(&self) -> &'hir [FieldDef<'hir>] {
2639 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2644 /// Return the `HirId` of this variant's constructor, if it has one.
2645 pub fn ctor_hir_id(&self) -> Option<HirId> {
2647 VariantData::Struct(_, _) => None,
2648 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2653 // The bodies for items are stored "out of line", in a separate
2654 // hashmap in the `Crate`. Here we just record the hir-id of the item
2655 // so it can fetched later.
2656 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug, Hash)]
2658 pub def_id: LocalDefId,
2663 pub fn hir_id(&self) -> HirId {
2664 // Items are always HIR owners.
2665 HirId::make_owner(self.def_id)
2671 /// The name might be a dummy name in case of anonymous items
2673 pub struct Item<'hir> {
2675 pub def_id: LocalDefId,
2676 pub kind: ItemKind<'hir>,
2677 pub vis: Visibility<'hir>,
2683 pub fn hir_id(&self) -> HirId {
2684 // Items are always HIR owners.
2685 HirId::make_owner(self.def_id)
2688 pub fn item_id(&self) -> ItemId {
2689 ItemId { def_id: self.def_id }
2693 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2694 #[derive(Encodable, Decodable, HashStable_Generic)]
2701 pub fn prefix_str(&self) -> &'static str {
2703 Self::Unsafe => "unsafe ",
2709 impl fmt::Display for Unsafety {
2710 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2711 f.write_str(match *self {
2712 Self::Unsafe => "unsafe",
2713 Self::Normal => "normal",
2718 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2719 #[derive(Encodable, Decodable, HashStable_Generic)]
2720 pub enum Constness {
2725 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2726 pub struct FnHeader {
2727 pub unsafety: Unsafety,
2728 pub constness: Constness,
2729 pub asyncness: IsAsync,
2734 pub fn is_const(&self) -> bool {
2735 matches!(&self.constness, Constness::Const)
2739 #[derive(Debug, HashStable_Generic)]
2740 pub enum ItemKind<'hir> {
2741 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2743 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2744 ExternCrate(Option<Symbol>),
2746 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2750 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2751 Use(&'hir Path<'hir>, UseKind),
2753 /// A `static` item.
2754 Static(&'hir Ty<'hir>, Mutability, BodyId),
2756 Const(&'hir Ty<'hir>, BodyId),
2757 /// A function declaration.
2758 Fn(FnSig<'hir>, Generics<'hir>, BodyId),
2761 /// An external module, e.g. `extern { .. }`.
2762 ForeignMod { abi: Abi, items: &'hir [ForeignItemRef<'hir>] },
2763 /// Module-level inline assembly (from `global_asm!`).
2764 GlobalAsm(&'hir InlineAsm<'hir>),
2765 /// A type alias, e.g., `type Foo = Bar<u8>`.
2766 TyAlias(&'hir Ty<'hir>, Generics<'hir>),
2767 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2768 OpaqueTy(OpaqueTy<'hir>),
2769 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2770 Enum(EnumDef<'hir>, Generics<'hir>),
2771 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2772 Struct(VariantData<'hir>, Generics<'hir>),
2773 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2774 Union(VariantData<'hir>, Generics<'hir>),
2775 /// A trait definition.
2776 Trait(IsAuto, Unsafety, Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
2778 TraitAlias(Generics<'hir>, GenericBounds<'hir>),
2780 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2784 #[derive(Debug, HashStable_Generic)]
2785 pub struct Impl<'hir> {
2786 pub unsafety: Unsafety,
2787 pub polarity: ImplPolarity,
2788 pub defaultness: Defaultness,
2789 // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata
2790 // decoding as `Span`s cannot be decoded when a `Session` is not available.
2791 pub defaultness_span: Option<Span>,
2792 pub constness: Constness,
2793 pub generics: Generics<'hir>,
2795 /// The trait being implemented, if any.
2796 pub of_trait: Option<TraitRef<'hir>>,
2798 pub self_ty: &'hir Ty<'hir>,
2799 pub items: &'hir [ImplItemRef<'hir>],
2803 pub fn generics(&self) -> Option<&Generics<'_>> {
2805 ItemKind::Fn(_, ref generics, _)
2806 | ItemKind::TyAlias(_, ref generics)
2807 | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
2808 | ItemKind::Enum(_, ref generics)
2809 | ItemKind::Struct(_, ref generics)
2810 | ItemKind::Union(_, ref generics)
2811 | ItemKind::Trait(_, _, ref generics, _, _)
2812 | ItemKind::Impl(Impl { ref generics, .. }) => generics,
2818 /// A reference from an trait to one of its associated items. This
2819 /// contains the item's id, naturally, but also the item's name and
2820 /// some other high-level details (like whether it is an associated
2821 /// type or method, and whether it is public). This allows other
2822 /// passes to find the impl they want without loading the ID (which
2823 /// means fewer edges in the incremental compilation graph).
2824 #[derive(Encodable, Debug, HashStable_Generic)]
2825 pub struct TraitItemRef {
2826 pub id: TraitItemId,
2827 #[stable_hasher(project(name))]
2829 pub kind: AssocItemKind,
2831 pub defaultness: Defaultness,
2834 /// A reference from an impl to one of its associated items. This
2835 /// contains the item's ID, naturally, but also the item's name and
2836 /// some other high-level details (like whether it is an associated
2837 /// type or method, and whether it is public). This allows other
2838 /// passes to find the impl they want without loading the ID (which
2839 /// means fewer edges in the incremental compilation graph).
2840 #[derive(Debug, HashStable_Generic)]
2841 pub struct ImplItemRef<'hir> {
2843 #[stable_hasher(project(name))]
2845 pub kind: AssocItemKind,
2847 pub vis: Visibility<'hir>,
2848 pub defaultness: Defaultness,
2851 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2852 pub enum AssocItemKind {
2854 Fn { has_self: bool },
2858 // The bodies for items are stored "out of line", in a separate
2859 // hashmap in the `Crate`. Here we just record the hir-id of the item
2860 // so it can fetched later.
2861 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
2862 pub struct ForeignItemId {
2863 pub def_id: LocalDefId,
2866 impl ForeignItemId {
2868 pub fn hir_id(&self) -> HirId {
2869 // Items are always HIR owners.
2870 HirId::make_owner(self.def_id)
2874 /// A reference from a foreign block to one of its items. This
2875 /// contains the item's ID, naturally, but also the item's name and
2876 /// some other high-level details (like whether it is an associated
2877 /// type or method, and whether it is public). This allows other
2878 /// passes to find the impl they want without loading the ID (which
2879 /// means fewer edges in the incremental compilation graph).
2880 #[derive(Debug, HashStable_Generic)]
2881 pub struct ForeignItemRef<'hir> {
2882 pub id: ForeignItemId,
2883 #[stable_hasher(project(name))]
2886 pub vis: Visibility<'hir>,
2890 pub struct ForeignItem<'hir> {
2892 pub kind: ForeignItemKind<'hir>,
2893 pub def_id: LocalDefId,
2895 pub vis: Visibility<'hir>,
2898 impl ForeignItem<'_> {
2900 pub fn hir_id(&self) -> HirId {
2901 // Items are always HIR owners.
2902 HirId::make_owner(self.def_id)
2905 pub fn foreign_item_id(&self) -> ForeignItemId {
2906 ForeignItemId { def_id: self.def_id }
2910 /// An item within an `extern` block.
2911 #[derive(Debug, HashStable_Generic)]
2912 pub enum ForeignItemKind<'hir> {
2913 /// A foreign function.
2914 Fn(&'hir FnDecl<'hir>, &'hir [Ident], Generics<'hir>),
2915 /// A foreign static item (`static ext: u8`).
2916 Static(&'hir Ty<'hir>, Mutability),
2921 /// A variable captured by a closure.
2922 #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)]
2924 // First span where it is accessed (there can be multiple).
2928 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2929 // has length > 0 if the trait is found through an chain of imports, starting with the
2930 // import/use statement in the scope where the trait is used.
2931 #[derive(Encodable, Decodable, Clone, Debug)]
2932 pub struct TraitCandidate {
2934 pub import_ids: SmallVec<[LocalDefId; 1]>,
2937 #[derive(Copy, Clone, Debug, HashStable_Generic)]
2938 pub enum Node<'hir> {
2939 Param(&'hir Param<'hir>),
2940 Item(&'hir Item<'hir>),
2941 ForeignItem(&'hir ForeignItem<'hir>),
2942 TraitItem(&'hir TraitItem<'hir>),
2943 ImplItem(&'hir ImplItem<'hir>),
2944 Variant(&'hir Variant<'hir>),
2945 Field(&'hir FieldDef<'hir>),
2946 AnonConst(&'hir AnonConst),
2947 Expr(&'hir Expr<'hir>),
2948 Stmt(&'hir Stmt<'hir>),
2949 PathSegment(&'hir PathSegment<'hir>),
2951 TraitRef(&'hir TraitRef<'hir>),
2952 Binding(&'hir Pat<'hir>),
2953 Pat(&'hir Pat<'hir>),
2954 Arm(&'hir Arm<'hir>),
2955 Block(&'hir Block<'hir>),
2956 Local(&'hir Local<'hir>),
2957 MacroDef(&'hir MacroDef<'hir>),
2959 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
2960 /// with synthesized constructors.
2961 Ctor(&'hir VariantData<'hir>),
2963 Lifetime(&'hir Lifetime),
2964 GenericParam(&'hir GenericParam<'hir>),
2965 Visibility(&'hir Visibility<'hir>),
2967 Crate(&'hir Mod<'hir>),
2970 impl<'hir> Node<'hir> {
2971 pub fn ident(&self) -> Option<Ident> {
2973 Node::TraitItem(TraitItem { ident, .. })
2974 | Node::ImplItem(ImplItem { ident, .. })
2975 | Node::ForeignItem(ForeignItem { ident, .. })
2976 | Node::Field(FieldDef { ident, .. })
2977 | Node::Variant(Variant { ident, .. })
2978 | Node::MacroDef(MacroDef { ident, .. })
2979 | Node::Item(Item { ident, .. }) => Some(*ident),
2984 pub fn fn_decl(&self) -> Option<&FnDecl<'hir>> {
2986 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
2987 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
2988 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
2989 Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
2996 pub fn body_id(&self) -> Option<BodyId> {
2998 Node::TraitItem(TraitItem {
2999 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3002 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3003 | Node::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3008 pub fn generics(&self) -> Option<&'hir Generics<'hir>> {
3010 Node::TraitItem(TraitItem { generics, .. })
3011 | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
3012 Node::Item(item) => item.kind.generics(),
3017 pub fn hir_id(&self) -> Option<HirId> {
3019 Node::Item(Item { def_id, .. })
3020 | Node::TraitItem(TraitItem { def_id, .. })
3021 | Node::ImplItem(ImplItem { def_id, .. })
3022 | Node::ForeignItem(ForeignItem { def_id, .. })
3023 | Node::MacroDef(MacroDef { def_id, .. }) => Some(HirId::make_owner(*def_id)),
3024 Node::Field(FieldDef { hir_id, .. })
3025 | Node::AnonConst(AnonConst { hir_id, .. })
3026 | Node::Expr(Expr { hir_id, .. })
3027 | Node::Stmt(Stmt { hir_id, .. })
3028 | Node::Ty(Ty { hir_id, .. })
3029 | Node::Binding(Pat { hir_id, .. })
3030 | Node::Pat(Pat { hir_id, .. })
3031 | Node::Arm(Arm { hir_id, .. })
3032 | Node::Block(Block { hir_id, .. })
3033 | Node::Local(Local { hir_id, .. })
3034 | Node::Lifetime(Lifetime { hir_id, .. })
3035 | Node::Param(Param { hir_id, .. })
3036 | Node::GenericParam(GenericParam { hir_id, .. }) => Some(*hir_id),
3037 Node::TraitRef(TraitRef { hir_ref_id, .. }) => Some(*hir_ref_id),
3038 Node::PathSegment(PathSegment { hir_id, .. }) => *hir_id,
3039 Node::Variant(Variant { id, .. }) => Some(*id),
3040 Node::Ctor(variant) => variant.ctor_hir_id(),
3041 Node::Crate(_) | Node::Visibility(_) => None,
3046 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3047 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
3049 rustc_data_structures::static_assert_size!(super::Block<'static>, 48);
3050 rustc_data_structures::static_assert_size!(super::Expr<'static>, 64);
3051 rustc_data_structures::static_assert_size!(super::Pat<'static>, 88);
3052 rustc_data_structures::static_assert_size!(super::QPath<'static>, 24);
3053 rustc_data_structures::static_assert_size!(super::Ty<'static>, 72);
3055 rustc_data_structures::static_assert_size!(super::Item<'static>, 184);
3056 rustc_data_structures::static_assert_size!(super::TraitItem<'static>, 128);
3057 rustc_data_structures::static_assert_size!(super::ImplItem<'static>, 152);
3058 rustc_data_structures::static_assert_size!(super::ForeignItem<'static>, 136);