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::{SourceMap, 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(_) => ast::ParamKindOrd::Const { unordered: feats.const_generics },
304 #[derive(Debug, HashStable_Generic)]
305 pub struct GenericArgs<'hir> {
306 /// The generic arguments for this path segment.
307 pub args: &'hir [GenericArg<'hir>],
308 /// Bindings (equality constraints) on associated types, if present.
309 /// E.g., `Foo<A = Bar>`.
310 pub bindings: &'hir [TypeBinding<'hir>],
311 /// Were arguments written in parenthesized form `Fn(T) -> U`?
312 /// This is required mostly for pretty-printing and diagnostics,
313 /// but also for changing lifetime elision rules to be "function-like".
314 pub parenthesized: bool,
317 impl GenericArgs<'_> {
318 pub const fn none() -> Self {
319 Self { args: &[], bindings: &[], parenthesized: false }
322 pub fn inputs(&self) -> &[Ty<'_>] {
323 if self.parenthesized {
324 for arg in self.args {
326 GenericArg::Lifetime(_) => {}
327 GenericArg::Type(ref ty) => {
328 if let TyKind::Tup(ref tys) = ty.kind {
333 GenericArg::Const(_) => {}
337 panic!("GenericArgs::inputs: not a `Fn(T) -> U`");
340 pub fn own_counts(&self) -> GenericParamCount {
341 // We could cache this as a property of `GenericParamCount`, but
342 // the aim is to refactor this away entirely eventually and the
343 // presence of this method will be a constant reminder.
344 let mut own_counts: GenericParamCount = Default::default();
346 for arg in self.args {
348 GenericArg::Lifetime(_) => own_counts.lifetimes += 1,
349 GenericArg::Type(_) => own_counts.types += 1,
350 GenericArg::Const(_) => own_counts.consts += 1,
357 pub fn span(&self) -> Option<Span> {
360 .filter(|arg| !arg.is_synthetic())
361 .map(|arg| arg.span())
362 .reduce(|span1, span2| span1.to(span2))
365 /// Returns span encompassing arguments and their surrounding `<>` or `()`
366 pub fn span_ext(&self, sm: &SourceMap) -> Option<Span> {
367 let mut span = self.span()?;
369 let (o, c) = if self.parenthesized { ('(', ')') } else { ('<', '>') };
371 if let Ok(snippet) = sm.span_to_snippet(span) {
372 let snippet = snippet.as_bytes();
374 if snippet[0] != (o as u8) || snippet[snippet.len() - 1] != (c as u8) {
375 span = sm.span_extend_to_prev_char(span, o, true);
376 span = span.with_lo(span.lo() - BytePos(1));
378 span = sm.span_extend_to_next_char(span, c, true);
379 span = span.with_hi(span.hi() + BytePos(1));
386 pub fn is_empty(&self) -> bool {
391 /// A modifier on a bound, currently this is only used for `?Sized`, where the
392 /// modifier is `Maybe`. Negative bounds should also be handled here.
393 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
394 #[derive(HashStable_Generic)]
395 pub enum TraitBoundModifier {
401 /// The AST represents all type param bounds as types.
402 /// `typeck::collect::compute_bounds` matches these against
403 /// the "special" built-in traits (see `middle::lang_items`) and
404 /// detects `Copy`, `Send` and `Sync`.
405 #[derive(Debug, HashStable_Generic)]
406 pub enum GenericBound<'hir> {
407 Trait(PolyTraitRef<'hir>, TraitBoundModifier),
408 // FIXME(davidtwco): Introduce `PolyTraitRef::LangItem`
409 LangItemTrait(LangItem, Span, HirId, &'hir GenericArgs<'hir>),
413 impl GenericBound<'_> {
414 pub fn trait_ref(&self) -> Option<&TraitRef<'_>> {
416 GenericBound::Trait(data, _) => Some(&data.trait_ref),
421 pub fn span(&self) -> Span {
423 GenericBound::Trait(t, ..) => t.span,
424 GenericBound::LangItemTrait(_, span, ..) => *span,
425 GenericBound::Outlives(l) => l.span,
430 pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
432 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
433 pub enum LifetimeParamKind {
434 // Indicates that the lifetime definition was explicitly declared (e.g., in
435 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
438 // Indicates that the lifetime definition was synthetically added
439 // as a result of an in-band lifetime usage (e.g., in
440 // `fn foo(x: &'a u8) -> &'a u8 { x }`).
443 // Indication that the lifetime was elided (e.g., in both cases in
444 // `fn foo(x: &u8) -> &'_ u8 { x }`).
447 // Indication that the lifetime name was somehow in error.
451 #[derive(Debug, HashStable_Generic)]
452 pub enum GenericParamKind<'hir> {
453 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
455 kind: LifetimeParamKind,
458 default: Option<&'hir Ty<'hir>>,
459 synthetic: Option<SyntheticTyParamKind>,
463 /// Optional default value for the const generic param
464 default: Option<AnonConst>,
468 #[derive(Debug, HashStable_Generic)]
469 pub struct GenericParam<'hir> {
472 pub bounds: GenericBounds<'hir>,
474 pub pure_wrt_drop: bool,
475 pub kind: GenericParamKind<'hir>,
478 impl GenericParam<'hir> {
479 pub fn bounds_span(&self) -> Option<Span> {
480 self.bounds.iter().fold(None, |span, bound| {
481 let span = span.map(|s| s.to(bound.span())).unwrap_or_else(|| bound.span());
489 pub struct GenericParamCount {
490 pub lifetimes: usize,
495 /// Represents lifetimes and type parameters attached to a declaration
496 /// of a function, enum, trait, etc.
497 #[derive(Debug, HashStable_Generic)]
498 pub struct Generics<'hir> {
499 pub params: &'hir [GenericParam<'hir>],
500 pub where_clause: WhereClause<'hir>,
504 impl Generics<'hir> {
505 pub const fn empty() -> Generics<'hir> {
508 where_clause: WhereClause { predicates: &[], span: DUMMY_SP },
513 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'_>> {
514 for param in self.params {
515 if name == param.name.ident().name {
522 pub fn spans(&self) -> MultiSpan {
523 if self.params.is_empty() {
526 self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
531 /// Synthetic type parameters are converted to another form during lowering; this allows
532 /// us to track the original form they had, and is useful for error messages.
533 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
534 #[derive(HashStable_Generic)]
535 pub enum SyntheticTyParamKind {
537 // Created by the `#[rustc_synthetic]` attribute.
541 /// A where-clause in a definition.
542 #[derive(Debug, HashStable_Generic)]
543 pub struct WhereClause<'hir> {
544 pub predicates: &'hir [WherePredicate<'hir>],
545 // Only valid if predicates aren't empty.
549 impl WhereClause<'_> {
550 pub fn span(&self) -> Option<Span> {
551 if self.predicates.is_empty() { None } else { Some(self.span) }
554 /// The `WhereClause` under normal circumstances points at either the predicates or the empty
555 /// space where the `where` clause should be. Only of use for diagnostic suggestions.
556 pub fn span_for_predicates_or_empty_place(&self) -> Span {
560 /// `Span` where further predicates would be suggested, accounting for trailing commas, like
561 /// in `fn foo<T>(t: T) where T: Foo,` so we don't suggest two trailing commas.
562 pub fn tail_span_for_suggestion(&self) -> Span {
563 let end = self.span_for_predicates_or_empty_place().shrink_to_hi();
564 self.predicates.last().map_or(end, |p| p.span()).shrink_to_hi().to(end)
568 /// A single predicate in a where-clause.
569 #[derive(Debug, HashStable_Generic)]
570 pub enum WherePredicate<'hir> {
571 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
572 BoundPredicate(WhereBoundPredicate<'hir>),
573 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
574 RegionPredicate(WhereRegionPredicate<'hir>),
575 /// An equality predicate (unsupported).
576 EqPredicate(WhereEqPredicate<'hir>),
579 impl WherePredicate<'_> {
580 pub fn span(&self) -> Span {
582 WherePredicate::BoundPredicate(p) => p.span,
583 WherePredicate::RegionPredicate(p) => p.span,
584 WherePredicate::EqPredicate(p) => p.span,
589 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
590 #[derive(Debug, HashStable_Generic)]
591 pub struct WhereBoundPredicate<'hir> {
593 /// Any generics from a `for` binding.
594 pub bound_generic_params: &'hir [GenericParam<'hir>],
595 /// The type being bounded.
596 pub bounded_ty: &'hir Ty<'hir>,
597 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
598 pub bounds: GenericBounds<'hir>,
601 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
602 #[derive(Debug, HashStable_Generic)]
603 pub struct WhereRegionPredicate<'hir> {
605 pub lifetime: Lifetime,
606 pub bounds: GenericBounds<'hir>,
609 /// An equality predicate (e.g., `T = int`); currently unsupported.
610 #[derive(Debug, HashStable_Generic)]
611 pub struct WhereEqPredicate<'hir> {
614 pub lhs_ty: &'hir Ty<'hir>,
615 pub rhs_ty: &'hir Ty<'hir>,
618 #[derive(Default, Encodable, Debug, HashStable_Generic)]
619 pub struct ModuleItems {
620 // Use BTreeSets here so items are in the same order as in the
621 // list of all items in Crate
622 pub items: BTreeSet<ItemId>,
623 pub trait_items: BTreeSet<TraitItemId>,
624 pub impl_items: BTreeSet<ImplItemId>,
625 pub foreign_items: BTreeSet<ForeignItemId>,
628 /// A type representing only the top-level module.
629 #[derive(Encodable, Debug, HashStable_Generic)]
630 pub struct CrateItem<'hir> {
631 pub module: Mod<'hir>,
635 /// The top-level data structure that stores the entire contents of
636 /// the crate currently being compiled.
638 /// For more details, see the [rustc dev guide].
640 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
642 pub struct Crate<'hir> {
643 pub item: CrateItem<'hir>,
644 pub exported_macros: &'hir [MacroDef<'hir>],
645 // Attributes from non-exported macros, kept only for collecting the library feature list.
646 pub non_exported_macro_attrs: &'hir [Attribute],
648 // N.B., we use a `BTreeMap` here so that `visit_all_items` iterates
649 // over the ids in increasing order. In principle it should not
650 // matter what order we visit things in, but in *practice* it
651 // does, because it can affect the order in which errors are
652 // detected, which in turn can make UI tests yield
653 // slightly different results.
654 pub items: BTreeMap<ItemId, Item<'hir>>,
656 pub trait_items: BTreeMap<TraitItemId, TraitItem<'hir>>,
657 pub impl_items: BTreeMap<ImplItemId, ImplItem<'hir>>,
658 pub foreign_items: BTreeMap<ForeignItemId, ForeignItem<'hir>>,
659 pub bodies: BTreeMap<BodyId, Body<'hir>>,
660 pub trait_impls: BTreeMap<DefId, Vec<LocalDefId>>,
662 /// A list of the body ids written out in the order in which they
663 /// appear in the crate. If you're going to process all the bodies
664 /// in the crate, you should iterate over this list rather than the keys
666 pub body_ids: Vec<BodyId>,
668 /// A list of modules written out in the order in which they
669 /// appear in the crate. This includes the main crate module.
670 pub modules: BTreeMap<LocalDefId, ModuleItems>,
671 /// A list of proc macro HirIds, written out in the order in which
672 /// they are declared in the static array generated by proc_macro_harness.
673 pub proc_macros: Vec<HirId>,
675 pub trait_map: BTreeMap<HirId, Vec<TraitCandidate>>,
677 /// Collected attributes from HIR nodes.
678 pub attrs: BTreeMap<HirId, &'hir [Attribute]>,
682 pub fn item(&self, id: ItemId) -> &Item<'hir> {
686 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem<'hir> {
687 &self.trait_items[&id]
690 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem<'hir> {
691 &self.impl_items[&id]
694 pub fn foreign_item(&self, id: ForeignItemId) -> &ForeignItem<'hir> {
695 &self.foreign_items[&id]
698 pub fn body(&self, id: BodyId) -> &Body<'hir> {
704 /// Visits all items in the crate in some deterministic (but
705 /// unspecified) order. If you just need to process every item,
706 /// but don't care about nesting, this method is the best choice.
708 /// If you do care about nesting -- usually because your algorithm
709 /// follows lexical scoping rules -- then you want a different
710 /// approach. You should override `visit_nested_item` in your
711 /// visitor and then call `intravisit::walk_crate` instead.
712 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
714 V: itemlikevisit::ItemLikeVisitor<'hir>,
716 for item in self.items.values() {
717 visitor.visit_item(item);
720 for trait_item in self.trait_items.values() {
721 visitor.visit_trait_item(trait_item);
724 for impl_item in self.impl_items.values() {
725 visitor.visit_impl_item(impl_item);
728 for foreign_item in self.foreign_items.values() {
729 visitor.visit_foreign_item(foreign_item);
733 /// A parallel version of `visit_all_item_likes`.
734 pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
736 V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send,
740 par_for_each_in(&self.items, |(_, item)| {
741 visitor.visit_item(item);
745 par_for_each_in(&self.trait_items, |(_, trait_item)| {
746 visitor.visit_trait_item(trait_item);
750 par_for_each_in(&self.impl_items, |(_, impl_item)| {
751 visitor.visit_impl_item(impl_item);
755 par_for_each_in(&self.foreign_items, |(_, foreign_item)| {
756 visitor.visit_foreign_item(foreign_item);
763 /// A macro definition, in this crate or imported from another.
765 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
767 pub struct MacroDef<'hir> {
769 pub vis: Visibility<'hir>,
770 pub def_id: LocalDefId,
772 pub ast: ast::MacroDef,
777 pub fn hir_id(&self) -> HirId {
778 HirId::make_owner(self.def_id)
782 /// A block of statements `{ .. }`, which may have a label (in this case the
783 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
784 /// the `rules` being anything but `DefaultBlock`.
785 #[derive(Debug, HashStable_Generic)]
786 pub struct Block<'hir> {
787 /// Statements in a block.
788 pub stmts: &'hir [Stmt<'hir>],
789 /// An expression at the end of the block
790 /// without a semicolon, if any.
791 pub expr: Option<&'hir Expr<'hir>>,
792 #[stable_hasher(ignore)]
794 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
795 pub rules: BlockCheckMode,
797 /// If true, then there may exist `break 'a` values that aim to
798 /// break out of this block early.
799 /// Used by `'label: {}` blocks and by `try {}` blocks.
800 pub targeted_by_break: bool,
803 #[derive(Debug, HashStable_Generic)]
804 pub struct Pat<'hir> {
805 #[stable_hasher(ignore)]
807 pub kind: PatKind<'hir>,
809 // Whether to use default binding modes.
810 // At present, this is false only for destructuring assignment.
811 pub default_binding_modes: bool,
814 impl<'hir> Pat<'hir> {
815 // FIXME(#19596) this is a workaround, but there should be a better way
816 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) -> bool {
823 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
824 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
825 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
826 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
827 Slice(before, slice, after) => {
828 before.iter().chain(slice.iter()).chain(after.iter()).all(|p| p.walk_short_(it))
833 /// Walk the pattern in left-to-right order,
834 /// short circuiting (with `.all(..)`) if `false` is returned.
836 /// Note that when visiting e.g. `Tuple(ps)`,
837 /// if visiting `ps[0]` returns `false`,
838 /// then `ps[1]` will not be visited.
839 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) -> bool {
840 self.walk_short_(&mut it)
843 // FIXME(#19596) this is a workaround, but there should be a better way
844 fn walk_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) {
851 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
852 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
853 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
854 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
855 Slice(before, slice, after) => {
856 before.iter().chain(slice.iter()).chain(after.iter()).for_each(|p| p.walk_(it))
861 /// Walk the pattern in left-to-right order.
863 /// If `it(pat)` returns `false`, the children are not visited.
864 pub fn walk(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) {
868 /// Walk the pattern in left-to-right order.
870 /// If you always want to recurse, prefer this method over `walk`.
871 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
879 /// A single field in a struct pattern.
881 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
882 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
883 /// except `is_shorthand` is true.
884 #[derive(Debug, HashStable_Generic)]
885 pub struct PatField<'hir> {
886 #[stable_hasher(ignore)]
888 /// The identifier for the field.
889 #[stable_hasher(project(name))]
891 /// The pattern the field is destructured to.
892 pub pat: &'hir Pat<'hir>,
893 pub is_shorthand: bool,
897 /// Explicit binding annotations given in the HIR for a binding. Note
898 /// that this is not the final binding *mode* that we infer after type
900 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
901 pub enum BindingAnnotation {
902 /// No binding annotation given: this means that the final binding mode
903 /// will depend on whether we have skipped through a `&` reference
904 /// when matching. For example, the `x` in `Some(x)` will have binding
905 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
906 /// ultimately be inferred to be by-reference.
908 /// Note that implicit reference skipping is not implemented yet (#42640).
911 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
914 /// Annotated as `ref`, like `ref x`
917 /// Annotated as `ref mut x`.
921 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
927 impl fmt::Display for RangeEnd {
928 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
929 f.write_str(match self {
930 RangeEnd::Included => "..=",
931 RangeEnd::Excluded => "..",
936 #[derive(Debug, HashStable_Generic)]
937 pub enum PatKind<'hir> {
938 /// Represents a wildcard pattern (i.e., `_`).
941 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
942 /// The `HirId` is the canonical ID for the variable being bound,
943 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
944 /// which is the pattern ID of the first `x`.
945 Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
947 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
948 /// The `bool` is `true` in the presence of a `..`.
949 Struct(QPath<'hir>, &'hir [PatField<'hir>], bool),
951 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
952 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
953 /// `0 <= position <= subpats.len()`
954 TupleStruct(QPath<'hir>, &'hir [&'hir Pat<'hir>], Option<usize>),
956 /// An or-pattern `A | B | C`.
957 /// Invariant: `pats.len() >= 2`.
958 Or(&'hir [&'hir Pat<'hir>]),
960 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
963 /// A tuple pattern (e.g., `(a, b)`).
964 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
965 /// `0 <= position <= subpats.len()`
966 Tuple(&'hir [&'hir Pat<'hir>], Option<usize>),
969 Box(&'hir Pat<'hir>),
971 /// A reference pattern (e.g., `&mut (a, b)`).
972 Ref(&'hir Pat<'hir>, Mutability),
975 Lit(&'hir Expr<'hir>),
977 /// A range pattern (e.g., `1..=2` or `1..2`).
978 Range(Option<&'hir Expr<'hir>>, Option<&'hir Expr<'hir>>, RangeEnd),
980 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
982 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
983 /// If `slice` exists, then `after` can be non-empty.
985 /// The representation for e.g., `[a, b, .., c, d]` is:
987 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
989 Slice(&'hir [&'hir Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [&'hir Pat<'hir>]),
992 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
994 /// The `+` operator (addition).
996 /// The `-` operator (subtraction).
998 /// The `*` operator (multiplication).
1000 /// The `/` operator (division).
1002 /// The `%` operator (modulus).
1004 /// The `&&` operator (logical and).
1006 /// The `||` operator (logical or).
1008 /// The `^` operator (bitwise xor).
1010 /// The `&` operator (bitwise and).
1012 /// The `|` operator (bitwise or).
1014 /// The `<<` operator (shift left).
1016 /// The `>>` operator (shift right).
1018 /// The `==` operator (equality).
1020 /// The `<` operator (less than).
1022 /// The `<=` operator (less than or equal to).
1024 /// The `!=` operator (not equal to).
1026 /// The `>=` operator (greater than or equal to).
1028 /// The `>` operator (greater than).
1033 pub fn as_str(self) -> &'static str {
1035 BinOpKind::Add => "+",
1036 BinOpKind::Sub => "-",
1037 BinOpKind::Mul => "*",
1038 BinOpKind::Div => "/",
1039 BinOpKind::Rem => "%",
1040 BinOpKind::And => "&&",
1041 BinOpKind::Or => "||",
1042 BinOpKind::BitXor => "^",
1043 BinOpKind::BitAnd => "&",
1044 BinOpKind::BitOr => "|",
1045 BinOpKind::Shl => "<<",
1046 BinOpKind::Shr => ">>",
1047 BinOpKind::Eq => "==",
1048 BinOpKind::Lt => "<",
1049 BinOpKind::Le => "<=",
1050 BinOpKind::Ne => "!=",
1051 BinOpKind::Ge => ">=",
1052 BinOpKind::Gt => ">",
1056 pub fn is_lazy(self) -> bool {
1057 matches!(self, BinOpKind::And | BinOpKind::Or)
1060 pub fn is_shift(self) -> bool {
1061 matches!(self, BinOpKind::Shl | BinOpKind::Shr)
1064 pub fn is_comparison(self) -> bool {
1071 | BinOpKind::Ge => true,
1083 | BinOpKind::Shr => false,
1087 /// Returns `true` if the binary operator takes its arguments by value.
1088 pub fn is_by_value(self) -> bool {
1089 !self.is_comparison()
1093 impl Into<ast::BinOpKind> for BinOpKind {
1094 fn into(self) -> ast::BinOpKind {
1096 BinOpKind::Add => ast::BinOpKind::Add,
1097 BinOpKind::Sub => ast::BinOpKind::Sub,
1098 BinOpKind::Mul => ast::BinOpKind::Mul,
1099 BinOpKind::Div => ast::BinOpKind::Div,
1100 BinOpKind::Rem => ast::BinOpKind::Rem,
1101 BinOpKind::And => ast::BinOpKind::And,
1102 BinOpKind::Or => ast::BinOpKind::Or,
1103 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1104 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1105 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1106 BinOpKind::Shl => ast::BinOpKind::Shl,
1107 BinOpKind::Shr => ast::BinOpKind::Shr,
1108 BinOpKind::Eq => ast::BinOpKind::Eq,
1109 BinOpKind::Lt => ast::BinOpKind::Lt,
1110 BinOpKind::Le => ast::BinOpKind::Le,
1111 BinOpKind::Ne => ast::BinOpKind::Ne,
1112 BinOpKind::Ge => ast::BinOpKind::Ge,
1113 BinOpKind::Gt => ast::BinOpKind::Gt,
1118 pub type BinOp = Spanned<BinOpKind>;
1120 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1122 /// The `*` operator (deferencing).
1124 /// The `!` operator (logical negation).
1126 /// The `-` operator (negation).
1131 pub fn as_str(self) -> &'static str {
1139 /// Returns `true` if the unary operator takes its argument by value.
1140 pub fn is_by_value(self) -> bool {
1141 matches!(self, Self::Neg | Self::Not)
1146 #[derive(Debug, HashStable_Generic)]
1147 pub struct Stmt<'hir> {
1149 pub kind: StmtKind<'hir>,
1153 /// The contents of a statement.
1154 #[derive(Debug, HashStable_Generic)]
1155 pub enum StmtKind<'hir> {
1156 /// A local (`let`) binding.
1157 Local(&'hir Local<'hir>),
1159 /// An item binding.
1162 /// An expression without a trailing semi-colon (must have unit type).
1163 Expr(&'hir Expr<'hir>),
1165 /// An expression with a trailing semi-colon (may have any type).
1166 Semi(&'hir Expr<'hir>),
1169 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1170 #[derive(Debug, HashStable_Generic)]
1171 pub struct Local<'hir> {
1172 pub pat: &'hir Pat<'hir>,
1173 /// Type annotation, if any (otherwise the type will be inferred).
1174 pub ty: Option<&'hir Ty<'hir>>,
1175 /// Initializer expression to set the value, if any.
1176 pub init: Option<&'hir Expr<'hir>>,
1179 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1180 /// desugaring. Otherwise will be `Normal`.
1181 pub source: LocalSource,
1184 /// Represents a single arm of a `match` expression, e.g.
1185 /// `<pat> (if <guard>) => <body>`.
1186 #[derive(Debug, HashStable_Generic)]
1187 pub struct Arm<'hir> {
1188 #[stable_hasher(ignore)]
1191 /// If this pattern and the optional guard matches, then `body` is evaluated.
1192 pub pat: &'hir Pat<'hir>,
1193 /// Optional guard clause.
1194 pub guard: Option<Guard<'hir>>,
1195 /// The expression the arm evaluates to if this arm matches.
1196 pub body: &'hir Expr<'hir>,
1199 #[derive(Debug, HashStable_Generic)]
1200 pub enum Guard<'hir> {
1201 If(&'hir Expr<'hir>),
1202 IfLet(&'hir Pat<'hir>, &'hir Expr<'hir>),
1205 #[derive(Debug, HashStable_Generic)]
1206 pub struct ExprField<'hir> {
1207 #[stable_hasher(ignore)]
1210 pub expr: &'hir Expr<'hir>,
1212 pub is_shorthand: bool,
1215 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1216 pub enum BlockCheckMode {
1218 UnsafeBlock(UnsafeSource),
1219 PushUnsafeBlock(UnsafeSource),
1220 PopUnsafeBlock(UnsafeSource),
1223 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1224 pub enum UnsafeSource {
1229 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Hash, Debug)]
1234 /// The body of a function, closure, or constant value. In the case of
1235 /// a function, the body contains not only the function body itself
1236 /// (which is an expression), but also the argument patterns, since
1237 /// those are something that the caller doesn't really care about.
1242 /// fn foo((x, y): (u32, u32)) -> u32 {
1247 /// Here, the `Body` associated with `foo()` would contain:
1249 /// - an `params` array containing the `(x, y)` pattern
1250 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1251 /// - `generator_kind` would be `None`
1253 /// All bodies have an **owner**, which can be accessed via the HIR
1254 /// map using `body_owner_def_id()`.
1256 pub struct Body<'hir> {
1257 pub params: &'hir [Param<'hir>],
1258 pub value: Expr<'hir>,
1259 pub generator_kind: Option<GeneratorKind>,
1263 pub fn id(&self) -> BodyId {
1264 BodyId { hir_id: self.value.hir_id }
1267 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1272 /// The type of source expression that caused this generator to be created.
1285 pub enum GeneratorKind {
1286 /// An explicit `async` block or the body of an async function.
1287 Async(AsyncGeneratorKind),
1289 /// A generator literal created via a `yield` inside a closure.
1293 impl fmt::Display for GeneratorKind {
1294 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1296 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1297 GeneratorKind::Gen => f.write_str("generator"),
1302 impl GeneratorKind {
1303 pub fn descr(&self) -> &'static str {
1305 GeneratorKind::Async(ask) => ask.descr(),
1306 GeneratorKind::Gen => "generator",
1311 /// In the case of a generator created as part of an async construct,
1312 /// which kind of async construct caused it to be created?
1314 /// This helps error messages but is also used to drive coercions in
1315 /// type-checking (see #60424).
1328 pub enum AsyncGeneratorKind {
1329 /// An explicit `async` block written by the user.
1332 /// An explicit `async` block written by the user.
1335 /// The `async` block generated as the body of an async function.
1339 impl fmt::Display for AsyncGeneratorKind {
1340 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1341 f.write_str(match self {
1342 AsyncGeneratorKind::Block => "`async` block",
1343 AsyncGeneratorKind::Closure => "`async` closure body",
1344 AsyncGeneratorKind::Fn => "`async fn` body",
1349 impl AsyncGeneratorKind {
1350 pub fn descr(&self) -> &'static str {
1352 AsyncGeneratorKind::Block => "`async` block",
1353 AsyncGeneratorKind::Closure => "`async` closure body",
1354 AsyncGeneratorKind::Fn => "`async fn` body",
1359 #[derive(Copy, Clone, Debug)]
1360 pub enum BodyOwnerKind {
1361 /// Functions and methods.
1367 /// Constants and associated constants.
1370 /// Initializer of a `static` item.
1374 impl BodyOwnerKind {
1375 pub fn is_fn_or_closure(self) -> bool {
1377 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1378 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1383 /// The kind of an item that requires const-checking.
1384 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1385 pub enum ConstContext {
1389 /// A `static` or `static mut`.
1392 /// A `const`, associated `const`, or other const context.
1394 /// Other contexts include:
1395 /// - Array length expressions
1396 /// - Enum discriminants
1397 /// - Const generics
1399 /// For the most part, other contexts are treated just like a regular `const`, so they are
1400 /// lumped into the same category.
1405 /// A description of this const context that can appear between backticks in an error message.
1407 /// E.g. `const` or `static mut`.
1408 pub fn keyword_name(self) -> &'static str {
1410 Self::Const => "const",
1411 Self::Static(Mutability::Not) => "static",
1412 Self::Static(Mutability::Mut) => "static mut",
1413 Self::ConstFn => "const fn",
1418 /// A colloquial, trivially pluralizable description of this const context for use in error
1420 impl fmt::Display for ConstContext {
1421 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1423 Self::Const => write!(f, "constant"),
1424 Self::Static(_) => write!(f, "static"),
1425 Self::ConstFn => write!(f, "constant function"),
1431 pub type Lit = Spanned<LitKind>;
1433 /// A constant (expression) that's not an item or associated item,
1434 /// but needs its own `DefId` for type-checking, const-eval, etc.
1435 /// These are usually found nested inside types (e.g., array lengths)
1436 /// or expressions (e.g., repeat counts), and also used to define
1437 /// explicit discriminant values for enum variants.
1438 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1439 pub struct AnonConst {
1446 pub struct Expr<'hir> {
1448 pub kind: ExprKind<'hir>,
1453 pub fn precedence(&self) -> ExprPrecedence {
1455 ExprKind::Box(_) => ExprPrecedence::Box,
1456 ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1457 ExprKind::Array(_) => ExprPrecedence::Array,
1458 ExprKind::Call(..) => ExprPrecedence::Call,
1459 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1460 ExprKind::Tup(_) => ExprPrecedence::Tup,
1461 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1462 ExprKind::Unary(..) => ExprPrecedence::Unary,
1463 ExprKind::Lit(_) => ExprPrecedence::Lit,
1464 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1465 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1466 ExprKind::If(..) => ExprPrecedence::If,
1467 ExprKind::Loop(..) => ExprPrecedence::Loop,
1468 ExprKind::Match(..) => ExprPrecedence::Match,
1469 ExprKind::Closure(..) => ExprPrecedence::Closure,
1470 ExprKind::Block(..) => ExprPrecedence::Block,
1471 ExprKind::Assign(..) => ExprPrecedence::Assign,
1472 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1473 ExprKind::Field(..) => ExprPrecedence::Field,
1474 ExprKind::Index(..) => ExprPrecedence::Index,
1475 ExprKind::Path(..) => ExprPrecedence::Path,
1476 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1477 ExprKind::Break(..) => ExprPrecedence::Break,
1478 ExprKind::Continue(..) => ExprPrecedence::Continue,
1479 ExprKind::Ret(..) => ExprPrecedence::Ret,
1480 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1481 ExprKind::LlvmInlineAsm(..) => ExprPrecedence::InlineAsm,
1482 ExprKind::Struct(..) => ExprPrecedence::Struct,
1483 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1484 ExprKind::Yield(..) => ExprPrecedence::Yield,
1485 ExprKind::Err => ExprPrecedence::Err,
1489 // Whether this looks like a place expr, without checking for deref
1491 // This will return `true` in some potentially surprising cases such as
1492 // `CONSTANT.field`.
1493 pub fn is_syntactic_place_expr(&self) -> bool {
1494 self.is_place_expr(|_| true)
1497 /// Whether this is a place expression.
1499 /// `allow_projections_from` should return `true` if indexing a field or index expression based
1500 /// on the given expression should be considered a place expression.
1501 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1503 ExprKind::Path(QPath::Resolved(_, ref path)) => {
1504 matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static, _) | Res::Err)
1507 // Type ascription inherits its place expression kind from its
1509 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1510 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1512 ExprKind::Unary(UnOp::Deref, _) => true,
1514 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1515 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1518 // Lang item paths cannot currently be local variables or statics.
1519 ExprKind::Path(QPath::LangItem(..)) => false,
1521 // Partially qualified paths in expressions can only legally
1522 // refer to associated items which are always rvalues.
1523 ExprKind::Path(QPath::TypeRelative(..))
1524 | ExprKind::Call(..)
1525 | ExprKind::MethodCall(..)
1526 | ExprKind::Struct(..)
1529 | ExprKind::Match(..)
1530 | ExprKind::Closure(..)
1531 | ExprKind::Block(..)
1532 | ExprKind::Repeat(..)
1533 | ExprKind::Array(..)
1534 | ExprKind::Break(..)
1535 | ExprKind::Continue(..)
1537 | ExprKind::Loop(..)
1538 | ExprKind::Assign(..)
1539 | ExprKind::InlineAsm(..)
1540 | ExprKind::LlvmInlineAsm(..)
1541 | ExprKind::AssignOp(..)
1543 | ExprKind::ConstBlock(..)
1544 | ExprKind::Unary(..)
1546 | ExprKind::AddrOf(..)
1547 | ExprKind::Binary(..)
1548 | ExprKind::Yield(..)
1549 | ExprKind::Cast(..)
1550 | ExprKind::DropTemps(..)
1551 | ExprKind::Err => false,
1555 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1556 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1557 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1558 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1559 /// beyond remembering to call this function before doing analysis on it.
1560 pub fn peel_drop_temps(&self) -> &Self {
1561 let mut expr = self;
1562 while let ExprKind::DropTemps(inner) = &expr.kind {
1568 pub fn peel_blocks(&self) -> &Self {
1569 let mut expr = self;
1570 while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind {
1576 pub fn can_have_side_effects(&self) -> bool {
1577 match self.peel_drop_temps().kind {
1578 ExprKind::Path(_) | ExprKind::Lit(_) => false,
1579 ExprKind::Type(base, _)
1580 | ExprKind::Unary(_, base)
1581 | ExprKind::Field(base, _)
1582 | ExprKind::Index(base, _)
1583 | ExprKind::AddrOf(.., base)
1584 | ExprKind::Cast(base, _) => {
1585 // This isn't exactly true for `Index` and all `Unnary`, but we are using this
1586 // method exclusively for diagnostics and there's a *cultural* pressure against
1587 // them being used only for its side-effects.
1588 base.can_have_side_effects()
1590 ExprKind::Struct(_, fields, init) => fields
1592 .map(|field| field.expr)
1593 .chain(init.into_iter())
1594 .all(|e| e.can_have_side_effects()),
1596 ExprKind::Array(args)
1597 | ExprKind::Tup(args)
1601 ExprKind::Path(QPath::Resolved(
1603 Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. },
1608 ) => args.iter().all(|arg| arg.can_have_side_effects()),
1610 | ExprKind::Match(..)
1611 | ExprKind::MethodCall(..)
1612 | ExprKind::Call(..)
1613 | ExprKind::Closure(..)
1614 | ExprKind::Block(..)
1615 | ExprKind::Repeat(..)
1616 | ExprKind::Break(..)
1617 | ExprKind::Continue(..)
1619 | ExprKind::Loop(..)
1620 | ExprKind::Assign(..)
1621 | ExprKind::InlineAsm(..)
1622 | ExprKind::LlvmInlineAsm(..)
1623 | ExprKind::AssignOp(..)
1624 | ExprKind::ConstBlock(..)
1626 | ExprKind::Binary(..)
1627 | ExprKind::Yield(..)
1628 | ExprKind::DropTemps(..)
1629 | ExprKind::Err => true,
1634 /// Checks if the specified expression is a built-in range literal.
1635 /// (See: `LoweringContext::lower_expr()`).
1636 pub fn is_range_literal(expr: &Expr<'_>) -> bool {
1638 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1639 ExprKind::Struct(ref qpath, _, _) => matches!(
1644 | LangItem::RangeFrom
1645 | LangItem::RangeFull
1646 | LangItem::RangeToInclusive,
1651 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1652 ExprKind::Call(ref func, _) => {
1653 matches!(func.kind, ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, _)))
1660 #[derive(Debug, HashStable_Generic)]
1661 pub enum ExprKind<'hir> {
1662 /// A `box x` expression.
1663 Box(&'hir Expr<'hir>),
1664 /// Allow anonymous constants from an inline `const` block
1665 ConstBlock(AnonConst),
1666 /// An array (e.g., `[a, b, c, d]`).
1667 Array(&'hir [Expr<'hir>]),
1668 /// A function call.
1670 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1671 /// and the second field is the list of arguments.
1672 /// This also represents calling the constructor of
1673 /// tuple-like ADTs such as tuple structs and enum variants.
1674 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1675 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1677 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1678 /// (within the angle brackets).
1679 /// The first element of the vector of `Expr`s is the expression that evaluates
1680 /// to the object on which the method is being called on (the receiver),
1681 /// and the remaining elements are the rest of the arguments.
1682 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1683 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1684 /// The final `Span` represents the span of the function and arguments
1685 /// (e.g. `foo::<Bar, Baz>(a, b, c, d)` in `x.foo::<Bar, Baz>(a, b, c, d)`
1687 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1688 /// the `hir_id` of the `MethodCall` node itself.
1690 /// [`type_dependent_def_id`]: ../ty/struct.TypeckResults.html#method.type_dependent_def_id
1691 MethodCall(&'hir PathSegment<'hir>, Span, &'hir [Expr<'hir>], Span),
1692 /// A tuple (e.g., `(a, b, c, d)`).
1693 Tup(&'hir [Expr<'hir>]),
1694 /// A binary operation (e.g., `a + b`, `a * b`).
1695 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1696 /// A unary operation (e.g., `!x`, `*x`).
1697 Unary(UnOp, &'hir Expr<'hir>),
1698 /// A literal (e.g., `1`, `"foo"`).
1700 /// A cast (e.g., `foo as f64`).
1701 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1702 /// A type reference (e.g., `Foo`).
1703 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1704 /// Wraps the expression in a terminating scope.
1705 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1707 /// This construct only exists to tweak the drop order in HIR lowering.
1708 /// An example of that is the desugaring of `for` loops.
1709 DropTemps(&'hir Expr<'hir>),
1710 /// An `if` block, with an optional else block.
1712 /// I.e., `if <expr> { <expr> } else { <expr> }`.
1713 If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
1714 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1716 /// I.e., `'label: loop { <block> }`.
1718 /// The `Span` is the loop header (`for x in y`/`while let pat = expr`).
1719 Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span),
1720 /// A `match` block, with a source that indicates whether or not it is
1721 /// the result of a desugaring, and if so, which kind.
1722 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1723 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1725 /// The `Span` is the argument block `|...|`.
1727 /// This may also be a generator literal or an `async block` as indicated by the
1728 /// `Option<Movability>`.
1729 Closure(CaptureBy, &'hir FnDecl<'hir>, BodyId, Span, Option<Movability>),
1730 /// A block (e.g., `'label: { ... }`).
1731 Block(&'hir Block<'hir>, Option<Label>),
1733 /// An assignment (e.g., `a = foo()`).
1734 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1735 /// An assignment with an operator.
1738 AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1739 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1740 Field(&'hir Expr<'hir>, Ident),
1741 /// An indexing operation (`foo[2]`).
1742 Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1744 /// Path to a definition, possibly containing lifetime or type parameters.
1747 /// A referencing operation (i.e., `&a` or `&mut a`).
1748 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1749 /// A `break`, with an optional label to break.
1750 Break(Destination, Option<&'hir Expr<'hir>>),
1751 /// A `continue`, with an optional label.
1752 Continue(Destination),
1753 /// A `return`, with an optional value to be returned.
1754 Ret(Option<&'hir Expr<'hir>>),
1756 /// Inline assembly (from `asm!`), with its outputs and inputs.
1757 InlineAsm(&'hir InlineAsm<'hir>),
1758 /// Inline assembly (from `llvm_asm!`), with its outputs and inputs.
1759 LlvmInlineAsm(&'hir LlvmInlineAsm<'hir>),
1761 /// A struct or struct-like variant literal expression.
1763 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1764 /// where `base` is the `Option<Expr>`.
1765 Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], Option<&'hir Expr<'hir>>),
1767 /// An array literal constructed from one repeated element.
1769 /// E.g., `[1; 5]`. The first expression is the element
1770 /// to be repeated; the second is the number of times to repeat it.
1771 Repeat(&'hir Expr<'hir>, AnonConst),
1773 /// A suspension point for generators (i.e., `yield <expr>`).
1774 Yield(&'hir Expr<'hir>, YieldSource),
1776 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1780 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1782 /// To resolve the path to a `DefId`, call [`qpath_res`].
1784 /// [`qpath_res`]: ../rustc_middle/ty/struct.TypeckResults.html#method.qpath_res
1785 #[derive(Debug, HashStable_Generic)]
1786 pub enum QPath<'hir> {
1787 /// Path to a definition, optionally "fully-qualified" with a `Self`
1788 /// type, if the path points to an associated item in a trait.
1790 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1791 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1792 /// even though they both have the same two-segment `Clone::clone` `Path`.
1793 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
1795 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1796 /// Will be resolved by type-checking to an associated item.
1798 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1799 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1800 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1801 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
1803 /// Reference to a `#[lang = "foo"]` item.
1804 LangItem(LangItem, Span),
1807 impl<'hir> QPath<'hir> {
1808 /// Returns the span of this `QPath`.
1809 pub fn span(&self) -> Span {
1811 QPath::Resolved(_, path) => path.span,
1812 QPath::TypeRelative(qself, ps) => qself.span.to(ps.ident.span),
1813 QPath::LangItem(_, span) => span,
1817 /// Returns the span of the qself of this `QPath`. For example, `()` in
1818 /// `<() as Trait>::method`.
1819 pub fn qself_span(&self) -> Span {
1821 QPath::Resolved(_, path) => path.span,
1822 QPath::TypeRelative(qself, _) => qself.span,
1823 QPath::LangItem(_, span) => span,
1827 /// Returns the span of the last segment of this `QPath`. For example, `method` in
1828 /// `<() as Trait>::method`.
1829 pub fn last_segment_span(&self) -> Span {
1831 QPath::Resolved(_, path) => path.segments.last().unwrap().ident.span,
1832 QPath::TypeRelative(_, segment) => segment.ident.span,
1833 QPath::LangItem(_, span) => span,
1838 /// Hints at the original code for a let statement.
1839 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1840 pub enum LocalSource {
1841 /// A `match _ { .. }`.
1843 /// A desugared `for _ in _ { .. }` loop.
1845 /// When lowering async functions, we create locals within the `async move` so that
1846 /// all parameters are dropped after the future is polled.
1848 /// ```ignore (pseudo-Rust)
1849 /// async fn foo(<pattern> @ x: Type) {
1851 /// let <pattern> = x;
1856 /// A desugared `<expr>.await`.
1858 /// A desugared `expr = expr`, where the LHS is a tuple, struct or array.
1859 /// The span is that of the `=` sign.
1860 AssignDesugar(Span),
1863 /// Hints at the original code for a `match _ { .. }`.
1864 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
1865 #[derive(HashStable_Generic)]
1866 pub enum MatchSource {
1867 /// A `match _ { .. }`.
1869 /// An `if let _ = _ { .. }` (optionally with `else { .. }`).
1870 IfLetDesugar { contains_else_clause: bool },
1871 /// An `if let _ = _ => { .. }` match guard.
1873 /// A `while _ { .. }` (which was desugared to a `loop { match _ { .. } }`).
1875 /// A `while let _ = _ { .. }` (which was desugared to a
1876 /// `loop { match _ { .. } }`).
1878 /// A desugared `for _ in _ { .. }` loop.
1880 /// A desugared `?` operator.
1882 /// A desugared `<expr>.await`.
1887 pub fn name(self) -> &'static str {
1891 IfLetDesugar { .. } | IfLetGuardDesugar => "if",
1892 WhileDesugar | WhileLetDesugar => "while",
1893 ForLoopDesugar => "for",
1895 AwaitDesugar => ".await",
1900 /// The loop type that yielded an `ExprKind::Loop`.
1901 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1902 pub enum LoopSource {
1903 /// A `loop { .. }` loop.
1905 /// A `while _ { .. }` loop.
1907 /// A `while let _ = _ { .. }` loop.
1909 /// A `for _ in _ { .. }` loop.
1914 pub fn name(self) -> &'static str {
1916 LoopSource::Loop => "loop",
1917 LoopSource::While | LoopSource::WhileLet => "while",
1918 LoopSource::ForLoop => "for",
1923 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1924 pub enum LoopIdError {
1926 UnlabeledCfInWhileCondition,
1930 impl fmt::Display for LoopIdError {
1931 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1932 f.write_str(match self {
1933 LoopIdError::OutsideLoopScope => "not inside loop scope",
1934 LoopIdError::UnlabeledCfInWhileCondition => {
1935 "unlabeled control flow (break or continue) in while condition"
1937 LoopIdError::UnresolvedLabel => "label not found",
1942 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1943 pub struct Destination {
1944 // This is `Some(_)` iff there is an explicit user-specified `label
1945 pub label: Option<Label>,
1947 // These errors are caught and then reported during the diagnostics pass in
1948 // librustc_passes/loops.rs
1949 pub target_id: Result<HirId, LoopIdError>,
1952 /// The yield kind that caused an `ExprKind::Yield`.
1953 #[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
1954 pub enum YieldSource {
1955 /// An `<expr>.await`.
1956 Await { expr: Option<HirId> },
1957 /// A plain `yield`.
1962 pub fn is_await(&self) -> bool {
1964 YieldSource::Await { .. } => true,
1965 YieldSource::Yield => false,
1970 impl fmt::Display for YieldSource {
1971 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1972 f.write_str(match self {
1973 YieldSource::Await { .. } => "`await`",
1974 YieldSource::Yield => "`yield`",
1979 impl From<GeneratorKind> for YieldSource {
1980 fn from(kind: GeneratorKind) -> Self {
1982 // Guess based on the kind of the current generator.
1983 GeneratorKind::Gen => Self::Yield,
1984 GeneratorKind::Async(_) => Self::Await { expr: None },
1989 // N.B., if you change this, you'll probably want to change the corresponding
1990 // type structure in middle/ty.rs as well.
1991 #[derive(Debug, HashStable_Generic)]
1992 pub struct MutTy<'hir> {
1993 pub ty: &'hir Ty<'hir>,
1994 pub mutbl: Mutability,
1997 /// Represents a function's signature in a trait declaration,
1998 /// trait implementation, or a free function.
1999 #[derive(Debug, HashStable_Generic)]
2000 pub struct FnSig<'hir> {
2001 pub header: FnHeader,
2002 pub decl: &'hir FnDecl<'hir>,
2006 // The bodies for items are stored "out of line", in a separate
2007 // hashmap in the `Crate`. Here we just record the hir-id of the item
2008 // so it can fetched later.
2009 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
2010 pub struct TraitItemId {
2011 pub def_id: LocalDefId,
2016 pub fn hir_id(&self) -> HirId {
2017 // Items are always HIR owners.
2018 HirId::make_owner(self.def_id)
2022 /// Represents an item declaration within a trait declaration,
2023 /// possibly including a default implementation. A trait item is
2024 /// either required (meaning it doesn't have an implementation, just a
2025 /// signature) or provided (meaning it has a default implementation).
2027 pub struct TraitItem<'hir> {
2029 pub def_id: LocalDefId,
2030 pub generics: Generics<'hir>,
2031 pub kind: TraitItemKind<'hir>,
2035 impl TraitItem<'_> {
2037 pub fn hir_id(&self) -> HirId {
2038 // Items are always HIR owners.
2039 HirId::make_owner(self.def_id)
2042 pub fn trait_item_id(&self) -> TraitItemId {
2043 TraitItemId { def_id: self.def_id }
2047 /// Represents a trait method's body (or just argument names).
2048 #[derive(Encodable, Debug, HashStable_Generic)]
2049 pub enum TraitFn<'hir> {
2050 /// No default body in the trait, just a signature.
2051 Required(&'hir [Ident]),
2053 /// Both signature and body are provided in the trait.
2057 /// Represents a trait method or associated constant or type
2058 #[derive(Debug, HashStable_Generic)]
2059 pub enum TraitItemKind<'hir> {
2060 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
2061 Const(&'hir Ty<'hir>, Option<BodyId>),
2062 /// An associated function with an optional body.
2063 Fn(FnSig<'hir>, TraitFn<'hir>),
2064 /// An associated type with (possibly empty) bounds and optional concrete
2066 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
2069 // The bodies for items are stored "out of line", in a separate
2070 // hashmap in the `Crate`. Here we just record the hir-id of the item
2071 // so it can fetched later.
2072 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
2073 pub struct ImplItemId {
2074 pub def_id: LocalDefId,
2079 pub fn hir_id(&self) -> HirId {
2080 // Items are always HIR owners.
2081 HirId::make_owner(self.def_id)
2085 /// Represents anything within an `impl` block.
2087 pub struct ImplItem<'hir> {
2089 pub def_id: LocalDefId,
2090 pub vis: Visibility<'hir>,
2091 pub defaultness: Defaultness,
2092 pub generics: Generics<'hir>,
2093 pub kind: ImplItemKind<'hir>,
2099 pub fn hir_id(&self) -> HirId {
2100 // Items are always HIR owners.
2101 HirId::make_owner(self.def_id)
2104 pub fn impl_item_id(&self) -> ImplItemId {
2105 ImplItemId { def_id: self.def_id }
2109 /// Represents various kinds of content within an `impl`.
2110 #[derive(Debug, HashStable_Generic)]
2111 pub enum ImplItemKind<'hir> {
2112 /// An associated constant of the given type, set to the constant result
2113 /// of the expression.
2114 Const(&'hir Ty<'hir>, BodyId),
2115 /// An associated function implementation with the given signature and body.
2116 Fn(FnSig<'hir>, BodyId),
2117 /// An associated type.
2118 TyAlias(&'hir Ty<'hir>),
2121 // The name of the associated type for `Fn` return types.
2122 pub const FN_OUTPUT_NAME: Symbol = sym::Output;
2124 /// Bind a type to an associated type (i.e., `A = Foo`).
2126 /// Bindings like `A: Debug` are represented as a special type `A =
2127 /// $::Debug` that is understood by the astconv code.
2129 /// FIXME(alexreg): why have a separate type for the binding case,
2130 /// wouldn't it be better to make the `ty` field an enum like the
2134 /// enum TypeBindingKind {
2139 #[derive(Debug, HashStable_Generic)]
2140 pub struct TypeBinding<'hir> {
2142 #[stable_hasher(project(name))]
2144 pub gen_args: &'hir GenericArgs<'hir>,
2145 pub kind: TypeBindingKind<'hir>,
2149 // Represents the two kinds of type bindings.
2150 #[derive(Debug, HashStable_Generic)]
2151 pub enum TypeBindingKind<'hir> {
2152 /// E.g., `Foo<Bar: Send>`.
2153 Constraint { bounds: &'hir [GenericBound<'hir>] },
2154 /// E.g., `Foo<Bar = ()>`.
2155 Equality { ty: &'hir Ty<'hir> },
2158 impl TypeBinding<'_> {
2159 pub fn ty(&self) -> &Ty<'_> {
2161 TypeBindingKind::Equality { ref ty } => ty,
2162 _ => panic!("expected equality type binding for parenthesized generic args"),
2168 pub struct Ty<'hir> {
2170 pub kind: TyKind<'hir>,
2174 /// Not represented directly in the AST; referred to by name through a `ty_path`.
2175 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
2176 #[derive(HashStable_Generic)]
2187 /// All of the primitive types
2188 pub const ALL: [Self; 17] = [
2189 // any changes here should also be reflected in `PrimTy::from_name`
2190 Self::Int(IntTy::I8),
2191 Self::Int(IntTy::I16),
2192 Self::Int(IntTy::I32),
2193 Self::Int(IntTy::I64),
2194 Self::Int(IntTy::I128),
2195 Self::Int(IntTy::Isize),
2196 Self::Uint(UintTy::U8),
2197 Self::Uint(UintTy::U16),
2198 Self::Uint(UintTy::U32),
2199 Self::Uint(UintTy::U64),
2200 Self::Uint(UintTy::U128),
2201 Self::Uint(UintTy::Usize),
2202 Self::Float(FloatTy::F32),
2203 Self::Float(FloatTy::F64),
2209 /// Like [`PrimTy::name`], but returns a &str instead of a symbol.
2211 /// Used by rustdoc.
2212 pub fn name_str(self) -> &'static str {
2214 PrimTy::Int(i) => i.name_str(),
2215 PrimTy::Uint(u) => u.name_str(),
2216 PrimTy::Float(f) => f.name_str(),
2217 PrimTy::Str => "str",
2218 PrimTy::Bool => "bool",
2219 PrimTy::Char => "char",
2223 pub fn name(self) -> Symbol {
2225 PrimTy::Int(i) => i.name(),
2226 PrimTy::Uint(u) => u.name(),
2227 PrimTy::Float(f) => f.name(),
2228 PrimTy::Str => sym::str,
2229 PrimTy::Bool => sym::bool,
2230 PrimTy::Char => sym::char,
2234 /// Returns the matching `PrimTy` for a `Symbol` such as "str" or "i32".
2235 /// Returns `None` if no matching type is found.
2236 pub fn from_name(name: Symbol) -> Option<Self> {
2237 let ty = match name {
2238 // any changes here should also be reflected in `PrimTy::ALL`
2239 sym::i8 => Self::Int(IntTy::I8),
2240 sym::i16 => Self::Int(IntTy::I16),
2241 sym::i32 => Self::Int(IntTy::I32),
2242 sym::i64 => Self::Int(IntTy::I64),
2243 sym::i128 => Self::Int(IntTy::I128),
2244 sym::isize => Self::Int(IntTy::Isize),
2245 sym::u8 => Self::Uint(UintTy::U8),
2246 sym::u16 => Self::Uint(UintTy::U16),
2247 sym::u32 => Self::Uint(UintTy::U32),
2248 sym::u64 => Self::Uint(UintTy::U64),
2249 sym::u128 => Self::Uint(UintTy::U128),
2250 sym::usize => Self::Uint(UintTy::Usize),
2251 sym::f32 => Self::Float(FloatTy::F32),
2252 sym::f64 => Self::Float(FloatTy::F64),
2253 sym::bool => Self::Bool,
2254 sym::char => Self::Char,
2255 sym::str => Self::Str,
2262 #[derive(Debug, HashStable_Generic)]
2263 pub struct BareFnTy<'hir> {
2264 pub unsafety: Unsafety,
2266 pub generic_params: &'hir [GenericParam<'hir>],
2267 pub decl: &'hir FnDecl<'hir>,
2268 pub param_names: &'hir [Ident],
2271 #[derive(Debug, HashStable_Generic)]
2272 pub struct OpaqueTy<'hir> {
2273 pub generics: Generics<'hir>,
2274 pub bounds: GenericBounds<'hir>,
2275 pub impl_trait_fn: Option<DefId>,
2276 pub origin: OpaqueTyOrigin,
2279 /// From whence the opaque type came.
2280 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2281 pub enum OpaqueTyOrigin {
2286 /// `let _: impl Trait = ...`
2288 /// type aliases: `type Foo = impl Trait;`
2290 /// Impl trait consts, statics, bounds.
2294 /// The various kinds of types recognized by the compiler.
2295 #[derive(Debug, HashStable_Generic)]
2296 pub enum TyKind<'hir> {
2297 /// A variable length slice (i.e., `[T]`).
2298 Slice(&'hir Ty<'hir>),
2299 /// A fixed length array (i.e., `[T; n]`).
2300 Array(&'hir Ty<'hir>, AnonConst),
2301 /// A raw pointer (i.e., `*const T` or `*mut T`).
2303 /// A reference (i.e., `&'a T` or `&'a mut T`).
2304 Rptr(Lifetime, MutTy<'hir>),
2305 /// A bare function (e.g., `fn(usize) -> bool`).
2306 BareFn(&'hir BareFnTy<'hir>),
2307 /// The never type (`!`).
2309 /// A tuple (`(A, B, C, D, ...)`).
2310 Tup(&'hir [Ty<'hir>]),
2311 /// A path to a type definition (`module::module::...::Type`), or an
2312 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2314 /// Type parameters may be stored in each `PathSegment`.
2316 /// A opaque type definition itself. This is currently only used for the
2317 /// `opaque type Foo: Trait` item that `impl Trait` in desugars to.
2319 /// The generic argument list contains the lifetimes (and in the future
2320 /// possibly parameters) that are actually bound on the `impl Trait`.
2321 OpaqueDef(ItemId, &'hir [GenericArg<'hir>]),
2322 /// A trait object type `Bound1 + Bound2 + Bound3`
2323 /// where `Bound` is a trait or a lifetime.
2324 TraitObject(&'hir [PolyTraitRef<'hir>], Lifetime, TraitObjectSyntax),
2327 /// `TyKind::Infer` means the type should be inferred instead of it having been
2328 /// specified. This can appear anywhere in a type.
2330 /// Placeholder for a type that has failed to be defined.
2334 #[derive(Debug, HashStable_Generic)]
2335 pub enum InlineAsmOperand<'hir> {
2337 reg: InlineAsmRegOrRegClass,
2341 reg: InlineAsmRegOrRegClass,
2343 expr: Option<Expr<'hir>>,
2346 reg: InlineAsmRegOrRegClass,
2351 reg: InlineAsmRegOrRegClass,
2353 in_expr: Expr<'hir>,
2354 out_expr: Option<Expr<'hir>>,
2364 impl<'hir> InlineAsmOperand<'hir> {
2365 pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
2367 Self::In { reg, .. }
2368 | Self::Out { reg, .. }
2369 | Self::InOut { reg, .. }
2370 | Self::SplitInOut { reg, .. } => Some(reg),
2371 Self::Const { .. } | Self::Sym { .. } => None,
2376 #[derive(Debug, HashStable_Generic)]
2377 pub struct InlineAsm<'hir> {
2378 pub template: &'hir [InlineAsmTemplatePiece],
2379 pub operands: &'hir [(InlineAsmOperand<'hir>, Span)],
2380 pub options: InlineAsmOptions,
2381 pub line_spans: &'hir [Span],
2384 #[derive(Copy, Clone, Encodable, Decodable, Debug, Hash, HashStable_Generic, PartialEq)]
2385 pub struct LlvmInlineAsmOutput {
2386 pub constraint: Symbol,
2388 pub is_indirect: bool,
2392 // NOTE(eddyb) This is used within MIR as well, so unlike the rest of the HIR,
2393 // it needs to be `Clone` and `Decodable` and use plain `Vec<T>` instead of
2394 // arena-allocated slice.
2395 #[derive(Clone, Encodable, Decodable, Debug, Hash, HashStable_Generic, PartialEq)]
2396 pub struct LlvmInlineAsmInner {
2398 pub asm_str_style: StrStyle,
2399 pub outputs: Vec<LlvmInlineAsmOutput>,
2400 pub inputs: Vec<Symbol>,
2401 pub clobbers: Vec<Symbol>,
2403 pub alignstack: bool,
2404 pub dialect: LlvmAsmDialect,
2407 #[derive(Debug, HashStable_Generic)]
2408 pub struct LlvmInlineAsm<'hir> {
2409 pub inner: LlvmInlineAsmInner,
2410 pub outputs_exprs: &'hir [Expr<'hir>],
2411 pub inputs_exprs: &'hir [Expr<'hir>],
2414 /// Represents a parameter in a function header.
2415 #[derive(Debug, HashStable_Generic)]
2416 pub struct Param<'hir> {
2418 pub pat: &'hir Pat<'hir>,
2423 /// Represents the header (not the body) of a function declaration.
2424 #[derive(Debug, HashStable_Generic)]
2425 pub struct FnDecl<'hir> {
2426 /// The types of the function's parameters.
2428 /// Additional argument data is stored in the function's [body](Body::params).
2429 pub inputs: &'hir [Ty<'hir>],
2430 pub output: FnRetTy<'hir>,
2431 pub c_variadic: bool,
2432 /// Does the function have an implicit self?
2433 pub implicit_self: ImplicitSelfKind,
2436 /// Represents what type of implicit self a function has, if any.
2437 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2438 pub enum ImplicitSelfKind {
2439 /// Represents a `fn x(self);`.
2441 /// Represents a `fn x(mut self);`.
2443 /// Represents a `fn x(&self);`.
2445 /// Represents a `fn x(&mut self);`.
2447 /// Represents when a function does not have a self argument or
2448 /// when a function has a `self: X` argument.
2452 impl ImplicitSelfKind {
2453 /// Does this represent an implicit self?
2454 pub fn has_implicit_self(&self) -> bool {
2455 !matches!(*self, ImplicitSelfKind::None)
2459 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable, Debug)]
2460 #[derive(HashStable_Generic)]
2466 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable, HashStable_Generic)]
2467 pub enum Defaultness {
2468 Default { has_value: bool },
2473 pub fn has_value(&self) -> bool {
2475 Defaultness::Default { has_value } => has_value,
2476 Defaultness::Final => true,
2480 pub fn is_final(&self) -> bool {
2481 *self == Defaultness::Final
2484 pub fn is_default(&self) -> bool {
2485 matches!(*self, Defaultness::Default { .. })
2489 #[derive(Debug, HashStable_Generic)]
2490 pub enum FnRetTy<'hir> {
2491 /// Return type is not specified.
2493 /// Functions default to `()` and
2494 /// closures default to inference. Span points to where return
2495 /// type would be inserted.
2496 DefaultReturn(Span),
2497 /// Everything else.
2498 Return(&'hir Ty<'hir>),
2502 pub fn span(&self) -> Span {
2504 Self::DefaultReturn(span) => span,
2505 Self::Return(ref ty) => ty.span,
2510 #[derive(Encodable, Debug)]
2511 pub struct Mod<'hir> {
2512 /// A span from the first token past `{` to the last token until `}`.
2513 /// For `mod foo;`, the inner span ranges from the first token
2514 /// to the last token in the external file.
2516 pub item_ids: &'hir [ItemId],
2519 #[derive(Encodable, Debug, HashStable_Generic)]
2520 pub struct GlobalAsm {
2524 #[derive(Debug, HashStable_Generic)]
2525 pub struct EnumDef<'hir> {
2526 pub variants: &'hir [Variant<'hir>],
2529 #[derive(Debug, HashStable_Generic)]
2530 pub struct Variant<'hir> {
2531 /// Name of the variant.
2532 #[stable_hasher(project(name))]
2534 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2536 /// Fields and constructor id of the variant.
2537 pub data: VariantData<'hir>,
2538 /// Explicit discriminant (e.g., `Foo = 1`).
2539 pub disr_expr: Option<AnonConst>,
2544 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2546 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2547 /// Also produced for each element of a list `use`, e.g.
2548 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2551 /// Glob import, e.g., `use foo::*`.
2554 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2555 /// an additional `use foo::{}` for performing checks such as
2556 /// unstable feature gating. May be removed in the future.
2560 /// References to traits in impls.
2562 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2563 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2564 /// trait being referred to but just a unique `HirId` that serves as a key
2565 /// within the resolution map.
2566 #[derive(Debug, HashStable_Generic)]
2567 pub struct TraitRef<'hir> {
2568 pub path: &'hir Path<'hir>,
2569 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2570 #[stable_hasher(ignore)]
2571 pub hir_ref_id: HirId,
2575 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2576 pub fn trait_def_id(&self) -> Option<DefId> {
2577 match self.path.res {
2578 Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
2580 _ => unreachable!(),
2585 #[derive(Debug, HashStable_Generic)]
2586 pub struct PolyTraitRef<'hir> {
2587 /// The `'a` in `for<'a> Foo<&'a T>`.
2588 pub bound_generic_params: &'hir [GenericParam<'hir>],
2590 /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
2591 pub trait_ref: TraitRef<'hir>,
2596 pub type Visibility<'hir> = Spanned<VisibilityKind<'hir>>;
2599 pub enum VisibilityKind<'hir> {
2602 Restricted { path: &'hir Path<'hir>, hir_id: HirId },
2606 impl VisibilityKind<'_> {
2607 pub fn is_pub(&self) -> bool {
2608 matches!(*self, VisibilityKind::Public)
2611 pub fn is_pub_restricted(&self) -> bool {
2613 VisibilityKind::Public | VisibilityKind::Inherited => false,
2614 VisibilityKind::Crate(..) | VisibilityKind::Restricted { .. } => true,
2619 #[derive(Debug, HashStable_Generic)]
2620 pub struct FieldDef<'hir> {
2622 #[stable_hasher(project(name))]
2624 pub vis: Visibility<'hir>,
2626 pub ty: &'hir Ty<'hir>,
2630 // Still necessary in couple of places
2631 pub fn is_positional(&self) -> bool {
2632 let first = self.ident.as_str().as_bytes()[0];
2633 (b'0'..=b'9').contains(&first)
2637 /// Fields and constructor IDs of enum variants and structs.
2638 #[derive(Debug, HashStable_Generic)]
2639 pub enum VariantData<'hir> {
2640 /// A struct variant.
2642 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2643 Struct(&'hir [FieldDef<'hir>], /* recovered */ bool),
2644 /// A tuple variant.
2646 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2647 Tuple(&'hir [FieldDef<'hir>], HirId),
2650 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2654 impl VariantData<'hir> {
2655 /// Return the fields of this variant.
2656 pub fn fields(&self) -> &'hir [FieldDef<'hir>] {
2658 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2663 /// Return the `HirId` of this variant's constructor, if it has one.
2664 pub fn ctor_hir_id(&self) -> Option<HirId> {
2666 VariantData::Struct(_, _) => None,
2667 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2672 // The bodies for items are stored "out of line", in a separate
2673 // hashmap in the `Crate`. Here we just record the hir-id of the item
2674 // so it can fetched later.
2675 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug, Hash)]
2677 pub def_id: LocalDefId,
2682 pub fn hir_id(&self) -> HirId {
2683 // Items are always HIR owners.
2684 HirId::make_owner(self.def_id)
2690 /// The name might be a dummy name in case of anonymous items
2692 pub struct Item<'hir> {
2694 pub def_id: LocalDefId,
2695 pub kind: ItemKind<'hir>,
2696 pub vis: Visibility<'hir>,
2702 pub fn hir_id(&self) -> HirId {
2703 // Items are always HIR owners.
2704 HirId::make_owner(self.def_id)
2707 pub fn item_id(&self) -> ItemId {
2708 ItemId { def_id: self.def_id }
2712 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2713 #[derive(Encodable, Decodable, HashStable_Generic)]
2720 pub fn prefix_str(&self) -> &'static str {
2722 Self::Unsafe => "unsafe ",
2728 impl fmt::Display for Unsafety {
2729 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2730 f.write_str(match *self {
2731 Self::Unsafe => "unsafe",
2732 Self::Normal => "normal",
2737 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2738 #[derive(Encodable, Decodable, HashStable_Generic)]
2739 pub enum Constness {
2744 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2745 pub struct FnHeader {
2746 pub unsafety: Unsafety,
2747 pub constness: Constness,
2748 pub asyncness: IsAsync,
2753 pub fn is_const(&self) -> bool {
2754 matches!(&self.constness, Constness::Const)
2758 #[derive(Debug, HashStable_Generic)]
2759 pub enum ItemKind<'hir> {
2760 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2762 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2763 ExternCrate(Option<Symbol>),
2765 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2769 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2770 Use(&'hir Path<'hir>, UseKind),
2772 /// A `static` item.
2773 Static(&'hir Ty<'hir>, Mutability, BodyId),
2775 Const(&'hir Ty<'hir>, BodyId),
2776 /// A function declaration.
2777 Fn(FnSig<'hir>, Generics<'hir>, BodyId),
2780 /// An external module, e.g. `extern { .. }`.
2781 ForeignMod { abi: Abi, items: &'hir [ForeignItemRef<'hir>] },
2782 /// Module-level inline assembly (from `global_asm!`).
2783 GlobalAsm(&'hir GlobalAsm),
2784 /// A type alias, e.g., `type Foo = Bar<u8>`.
2785 TyAlias(&'hir Ty<'hir>, Generics<'hir>),
2786 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2787 OpaqueTy(OpaqueTy<'hir>),
2788 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2789 Enum(EnumDef<'hir>, Generics<'hir>),
2790 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2791 Struct(VariantData<'hir>, Generics<'hir>),
2792 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2793 Union(VariantData<'hir>, Generics<'hir>),
2794 /// A trait definition.
2795 Trait(IsAuto, Unsafety, Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
2797 TraitAlias(Generics<'hir>, GenericBounds<'hir>),
2799 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2803 #[derive(Debug, HashStable_Generic)]
2804 pub struct Impl<'hir> {
2805 pub unsafety: Unsafety,
2806 pub polarity: ImplPolarity,
2807 pub defaultness: Defaultness,
2808 // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata
2809 // decoding as `Span`s cannot be decoded when a `Session` is not available.
2810 pub defaultness_span: Option<Span>,
2811 pub constness: Constness,
2812 pub generics: Generics<'hir>,
2814 /// The trait being implemented, if any.
2815 pub of_trait: Option<TraitRef<'hir>>,
2817 pub self_ty: &'hir Ty<'hir>,
2818 pub items: &'hir [ImplItemRef<'hir>],
2822 pub fn generics(&self) -> Option<&Generics<'_>> {
2824 ItemKind::Fn(_, ref generics, _)
2825 | ItemKind::TyAlias(_, ref generics)
2826 | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
2827 | ItemKind::Enum(_, ref generics)
2828 | ItemKind::Struct(_, ref generics)
2829 | ItemKind::Union(_, ref generics)
2830 | ItemKind::Trait(_, _, ref generics, _, _)
2831 | ItemKind::Impl(Impl { ref generics, .. }) => generics,
2837 /// A reference from an trait to one of its associated items. This
2838 /// contains the item's id, naturally, but also the item's name and
2839 /// some other high-level details (like whether it is an associated
2840 /// type or method, and whether it is public). This allows other
2841 /// passes to find the impl they want without loading the ID (which
2842 /// means fewer edges in the incremental compilation graph).
2843 #[derive(Encodable, Debug, HashStable_Generic)]
2844 pub struct TraitItemRef {
2845 pub id: TraitItemId,
2846 #[stable_hasher(project(name))]
2848 pub kind: AssocItemKind,
2850 pub defaultness: Defaultness,
2853 /// A reference from an impl to one of its associated items. This
2854 /// contains the item's ID, naturally, but also the item's name and
2855 /// some other high-level details (like whether it is an associated
2856 /// type or method, and whether it is public). This allows other
2857 /// passes to find the impl they want without loading the ID (which
2858 /// means fewer edges in the incremental compilation graph).
2859 #[derive(Debug, HashStable_Generic)]
2860 pub struct ImplItemRef<'hir> {
2862 #[stable_hasher(project(name))]
2864 pub kind: AssocItemKind,
2866 pub vis: Visibility<'hir>,
2867 pub defaultness: Defaultness,
2870 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2871 pub enum AssocItemKind {
2873 Fn { has_self: bool },
2877 // The bodies for items are stored "out of line", in a separate
2878 // hashmap in the `Crate`. Here we just record the hir-id of the item
2879 // so it can fetched later.
2880 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
2881 pub struct ForeignItemId {
2882 pub def_id: LocalDefId,
2885 impl ForeignItemId {
2887 pub fn hir_id(&self) -> HirId {
2888 // Items are always HIR owners.
2889 HirId::make_owner(self.def_id)
2893 /// A reference from a foreign block to one of its items. This
2894 /// contains the item's ID, naturally, but also the item's name and
2895 /// some other high-level details (like whether it is an associated
2896 /// type or method, and whether it is public). This allows other
2897 /// passes to find the impl they want without loading the ID (which
2898 /// means fewer edges in the incremental compilation graph).
2899 #[derive(Debug, HashStable_Generic)]
2900 pub struct ForeignItemRef<'hir> {
2901 pub id: ForeignItemId,
2902 #[stable_hasher(project(name))]
2905 pub vis: Visibility<'hir>,
2909 pub struct ForeignItem<'hir> {
2911 pub kind: ForeignItemKind<'hir>,
2912 pub def_id: LocalDefId,
2914 pub vis: Visibility<'hir>,
2917 impl ForeignItem<'_> {
2919 pub fn hir_id(&self) -> HirId {
2920 // Items are always HIR owners.
2921 HirId::make_owner(self.def_id)
2924 pub fn foreign_item_id(&self) -> ForeignItemId {
2925 ForeignItemId { def_id: self.def_id }
2929 /// An item within an `extern` block.
2930 #[derive(Debug, HashStable_Generic)]
2931 pub enum ForeignItemKind<'hir> {
2932 /// A foreign function.
2933 Fn(&'hir FnDecl<'hir>, &'hir [Ident], Generics<'hir>),
2934 /// A foreign static item (`static ext: u8`).
2935 Static(&'hir Ty<'hir>, Mutability),
2940 /// A variable captured by a closure.
2941 #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)]
2943 // First span where it is accessed (there can be multiple).
2947 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2948 // has length > 0 if the trait is found through an chain of imports, starting with the
2949 // import/use statement in the scope where the trait is used.
2950 #[derive(Encodable, Decodable, Clone, Debug)]
2951 pub struct TraitCandidate {
2953 pub import_ids: SmallVec<[LocalDefId; 1]>,
2956 #[derive(Copy, Clone, Debug, HashStable_Generic)]
2957 pub enum Node<'hir> {
2958 Param(&'hir Param<'hir>),
2959 Item(&'hir Item<'hir>),
2960 ForeignItem(&'hir ForeignItem<'hir>),
2961 TraitItem(&'hir TraitItem<'hir>),
2962 ImplItem(&'hir ImplItem<'hir>),
2963 Variant(&'hir Variant<'hir>),
2964 Field(&'hir FieldDef<'hir>),
2965 AnonConst(&'hir AnonConst),
2966 Expr(&'hir Expr<'hir>),
2967 Stmt(&'hir Stmt<'hir>),
2968 PathSegment(&'hir PathSegment<'hir>),
2970 TraitRef(&'hir TraitRef<'hir>),
2971 Binding(&'hir Pat<'hir>),
2972 Pat(&'hir Pat<'hir>),
2973 Arm(&'hir Arm<'hir>),
2974 Block(&'hir Block<'hir>),
2975 Local(&'hir Local<'hir>),
2976 MacroDef(&'hir MacroDef<'hir>),
2978 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
2979 /// with synthesized constructors.
2980 Ctor(&'hir VariantData<'hir>),
2982 Lifetime(&'hir Lifetime),
2983 GenericParam(&'hir GenericParam<'hir>),
2984 Visibility(&'hir Visibility<'hir>),
2986 Crate(&'hir CrateItem<'hir>),
2989 impl<'hir> Node<'hir> {
2990 pub fn ident(&self) -> Option<Ident> {
2992 Node::TraitItem(TraitItem { ident, .. })
2993 | Node::ImplItem(ImplItem { ident, .. })
2994 | Node::ForeignItem(ForeignItem { ident, .. })
2995 | Node::Field(FieldDef { ident, .. })
2996 | Node::Variant(Variant { ident, .. })
2997 | Node::MacroDef(MacroDef { ident, .. })
2998 | Node::Item(Item { ident, .. }) => Some(*ident),
3003 pub fn fn_decl(&self) -> Option<&FnDecl<'hir>> {
3005 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3006 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3007 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3008 Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
3015 pub fn body_id(&self) -> Option<BodyId> {
3017 Node::TraitItem(TraitItem {
3018 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3021 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3022 | Node::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3027 pub fn generics(&self) -> Option<&'hir Generics<'hir>> {
3029 Node::TraitItem(TraitItem { generics, .. })
3030 | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
3031 Node::Item(item) => item.kind.generics(),
3036 pub fn hir_id(&self) -> Option<HirId> {
3038 Node::Item(Item { def_id, .. })
3039 | Node::TraitItem(TraitItem { def_id, .. })
3040 | Node::ImplItem(ImplItem { def_id, .. })
3041 | Node::ForeignItem(ForeignItem { def_id, .. })
3042 | Node::MacroDef(MacroDef { def_id, .. }) => Some(HirId::make_owner(*def_id)),
3043 Node::Field(FieldDef { hir_id, .. })
3044 | Node::AnonConst(AnonConst { hir_id, .. })
3045 | Node::Expr(Expr { hir_id, .. })
3046 | Node::Stmt(Stmt { hir_id, .. })
3047 | Node::Ty(Ty { hir_id, .. })
3048 | Node::Binding(Pat { hir_id, .. })
3049 | Node::Pat(Pat { hir_id, .. })
3050 | Node::Arm(Arm { hir_id, .. })
3051 | Node::Block(Block { hir_id, .. })
3052 | Node::Local(Local { hir_id, .. })
3053 | Node::Lifetime(Lifetime { hir_id, .. })
3054 | Node::Param(Param { hir_id, .. })
3055 | Node::GenericParam(GenericParam { hir_id, .. }) => Some(*hir_id),
3056 Node::TraitRef(TraitRef { hir_ref_id, .. }) => Some(*hir_ref_id),
3057 Node::PathSegment(PathSegment { hir_id, .. }) => *hir_id,
3058 Node::Variant(Variant { id, .. }) => Some(*id),
3059 Node::Ctor(variant) => variant.ctor_hir_id(),
3060 Node::Crate(_) | Node::Visibility(_) => None,
3065 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3066 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
3068 rustc_data_structures::static_assert_size!(super::Block<'static>, 48);
3069 rustc_data_structures::static_assert_size!(super::Expr<'static>, 64);
3070 rustc_data_structures::static_assert_size!(super::Pat<'static>, 88);
3071 rustc_data_structures::static_assert_size!(super::QPath<'static>, 24);
3072 rustc_data_structures::static_assert_size!(super::Ty<'static>, 72);
3074 rustc_data_structures::static_assert_size!(super::Item<'static>, 184);
3075 rustc_data_structures::static_assert_size!(super::TraitItem<'static>, 128);
3076 rustc_data_structures::static_assert_size!(super::ImplItem<'static>, 152);
3077 rustc_data_structures::static_assert_size!(super::ForeignItem<'static>, 136);