1 use crate::def::{CtorKind, DefKind, Res};
2 use crate::def_id::{DefId, CRATE_DEF_ID};
3 crate use crate::hir_id::{HirId, ItemLocalId};
6 use rustc_ast::util::parser::ExprPrecedence;
7 use rustc_ast::{self as ast, CrateSugar, LlvmAsmDialect};
8 use rustc_ast::{Attribute, FloatTy, IntTy, Label, LitKind, StrStyle, TraitObjectSyntax, UintTy};
9 pub use rustc_ast::{BorrowKind, ImplPolarity, IsAuto};
10 pub use rustc_ast::{CaptureBy, Movability, Mutability};
11 use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
12 use rustc_data_structures::fx::FxHashMap;
13 use rustc_index::vec::IndexVec;
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;
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(Copy, Clone, Encodable, Debug, HashStable_Generic)]
263 pub fn is_type(self) -> bool {
264 matches!(self, InferKind::Type)
268 #[derive(Encodable, Debug, HashStable_Generic)]
269 pub struct InferArg {
276 pub fn to_ty(&self) -> Ty<'_> {
277 Ty { kind: TyKind::Infer, span: self.span, hir_id: self.hir_id }
281 #[derive(Debug, HashStable_Generic)]
282 pub enum GenericArg<'hir> {
289 impl GenericArg<'_> {
290 pub fn span(&self) -> Span {
292 GenericArg::Lifetime(l) => l.span,
293 GenericArg::Type(t) => t.span,
294 GenericArg::Const(c) => c.span,
295 GenericArg::Infer(i) => i.span,
299 pub fn id(&self) -> HirId {
301 GenericArg::Lifetime(l) => l.hir_id,
302 GenericArg::Type(t) => t.hir_id,
303 GenericArg::Const(c) => c.value.hir_id,
304 GenericArg::Infer(i) => i.hir_id,
308 pub fn is_const(&self) -> bool {
309 matches!(self, GenericArg::Const(_))
312 pub fn is_synthetic(&self) -> bool {
313 matches!(self, GenericArg::Lifetime(lifetime) if lifetime.name.ident() == Ident::invalid())
316 pub fn descr(&self) -> &'static str {
318 GenericArg::Lifetime(_) => "lifetime",
319 GenericArg::Type(_) => "type",
320 GenericArg::Const(_) => "constant",
321 GenericArg::Infer(_) => "inferred",
325 pub fn to_ord(&self, feats: &rustc_feature::Features) -> ast::ParamKindOrd {
327 GenericArg::Lifetime(_) => ast::ParamKindOrd::Lifetime,
328 GenericArg::Type(_) => ast::ParamKindOrd::Type,
329 GenericArg::Const(_) => {
330 ast::ParamKindOrd::Const { unordered: feats.unordered_const_ty_params() }
332 GenericArg::Infer(_) => ast::ParamKindOrd::Infer,
337 #[derive(Debug, HashStable_Generic)]
338 pub struct GenericArgs<'hir> {
339 /// The generic arguments for this path segment.
340 pub args: &'hir [GenericArg<'hir>],
341 /// Bindings (equality constraints) on associated types, if present.
342 /// E.g., `Foo<A = Bar>`.
343 pub bindings: &'hir [TypeBinding<'hir>],
344 /// Were arguments written in parenthesized form `Fn(T) -> U`?
345 /// This is required mostly for pretty-printing and diagnostics,
346 /// but also for changing lifetime elision rules to be "function-like".
347 pub parenthesized: bool,
348 /// The span encompassing arguments and the surrounding brackets `<>` or `()`
349 /// Foo<A, B, AssocTy = D> Fn(T, U, V) -> W
350 /// ^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^
351 /// Note that this may be:
352 /// - empty, if there are no generic brackets (but there may be hidden lifetimes)
353 /// - dummy, if this was generated while desugaring
357 impl GenericArgs<'_> {
358 pub const fn none() -> Self {
359 Self { args: &[], bindings: &[], parenthesized: false, span_ext: DUMMY_SP }
362 pub fn inputs(&self) -> &[Ty<'_>] {
363 if self.parenthesized {
364 for arg in self.args {
366 GenericArg::Lifetime(_) => {}
367 GenericArg::Type(ref ty) => {
368 if let TyKind::Tup(ref tys) = ty.kind {
373 GenericArg::Const(_) => {}
374 GenericArg::Infer(_) => {}
378 panic!("GenericArgs::inputs: not a `Fn(T) -> U`");
382 pub fn has_type_params(&self) -> bool {
383 self.args.iter().any(|arg| matches!(arg, GenericArg::Type(_)))
386 pub fn has_err(&self) -> bool {
387 self.args.iter().any(|arg| match arg {
388 GenericArg::Type(ty) => matches!(ty.kind, TyKind::Err),
390 }) || self.bindings.iter().any(|arg| match arg.kind {
391 TypeBindingKind::Equality { ty } => matches!(ty.kind, TyKind::Err),
397 pub fn num_type_params(&self) -> usize {
398 self.args.iter().filter(|arg| matches!(arg, GenericArg::Type(_))).count()
402 pub fn num_lifetime_params(&self) -> usize {
403 self.args.iter().filter(|arg| matches!(arg, GenericArg::Lifetime(_))).count()
407 pub fn has_lifetime_params(&self) -> bool {
408 self.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)))
412 pub fn num_generic_params(&self) -> usize {
413 self.args.iter().filter(|arg| !matches!(arg, GenericArg::Lifetime(_))).count()
416 /// The span encompassing the text inside the surrounding brackets.
417 /// It will also include bindings if they aren't in the form `-> Ret`
418 /// Returns `None` if the span is empty (e.g. no brackets) or dummy
419 pub fn span(&self) -> Option<Span> {
420 let span_ext = self.span_ext()?;
421 Some(span_ext.with_lo(span_ext.lo() + BytePos(1)).with_hi(span_ext.hi() - BytePos(1)))
424 /// Returns span encompassing arguments and their surrounding `<>` or `()`
425 pub fn span_ext(&self) -> Option<Span> {
426 Some(self.span_ext).filter(|span| !span.is_empty())
429 pub fn is_empty(&self) -> bool {
434 /// A modifier on a bound, currently this is only used for `?Sized`, where the
435 /// modifier is `Maybe`. Negative bounds should also be handled here.
436 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
437 #[derive(HashStable_Generic)]
438 pub enum TraitBoundModifier {
444 /// The AST represents all type param bounds as types.
445 /// `typeck::collect::compute_bounds` matches these against
446 /// the "special" built-in traits (see `middle::lang_items`) and
447 /// detects `Copy`, `Send` and `Sync`.
448 #[derive(Clone, Debug, HashStable_Generic)]
449 pub enum GenericBound<'hir> {
450 Trait(PolyTraitRef<'hir>, TraitBoundModifier),
451 // FIXME(davidtwco): Introduce `PolyTraitRef::LangItem`
452 LangItemTrait(LangItem, Span, HirId, &'hir GenericArgs<'hir>),
456 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
457 rustc_data_structures::static_assert_size!(GenericBound<'_>, 48);
459 impl GenericBound<'_> {
460 pub fn trait_ref(&self) -> Option<&TraitRef<'_>> {
462 GenericBound::Trait(data, _) => Some(&data.trait_ref),
467 pub fn span(&self) -> Span {
469 GenericBound::Trait(t, ..) => t.span,
470 GenericBound::LangItemTrait(_, span, ..) => *span,
471 GenericBound::Outlives(l) => l.span,
476 pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
478 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
479 pub enum LifetimeParamKind {
480 // Indicates that the lifetime definition was explicitly declared (e.g., in
481 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
484 // Indicates that the lifetime definition was synthetically added
485 // as a result of an in-band lifetime usage (e.g., in
486 // `fn foo(x: &'a u8) -> &'a u8 { x }`).
489 // Indication that the lifetime was elided (e.g., in both cases in
490 // `fn foo(x: &u8) -> &'_ u8 { x }`).
493 // Indication that the lifetime name was somehow in error.
497 #[derive(Debug, HashStable_Generic)]
498 pub enum GenericParamKind<'hir> {
499 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
501 kind: LifetimeParamKind,
504 default: Option<&'hir Ty<'hir>>,
505 synthetic: Option<SyntheticTyParamKind>,
509 /// Optional default value for the const generic param
510 default: Option<AnonConst>,
514 #[derive(Debug, HashStable_Generic)]
515 pub struct GenericParam<'hir> {
518 pub bounds: GenericBounds<'hir>,
520 pub pure_wrt_drop: bool,
521 pub kind: GenericParamKind<'hir>,
524 impl GenericParam<'hir> {
525 pub fn bounds_span(&self) -> Option<Span> {
526 self.bounds.iter().fold(None, |span, bound| {
527 let span = span.map(|s| s.to(bound.span())).unwrap_or_else(|| bound.span());
535 pub struct GenericParamCount {
536 pub lifetimes: usize,
542 /// Represents lifetimes and type parameters attached to a declaration
543 /// of a function, enum, trait, etc.
544 #[derive(Debug, HashStable_Generic)]
545 pub struct Generics<'hir> {
546 pub params: &'hir [GenericParam<'hir>],
547 pub where_clause: WhereClause<'hir>,
551 impl Generics<'hir> {
552 pub const fn empty() -> Generics<'hir> {
555 where_clause: WhereClause { predicates: &[], span: DUMMY_SP },
560 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'_>> {
561 for param in self.params {
562 if name == param.name.ident().name {
569 pub fn spans(&self) -> MultiSpan {
570 if self.params.is_empty() {
573 self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
578 /// Synthetic type parameters are converted to another form during lowering; this allows
579 /// us to track the original form they had, and is useful for error messages.
580 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
581 #[derive(HashStable_Generic)]
582 pub enum SyntheticTyParamKind {
584 // Created by the `#[rustc_synthetic]` attribute.
588 /// A where-clause in a definition.
589 #[derive(Debug, HashStable_Generic)]
590 pub struct WhereClause<'hir> {
591 pub predicates: &'hir [WherePredicate<'hir>],
592 // Only valid if predicates aren't empty.
596 impl WhereClause<'_> {
597 pub fn span(&self) -> Option<Span> {
598 if self.predicates.is_empty() { None } else { Some(self.span) }
601 /// The `WhereClause` under normal circumstances points at either the predicates or the empty
602 /// space where the `where` clause should be. Only of use for diagnostic suggestions.
603 pub fn span_for_predicates_or_empty_place(&self) -> Span {
607 /// `Span` where further predicates would be suggested, accounting for trailing commas, like
608 /// in `fn foo<T>(t: T) where T: Foo,` so we don't suggest two trailing commas.
609 pub fn tail_span_for_suggestion(&self) -> Span {
610 let end = self.span_for_predicates_or_empty_place().shrink_to_hi();
611 self.predicates.last().map_or(end, |p| p.span()).shrink_to_hi().to(end)
615 /// A single predicate in a where-clause.
616 #[derive(Debug, HashStable_Generic)]
617 pub enum WherePredicate<'hir> {
618 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
619 BoundPredicate(WhereBoundPredicate<'hir>),
620 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
621 RegionPredicate(WhereRegionPredicate<'hir>),
622 /// An equality predicate (unsupported).
623 EqPredicate(WhereEqPredicate<'hir>),
626 impl WherePredicate<'_> {
627 pub fn span(&self) -> Span {
629 WherePredicate::BoundPredicate(p) => p.span,
630 WherePredicate::RegionPredicate(p) => p.span,
631 WherePredicate::EqPredicate(p) => p.span,
636 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
637 #[derive(Debug, HashStable_Generic)]
638 pub struct WhereBoundPredicate<'hir> {
640 /// Any generics from a `for` binding.
641 pub bound_generic_params: &'hir [GenericParam<'hir>],
642 /// The type being bounded.
643 pub bounded_ty: &'hir Ty<'hir>,
644 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
645 pub bounds: GenericBounds<'hir>,
648 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
649 #[derive(Debug, HashStable_Generic)]
650 pub struct WhereRegionPredicate<'hir> {
652 pub lifetime: Lifetime,
653 pub bounds: GenericBounds<'hir>,
656 /// An equality predicate (e.g., `T = int`); currently unsupported.
657 #[derive(Debug, HashStable_Generic)]
658 pub struct WhereEqPredicate<'hir> {
661 pub lhs_ty: &'hir Ty<'hir>,
662 pub rhs_ty: &'hir Ty<'hir>,
665 /// The top-level data structure that stores the entire contents of
666 /// the crate currently being compiled.
668 /// For more details, see the [rustc dev guide].
670 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
672 pub struct Crate<'hir> {
673 pub owners: IndexVec<LocalDefId, Option<OwnerNode<'hir>>>,
674 pub bodies: BTreeMap<BodyId, Body<'hir>>,
676 /// Map indicating what traits are in scope for places where this
677 /// is relevant; generated by resolve.
678 pub trait_map: FxHashMap<LocalDefId, FxHashMap<ItemLocalId, Box<[TraitCandidate]>>>,
680 /// Collected attributes from HIR nodes.
681 pub attrs: BTreeMap<HirId, &'hir [Attribute]>,
685 pub fn module(&self) -> &'hir Mod<'hir> {
686 if let Some(OwnerNode::Crate(m)) = self.owners[CRATE_DEF_ID] { m } else { panic!() }
689 pub fn item(&self, id: ItemId) -> &'hir Item<'hir> {
690 self.owners[id.def_id].as_ref().unwrap().expect_item()
693 pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> {
694 self.owners[id.def_id].as_ref().unwrap().expect_trait_item()
697 pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> {
698 self.owners[id.def_id].as_ref().unwrap().expect_impl_item()
701 pub fn foreign_item(&self, id: ForeignItemId) -> &'hir ForeignItem<'hir> {
702 self.owners[id.def_id].as_ref().unwrap().expect_foreign_item()
705 pub fn body(&self, id: BodyId) -> &Body<'hir> {
710 /// A block of statements `{ .. }`, which may have a label (in this case the
711 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
712 /// the `rules` being anything but `DefaultBlock`.
713 #[derive(Debug, HashStable_Generic)]
714 pub struct Block<'hir> {
715 /// Statements in a block.
716 pub stmts: &'hir [Stmt<'hir>],
717 /// An expression at the end of the block
718 /// without a semicolon, if any.
719 pub expr: Option<&'hir Expr<'hir>>,
720 #[stable_hasher(ignore)]
722 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
723 pub rules: BlockCheckMode,
725 /// If true, then there may exist `break 'a` values that aim to
726 /// break out of this block early.
727 /// Used by `'label: {}` blocks and by `try {}` blocks.
728 pub targeted_by_break: bool,
731 #[derive(Debug, HashStable_Generic)]
732 pub struct Pat<'hir> {
733 #[stable_hasher(ignore)]
735 pub kind: PatKind<'hir>,
737 // Whether to use default binding modes.
738 // At present, this is false only for destructuring assignment.
739 pub default_binding_modes: bool,
742 impl<'hir> Pat<'hir> {
743 // FIXME(#19596) this is a workaround, but there should be a better way
744 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) -> bool {
751 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
752 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
753 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
754 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
755 Slice(before, slice, after) => {
756 before.iter().chain(slice).chain(after.iter()).all(|p| p.walk_short_(it))
761 /// Walk the pattern in left-to-right order,
762 /// short circuiting (with `.all(..)`) if `false` is returned.
764 /// Note that when visiting e.g. `Tuple(ps)`,
765 /// if visiting `ps[0]` returns `false`,
766 /// then `ps[1]` will not be visited.
767 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) -> bool {
768 self.walk_short_(&mut it)
771 // FIXME(#19596) this is a workaround, but there should be a better way
772 fn walk_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) {
779 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
780 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
781 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
782 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
783 Slice(before, slice, after) => {
784 before.iter().chain(slice).chain(after.iter()).for_each(|p| p.walk_(it))
789 /// Walk the pattern in left-to-right order.
791 /// If `it(pat)` returns `false`, the children are not visited.
792 pub fn walk(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) {
796 /// Walk the pattern in left-to-right order.
798 /// If you always want to recurse, prefer this method over `walk`.
799 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
807 /// A single field in a struct pattern.
809 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
810 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
811 /// except `is_shorthand` is true.
812 #[derive(Debug, HashStable_Generic)]
813 pub struct PatField<'hir> {
814 #[stable_hasher(ignore)]
816 /// The identifier for the field.
817 #[stable_hasher(project(name))]
819 /// The pattern the field is destructured to.
820 pub pat: &'hir Pat<'hir>,
821 pub is_shorthand: bool,
825 /// Explicit binding annotations given in the HIR for a binding. Note
826 /// that this is not the final binding *mode* that we infer after type
828 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
829 pub enum BindingAnnotation {
830 /// No binding annotation given: this means that the final binding mode
831 /// will depend on whether we have skipped through a `&` reference
832 /// when matching. For example, the `x` in `Some(x)` will have binding
833 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
834 /// ultimately be inferred to be by-reference.
836 /// Note that implicit reference skipping is not implemented yet (#42640).
839 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
842 /// Annotated as `ref`, like `ref x`
845 /// Annotated as `ref mut x`.
849 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
855 impl fmt::Display for RangeEnd {
856 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
857 f.write_str(match self {
858 RangeEnd::Included => "..=",
859 RangeEnd::Excluded => "..",
864 #[derive(Debug, HashStable_Generic)]
865 pub enum PatKind<'hir> {
866 /// Represents a wildcard pattern (i.e., `_`).
869 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
870 /// The `HirId` is the canonical ID for the variable being bound,
871 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
872 /// which is the pattern ID of the first `x`.
873 Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
875 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
876 /// The `bool` is `true` in the presence of a `..`.
877 Struct(QPath<'hir>, &'hir [PatField<'hir>], bool),
879 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
880 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
881 /// `0 <= position <= subpats.len()`
882 TupleStruct(QPath<'hir>, &'hir [Pat<'hir>], Option<usize>),
884 /// An or-pattern `A | B | C`.
885 /// Invariant: `pats.len() >= 2`.
886 Or(&'hir [Pat<'hir>]),
888 /// A path pattern for a unit struct/variant or a (maybe-associated) constant.
891 /// A tuple pattern (e.g., `(a, b)`).
892 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
893 /// `0 <= position <= subpats.len()`
894 Tuple(&'hir [Pat<'hir>], Option<usize>),
897 Box(&'hir Pat<'hir>),
899 /// A reference pattern (e.g., `&mut (a, b)`).
900 Ref(&'hir Pat<'hir>, Mutability),
903 Lit(&'hir Expr<'hir>),
905 /// A range pattern (e.g., `1..=2` or `1..2`).
906 Range(Option<&'hir Expr<'hir>>, Option<&'hir Expr<'hir>>, RangeEnd),
908 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
910 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
911 /// If `slice` exists, then `after` can be non-empty.
913 /// The representation for e.g., `[a, b, .., c, d]` is:
915 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
917 Slice(&'hir [Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [Pat<'hir>]),
920 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
922 /// The `+` operator (addition).
924 /// The `-` operator (subtraction).
926 /// The `*` operator (multiplication).
928 /// The `/` operator (division).
930 /// The `%` operator (modulus).
932 /// The `&&` operator (logical and).
934 /// The `||` operator (logical or).
936 /// The `^` operator (bitwise xor).
938 /// The `&` operator (bitwise and).
940 /// The `|` operator (bitwise or).
942 /// The `<<` operator (shift left).
944 /// The `>>` operator (shift right).
946 /// The `==` operator (equality).
948 /// The `<` operator (less than).
950 /// The `<=` operator (less than or equal to).
952 /// The `!=` operator (not equal to).
954 /// The `>=` operator (greater than or equal to).
956 /// The `>` operator (greater than).
961 pub fn as_str(self) -> &'static str {
963 BinOpKind::Add => "+",
964 BinOpKind::Sub => "-",
965 BinOpKind::Mul => "*",
966 BinOpKind::Div => "/",
967 BinOpKind::Rem => "%",
968 BinOpKind::And => "&&",
969 BinOpKind::Or => "||",
970 BinOpKind::BitXor => "^",
971 BinOpKind::BitAnd => "&",
972 BinOpKind::BitOr => "|",
973 BinOpKind::Shl => "<<",
974 BinOpKind::Shr => ">>",
975 BinOpKind::Eq => "==",
976 BinOpKind::Lt => "<",
977 BinOpKind::Le => "<=",
978 BinOpKind::Ne => "!=",
979 BinOpKind::Ge => ">=",
980 BinOpKind::Gt => ">",
984 pub fn is_lazy(self) -> bool {
985 matches!(self, BinOpKind::And | BinOpKind::Or)
988 pub fn is_shift(self) -> bool {
989 matches!(self, BinOpKind::Shl | BinOpKind::Shr)
992 pub fn is_comparison(self) -> bool {
999 | BinOpKind::Ge => true,
1011 | BinOpKind::Shr => false,
1015 /// Returns `true` if the binary operator takes its arguments by value.
1016 pub fn is_by_value(self) -> bool {
1017 !self.is_comparison()
1021 impl Into<ast::BinOpKind> for BinOpKind {
1022 fn into(self) -> ast::BinOpKind {
1024 BinOpKind::Add => ast::BinOpKind::Add,
1025 BinOpKind::Sub => ast::BinOpKind::Sub,
1026 BinOpKind::Mul => ast::BinOpKind::Mul,
1027 BinOpKind::Div => ast::BinOpKind::Div,
1028 BinOpKind::Rem => ast::BinOpKind::Rem,
1029 BinOpKind::And => ast::BinOpKind::And,
1030 BinOpKind::Or => ast::BinOpKind::Or,
1031 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1032 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1033 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1034 BinOpKind::Shl => ast::BinOpKind::Shl,
1035 BinOpKind::Shr => ast::BinOpKind::Shr,
1036 BinOpKind::Eq => ast::BinOpKind::Eq,
1037 BinOpKind::Lt => ast::BinOpKind::Lt,
1038 BinOpKind::Le => ast::BinOpKind::Le,
1039 BinOpKind::Ne => ast::BinOpKind::Ne,
1040 BinOpKind::Ge => ast::BinOpKind::Ge,
1041 BinOpKind::Gt => ast::BinOpKind::Gt,
1046 pub type BinOp = Spanned<BinOpKind>;
1048 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1050 /// The `*` operator (deferencing).
1052 /// The `!` operator (logical negation).
1054 /// The `-` operator (negation).
1059 pub fn as_str(self) -> &'static str {
1067 /// Returns `true` if the unary operator takes its argument by value.
1068 pub fn is_by_value(self) -> bool {
1069 matches!(self, Self::Neg | Self::Not)
1074 #[derive(Debug, HashStable_Generic)]
1075 pub struct Stmt<'hir> {
1077 pub kind: StmtKind<'hir>,
1081 /// The contents of a statement.
1082 #[derive(Debug, HashStable_Generic)]
1083 pub enum StmtKind<'hir> {
1084 /// A local (`let`) binding.
1085 Local(&'hir Local<'hir>),
1087 /// An item binding.
1090 /// An expression without a trailing semi-colon (must have unit type).
1091 Expr(&'hir Expr<'hir>),
1093 /// An expression with a trailing semi-colon (may have any type).
1094 Semi(&'hir Expr<'hir>),
1097 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1098 #[derive(Debug, HashStable_Generic)]
1099 pub struct Local<'hir> {
1100 pub pat: &'hir Pat<'hir>,
1101 /// Type annotation, if any (otherwise the type will be inferred).
1102 pub ty: Option<&'hir Ty<'hir>>,
1103 /// Initializer expression to set the value, if any.
1104 pub init: Option<&'hir Expr<'hir>>,
1107 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1108 /// desugaring. Otherwise will be `Normal`.
1109 pub source: LocalSource,
1112 /// Represents a single arm of a `match` expression, e.g.
1113 /// `<pat> (if <guard>) => <body>`.
1114 #[derive(Debug, HashStable_Generic)]
1115 pub struct Arm<'hir> {
1116 #[stable_hasher(ignore)]
1119 /// If this pattern and the optional guard matches, then `body` is evaluated.
1120 pub pat: &'hir Pat<'hir>,
1121 /// Optional guard clause.
1122 pub guard: Option<Guard<'hir>>,
1123 /// The expression the arm evaluates to if this arm matches.
1124 pub body: &'hir Expr<'hir>,
1127 #[derive(Debug, HashStable_Generic)]
1128 pub enum Guard<'hir> {
1129 If(&'hir Expr<'hir>),
1130 // FIXME use ExprKind::Let for this.
1131 IfLet(&'hir Pat<'hir>, &'hir Expr<'hir>),
1134 #[derive(Debug, HashStable_Generic)]
1135 pub struct ExprField<'hir> {
1136 #[stable_hasher(ignore)]
1139 pub expr: &'hir Expr<'hir>,
1141 pub is_shorthand: bool,
1144 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1145 pub enum BlockCheckMode {
1147 UnsafeBlock(UnsafeSource),
1150 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1151 pub enum UnsafeSource {
1156 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Hash, Debug)]
1161 /// The body of a function, closure, or constant value. In the case of
1162 /// a function, the body contains not only the function body itself
1163 /// (which is an expression), but also the argument patterns, since
1164 /// those are something that the caller doesn't really care about.
1169 /// fn foo((x, y): (u32, u32)) -> u32 {
1174 /// Here, the `Body` associated with `foo()` would contain:
1176 /// - an `params` array containing the `(x, y)` pattern
1177 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1178 /// - `generator_kind` would be `None`
1180 /// All bodies have an **owner**, which can be accessed via the HIR
1181 /// map using `body_owner_def_id()`.
1183 pub struct Body<'hir> {
1184 pub params: &'hir [Param<'hir>],
1185 pub value: Expr<'hir>,
1186 pub generator_kind: Option<GeneratorKind>,
1190 pub fn id(&self) -> BodyId {
1191 BodyId { hir_id: self.value.hir_id }
1194 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1199 /// The type of source expression that caused this generator to be created.
1212 pub enum GeneratorKind {
1213 /// An explicit `async` block or the body of an async function.
1214 Async(AsyncGeneratorKind),
1216 /// A generator literal created via a `yield` inside a closure.
1220 impl fmt::Display for GeneratorKind {
1221 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1223 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1224 GeneratorKind::Gen => f.write_str("generator"),
1229 impl GeneratorKind {
1230 pub fn descr(&self) -> &'static str {
1232 GeneratorKind::Async(ask) => ask.descr(),
1233 GeneratorKind::Gen => "generator",
1238 /// In the case of a generator created as part of an async construct,
1239 /// which kind of async construct caused it to be created?
1241 /// This helps error messages but is also used to drive coercions in
1242 /// type-checking (see #60424).
1255 pub enum AsyncGeneratorKind {
1256 /// An explicit `async` block written by the user.
1259 /// An explicit `async` block written by the user.
1262 /// The `async` block generated as the body of an async function.
1266 impl fmt::Display for AsyncGeneratorKind {
1267 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1268 f.write_str(match self {
1269 AsyncGeneratorKind::Block => "`async` block",
1270 AsyncGeneratorKind::Closure => "`async` closure body",
1271 AsyncGeneratorKind::Fn => "`async fn` body",
1276 impl AsyncGeneratorKind {
1277 pub fn descr(&self) -> &'static str {
1279 AsyncGeneratorKind::Block => "`async` block",
1280 AsyncGeneratorKind::Closure => "`async` closure body",
1281 AsyncGeneratorKind::Fn => "`async fn` body",
1286 #[derive(Copy, Clone, Debug)]
1287 pub enum BodyOwnerKind {
1288 /// Functions and methods.
1294 /// Constants and associated constants.
1297 /// Initializer of a `static` item.
1301 impl BodyOwnerKind {
1302 pub fn is_fn_or_closure(self) -> bool {
1304 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1305 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1310 /// The kind of an item that requires const-checking.
1311 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1312 pub enum ConstContext {
1316 /// A `static` or `static mut`.
1319 /// A `const`, associated `const`, or other const context.
1321 /// Other contexts include:
1322 /// - Array length expressions
1323 /// - Enum discriminants
1324 /// - Const generics
1326 /// For the most part, other contexts are treated just like a regular `const`, so they are
1327 /// lumped into the same category.
1332 /// A description of this const context that can appear between backticks in an error message.
1334 /// E.g. `const` or `static mut`.
1335 pub fn keyword_name(self) -> &'static str {
1337 Self::Const => "const",
1338 Self::Static(Mutability::Not) => "static",
1339 Self::Static(Mutability::Mut) => "static mut",
1340 Self::ConstFn => "const fn",
1345 /// A colloquial, trivially pluralizable description of this const context for use in error
1347 impl fmt::Display for ConstContext {
1348 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1350 Self::Const => write!(f, "constant"),
1351 Self::Static(_) => write!(f, "static"),
1352 Self::ConstFn => write!(f, "constant function"),
1358 pub type Lit = Spanned<LitKind>;
1360 /// A constant (expression) that's not an item or associated item,
1361 /// but needs its own `DefId` for type-checking, const-eval, etc.
1362 /// These are usually found nested inside types (e.g., array lengths)
1363 /// or expressions (e.g., repeat counts), and also used to define
1364 /// explicit discriminant values for enum variants.
1366 /// You can check if this anon const is a default in a const param
1367 /// `const N: usize = { ... }` with `tcx.hir().opt_const_param_default_param_hir_id(..)`
1368 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1369 pub struct AnonConst {
1376 pub struct Expr<'hir> {
1378 pub kind: ExprKind<'hir>,
1383 pub fn precedence(&self) -> ExprPrecedence {
1385 ExprKind::Box(_) => ExprPrecedence::Box,
1386 ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1387 ExprKind::Array(_) => ExprPrecedence::Array,
1388 ExprKind::Call(..) => ExprPrecedence::Call,
1389 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1390 ExprKind::Tup(_) => ExprPrecedence::Tup,
1391 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1392 ExprKind::Unary(..) => ExprPrecedence::Unary,
1393 ExprKind::Lit(_) => ExprPrecedence::Lit,
1394 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1395 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1396 ExprKind::If(..) => ExprPrecedence::If,
1397 ExprKind::Let(..) => ExprPrecedence::Let,
1398 ExprKind::Loop(..) => ExprPrecedence::Loop,
1399 ExprKind::Match(..) => ExprPrecedence::Match,
1400 ExprKind::Closure(..) => ExprPrecedence::Closure,
1401 ExprKind::Block(..) => ExprPrecedence::Block,
1402 ExprKind::Assign(..) => ExprPrecedence::Assign,
1403 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1404 ExprKind::Field(..) => ExprPrecedence::Field,
1405 ExprKind::Index(..) => ExprPrecedence::Index,
1406 ExprKind::Path(..) => ExprPrecedence::Path,
1407 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1408 ExprKind::Break(..) => ExprPrecedence::Break,
1409 ExprKind::Continue(..) => ExprPrecedence::Continue,
1410 ExprKind::Ret(..) => ExprPrecedence::Ret,
1411 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1412 ExprKind::LlvmInlineAsm(..) => ExprPrecedence::InlineAsm,
1413 ExprKind::Struct(..) => ExprPrecedence::Struct,
1414 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1415 ExprKind::Yield(..) => ExprPrecedence::Yield,
1416 ExprKind::Err => ExprPrecedence::Err,
1420 // Whether this looks like a place expr, without checking for deref
1422 // This will return `true` in some potentially surprising cases such as
1423 // `CONSTANT.field`.
1424 pub fn is_syntactic_place_expr(&self) -> bool {
1425 self.is_place_expr(|_| true)
1428 /// Whether this is a place expression.
1430 /// `allow_projections_from` should return `true` if indexing a field or index expression based
1431 /// on the given expression should be considered a place expression.
1432 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1434 ExprKind::Path(QPath::Resolved(_, ref path)) => {
1435 matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static, _) | Res::Err)
1438 // Type ascription inherits its place expression kind from its
1440 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1441 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1443 ExprKind::Unary(UnOp::Deref, _) => true,
1445 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1446 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1449 // Lang item paths cannot currently be local variables or statics.
1450 ExprKind::Path(QPath::LangItem(..)) => false,
1452 // Partially qualified paths in expressions can only legally
1453 // refer to associated items which are always rvalues.
1454 ExprKind::Path(QPath::TypeRelative(..))
1455 | ExprKind::Call(..)
1456 | ExprKind::MethodCall(..)
1457 | ExprKind::Struct(..)
1460 | ExprKind::Match(..)
1461 | ExprKind::Closure(..)
1462 | ExprKind::Block(..)
1463 | ExprKind::Repeat(..)
1464 | ExprKind::Array(..)
1465 | ExprKind::Break(..)
1466 | ExprKind::Continue(..)
1469 | ExprKind::Loop(..)
1470 | ExprKind::Assign(..)
1471 | ExprKind::InlineAsm(..)
1472 | ExprKind::LlvmInlineAsm(..)
1473 | ExprKind::AssignOp(..)
1475 | ExprKind::ConstBlock(..)
1476 | ExprKind::Unary(..)
1478 | ExprKind::AddrOf(..)
1479 | ExprKind::Binary(..)
1480 | ExprKind::Yield(..)
1481 | ExprKind::Cast(..)
1482 | ExprKind::DropTemps(..)
1483 | ExprKind::Err => false,
1487 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1488 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1489 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1490 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1491 /// beyond remembering to call this function before doing analysis on it.
1492 pub fn peel_drop_temps(&self) -> &Self {
1493 let mut expr = self;
1494 while let ExprKind::DropTemps(inner) = &expr.kind {
1500 pub fn peel_blocks(&self) -> &Self {
1501 let mut expr = self;
1502 while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind {
1508 pub fn can_have_side_effects(&self) -> bool {
1509 match self.peel_drop_temps().kind {
1510 ExprKind::Path(_) | ExprKind::Lit(_) => false,
1511 ExprKind::Type(base, _)
1512 | ExprKind::Unary(_, base)
1513 | ExprKind::Field(base, _)
1514 | ExprKind::Index(base, _)
1515 | ExprKind::AddrOf(.., base)
1516 | ExprKind::Cast(base, _) => {
1517 // This isn't exactly true for `Index` and all `Unnary`, but we are using this
1518 // method exclusively for diagnostics and there's a *cultural* pressure against
1519 // them being used only for its side-effects.
1520 base.can_have_side_effects()
1522 ExprKind::Struct(_, fields, init) => fields
1524 .map(|field| field.expr)
1525 .chain(init.into_iter())
1526 .all(|e| e.can_have_side_effects()),
1528 ExprKind::Array(args)
1529 | ExprKind::Tup(args)
1533 ExprKind::Path(QPath::Resolved(
1535 Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. },
1540 ) => args.iter().all(|arg| arg.can_have_side_effects()),
1542 | ExprKind::Match(..)
1543 | ExprKind::MethodCall(..)
1544 | ExprKind::Call(..)
1545 | ExprKind::Closure(..)
1546 | ExprKind::Block(..)
1547 | ExprKind::Repeat(..)
1548 | ExprKind::Break(..)
1549 | ExprKind::Continue(..)
1552 | ExprKind::Loop(..)
1553 | ExprKind::Assign(..)
1554 | ExprKind::InlineAsm(..)
1555 | ExprKind::LlvmInlineAsm(..)
1556 | ExprKind::AssignOp(..)
1557 | ExprKind::ConstBlock(..)
1559 | ExprKind::Binary(..)
1560 | ExprKind::Yield(..)
1561 | ExprKind::DropTemps(..)
1562 | ExprKind::Err => true,
1567 /// Checks if the specified expression is a built-in range literal.
1568 /// (See: `LoweringContext::lower_expr()`).
1569 pub fn is_range_literal(expr: &Expr<'_>) -> bool {
1571 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1572 ExprKind::Struct(ref qpath, _, _) => matches!(
1577 | LangItem::RangeFrom
1578 | LangItem::RangeFull
1579 | LangItem::RangeToInclusive,
1584 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1585 ExprKind::Call(ref func, _) => {
1586 matches!(func.kind, ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, _)))
1593 #[derive(Debug, HashStable_Generic)]
1594 pub enum ExprKind<'hir> {
1595 /// A `box x` expression.
1596 Box(&'hir Expr<'hir>),
1597 /// Allow anonymous constants from an inline `const` block
1598 ConstBlock(AnonConst),
1599 /// An array (e.g., `[a, b, c, d]`).
1600 Array(&'hir [Expr<'hir>]),
1601 /// A function call.
1603 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1604 /// and the second field is the list of arguments.
1605 /// This also represents calling the constructor of
1606 /// tuple-like ADTs such as tuple structs and enum variants.
1607 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1608 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1610 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1611 /// (within the angle brackets).
1612 /// The first element of the vector of `Expr`s is the expression that evaluates
1613 /// to the object on which the method is being called on (the receiver),
1614 /// and the remaining elements are the rest of the arguments.
1615 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1616 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1617 /// The final `Span` represents the span of the function and arguments
1618 /// (e.g. `foo::<Bar, Baz>(a, b, c, d)` in `x.foo::<Bar, Baz>(a, b, c, d)`
1620 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1621 /// the `hir_id` of the `MethodCall` node itself.
1623 /// [`type_dependent_def_id`]: ../ty/struct.TypeckResults.html#method.type_dependent_def_id
1624 MethodCall(&'hir PathSegment<'hir>, Span, &'hir [Expr<'hir>], Span),
1625 /// A tuple (e.g., `(a, b, c, d)`).
1626 Tup(&'hir [Expr<'hir>]),
1627 /// A binary operation (e.g., `a + b`, `a * b`).
1628 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1629 /// A unary operation (e.g., `!x`, `*x`).
1630 Unary(UnOp, &'hir Expr<'hir>),
1631 /// A literal (e.g., `1`, `"foo"`).
1633 /// A cast (e.g., `foo as f64`).
1634 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1635 /// A type reference (e.g., `Foo`).
1636 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1637 /// Wraps the expression in a terminating scope.
1638 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1640 /// This construct only exists to tweak the drop order in HIR lowering.
1641 /// An example of that is the desugaring of `for` loops.
1642 DropTemps(&'hir Expr<'hir>),
1643 /// A `let $pat = $expr` expression.
1645 /// These are not `Local` and only occur as expressions.
1646 /// The `let Some(x) = foo()` in `if let Some(x) = foo()` is an example of `Let(..)`.
1647 Let(&'hir Pat<'hir>, &'hir Expr<'hir>, Span),
1648 /// An `if` block, with an optional else block.
1650 /// I.e., `if <expr> { <expr> } else { <expr> }`.
1651 If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
1652 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1654 /// I.e., `'label: loop { <block> }`.
1656 /// The `Span` is the loop header (`for x in y`/`while let pat = expr`).
1657 Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span),
1658 /// A `match` block, with a source that indicates whether or not it is
1659 /// the result of a desugaring, and if so, which kind.
1660 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1661 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1663 /// The `Span` is the argument block `|...|`.
1665 /// This may also be a generator literal or an `async block` as indicated by the
1666 /// `Option<Movability>`.
1667 Closure(CaptureBy, &'hir FnDecl<'hir>, BodyId, Span, Option<Movability>),
1668 /// A block (e.g., `'label: { ... }`).
1669 Block(&'hir Block<'hir>, Option<Label>),
1671 /// An assignment (e.g., `a = foo()`).
1672 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1673 /// An assignment with an operator.
1676 AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1677 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1678 Field(&'hir Expr<'hir>, Ident),
1679 /// An indexing operation (`foo[2]`).
1680 Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1682 /// Path to a definition, possibly containing lifetime or type parameters.
1685 /// A referencing operation (i.e., `&a` or `&mut a`).
1686 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1687 /// A `break`, with an optional label to break.
1688 Break(Destination, Option<&'hir Expr<'hir>>),
1689 /// A `continue`, with an optional label.
1690 Continue(Destination),
1691 /// A `return`, with an optional value to be returned.
1692 Ret(Option<&'hir Expr<'hir>>),
1694 /// Inline assembly (from `asm!`), with its outputs and inputs.
1695 InlineAsm(&'hir InlineAsm<'hir>),
1696 /// Inline assembly (from `llvm_asm!`), with its outputs and inputs.
1697 LlvmInlineAsm(&'hir LlvmInlineAsm<'hir>),
1699 /// A struct or struct-like variant literal expression.
1701 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1702 /// where `base` is the `Option<Expr>`.
1703 Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], Option<&'hir Expr<'hir>>),
1705 /// An array literal constructed from one repeated element.
1707 /// E.g., `[1; 5]`. The first expression is the element
1708 /// to be repeated; the second is the number of times to repeat it.
1709 Repeat(&'hir Expr<'hir>, AnonConst),
1711 /// A suspension point for generators (i.e., `yield <expr>`).
1712 Yield(&'hir Expr<'hir>, YieldSource),
1714 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1718 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1720 /// To resolve the path to a `DefId`, call [`qpath_res`].
1722 /// [`qpath_res`]: ../rustc_middle/ty/struct.TypeckResults.html#method.qpath_res
1723 #[derive(Debug, HashStable_Generic)]
1724 pub enum QPath<'hir> {
1725 /// Path to a definition, optionally "fully-qualified" with a `Self`
1726 /// type, if the path points to an associated item in a trait.
1728 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1729 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1730 /// even though they both have the same two-segment `Clone::clone` `Path`.
1731 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
1733 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1734 /// Will be resolved by type-checking to an associated item.
1736 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1737 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1738 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1739 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
1741 /// Reference to a `#[lang = "foo"]` item.
1742 LangItem(LangItem, Span),
1745 impl<'hir> QPath<'hir> {
1746 /// Returns the span of this `QPath`.
1747 pub fn span(&self) -> Span {
1749 QPath::Resolved(_, path) => path.span,
1750 QPath::TypeRelative(qself, ps) => qself.span.to(ps.ident.span),
1751 QPath::LangItem(_, span) => span,
1755 /// Returns the span of the qself of this `QPath`. For example, `()` in
1756 /// `<() as Trait>::method`.
1757 pub fn qself_span(&self) -> Span {
1759 QPath::Resolved(_, path) => path.span,
1760 QPath::TypeRelative(qself, _) => qself.span,
1761 QPath::LangItem(_, span) => span,
1765 /// Returns the span of the last segment of this `QPath`. For example, `method` in
1766 /// `<() as Trait>::method`.
1767 pub fn last_segment_span(&self) -> Span {
1769 QPath::Resolved(_, path) => path.segments.last().unwrap().ident.span,
1770 QPath::TypeRelative(_, segment) => segment.ident.span,
1771 QPath::LangItem(_, span) => span,
1776 /// Hints at the original code for a let statement.
1777 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1778 pub enum LocalSource {
1779 /// A `match _ { .. }`.
1781 /// A desugared `for _ in _ { .. }` loop.
1783 /// When lowering async functions, we create locals within the `async move` so that
1784 /// all parameters are dropped after the future is polled.
1786 /// ```ignore (pseudo-Rust)
1787 /// async fn foo(<pattern> @ x: Type) {
1789 /// let <pattern> = x;
1794 /// A desugared `<expr>.await`.
1796 /// A desugared `expr = expr`, where the LHS is a tuple, struct or array.
1797 /// The span is that of the `=` sign.
1798 AssignDesugar(Span),
1801 /// Hints at the original code for a `match _ { .. }`.
1802 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
1803 #[derive(HashStable_Generic)]
1804 pub enum MatchSource {
1805 /// A `match _ { .. }`.
1807 /// A desugared `for _ in _ { .. }` loop.
1809 /// A desugared `?` operator.
1811 /// A desugared `<expr>.await`.
1817 pub const fn name(self) -> &'static str {
1821 ForLoopDesugar => "for",
1823 AwaitDesugar => ".await",
1828 /// The loop type that yielded an `ExprKind::Loop`.
1829 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1830 pub enum LoopSource {
1831 /// A `loop { .. }` loop.
1833 /// A `while _ { .. }` loop.
1835 /// A `for _ in _ { .. }` loop.
1840 pub fn name(self) -> &'static str {
1842 LoopSource::Loop => "loop",
1843 LoopSource::While => "while",
1844 LoopSource::ForLoop => "for",
1849 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1850 pub enum LoopIdError {
1852 UnlabeledCfInWhileCondition,
1856 impl fmt::Display for LoopIdError {
1857 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1858 f.write_str(match self {
1859 LoopIdError::OutsideLoopScope => "not inside loop scope",
1860 LoopIdError::UnlabeledCfInWhileCondition => {
1861 "unlabeled control flow (break or continue) in while condition"
1863 LoopIdError::UnresolvedLabel => "label not found",
1868 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1869 pub struct Destination {
1870 // This is `Some(_)` iff there is an explicit user-specified `label
1871 pub label: Option<Label>,
1873 // These errors are caught and then reported during the diagnostics pass in
1874 // librustc_passes/loops.rs
1875 pub target_id: Result<HirId, LoopIdError>,
1878 /// The yield kind that caused an `ExprKind::Yield`.
1879 #[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
1880 pub enum YieldSource {
1881 /// An `<expr>.await`.
1882 Await { expr: Option<HirId> },
1883 /// A plain `yield`.
1888 pub fn is_await(&self) -> bool {
1890 YieldSource::Await { .. } => true,
1891 YieldSource::Yield => false,
1896 impl fmt::Display for YieldSource {
1897 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1898 f.write_str(match self {
1899 YieldSource::Await { .. } => "`await`",
1900 YieldSource::Yield => "`yield`",
1905 impl From<GeneratorKind> for YieldSource {
1906 fn from(kind: GeneratorKind) -> Self {
1908 // Guess based on the kind of the current generator.
1909 GeneratorKind::Gen => Self::Yield,
1910 GeneratorKind::Async(_) => Self::Await { expr: None },
1915 // N.B., if you change this, you'll probably want to change the corresponding
1916 // type structure in middle/ty.rs as well.
1917 #[derive(Debug, HashStable_Generic)]
1918 pub struct MutTy<'hir> {
1919 pub ty: &'hir Ty<'hir>,
1920 pub mutbl: Mutability,
1923 /// Represents a function's signature in a trait declaration,
1924 /// trait implementation, or a free function.
1925 #[derive(Debug, HashStable_Generic)]
1926 pub struct FnSig<'hir> {
1927 pub header: FnHeader,
1928 pub decl: &'hir FnDecl<'hir>,
1932 // The bodies for items are stored "out of line", in a separate
1933 // hashmap in the `Crate`. Here we just record the hir-id of the item
1934 // so it can fetched later.
1935 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
1936 pub struct TraitItemId {
1937 pub def_id: LocalDefId,
1942 pub fn hir_id(&self) -> HirId {
1943 // Items are always HIR owners.
1944 HirId::make_owner(self.def_id)
1948 /// Represents an item declaration within a trait declaration,
1949 /// possibly including a default implementation. A trait item is
1950 /// either required (meaning it doesn't have an implementation, just a
1951 /// signature) or provided (meaning it has a default implementation).
1953 pub struct TraitItem<'hir> {
1955 pub def_id: LocalDefId,
1956 pub generics: Generics<'hir>,
1957 pub kind: TraitItemKind<'hir>,
1961 impl TraitItem<'_> {
1963 pub fn hir_id(&self) -> HirId {
1964 // Items are always HIR owners.
1965 HirId::make_owner(self.def_id)
1968 pub fn trait_item_id(&self) -> TraitItemId {
1969 TraitItemId { def_id: self.def_id }
1973 /// Represents a trait method's body (or just argument names).
1974 #[derive(Encodable, Debug, HashStable_Generic)]
1975 pub enum TraitFn<'hir> {
1976 /// No default body in the trait, just a signature.
1977 Required(&'hir [Ident]),
1979 /// Both signature and body are provided in the trait.
1983 /// Represents a trait method or associated constant or type
1984 #[derive(Debug, HashStable_Generic)]
1985 pub enum TraitItemKind<'hir> {
1986 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
1987 Const(&'hir Ty<'hir>, Option<BodyId>),
1988 /// An associated function with an optional body.
1989 Fn(FnSig<'hir>, TraitFn<'hir>),
1990 /// An associated type with (possibly empty) bounds and optional concrete
1992 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
1995 // The bodies for items are stored "out of line", in a separate
1996 // hashmap in the `Crate`. Here we just record the hir-id of the item
1997 // so it can fetched later.
1998 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
1999 pub struct ImplItemId {
2000 pub def_id: LocalDefId,
2005 pub fn hir_id(&self) -> HirId {
2006 // Items are always HIR owners.
2007 HirId::make_owner(self.def_id)
2011 /// Represents anything within an `impl` block.
2013 pub struct ImplItem<'hir> {
2015 pub def_id: LocalDefId,
2016 pub vis: Visibility<'hir>,
2017 pub defaultness: Defaultness,
2018 pub generics: Generics<'hir>,
2019 pub kind: ImplItemKind<'hir>,
2025 pub fn hir_id(&self) -> HirId {
2026 // Items are always HIR owners.
2027 HirId::make_owner(self.def_id)
2030 pub fn impl_item_id(&self) -> ImplItemId {
2031 ImplItemId { def_id: self.def_id }
2035 /// Represents various kinds of content within an `impl`.
2036 #[derive(Debug, HashStable_Generic)]
2037 pub enum ImplItemKind<'hir> {
2038 /// An associated constant of the given type, set to the constant result
2039 /// of the expression.
2040 Const(&'hir Ty<'hir>, BodyId),
2041 /// An associated function implementation with the given signature and body.
2042 Fn(FnSig<'hir>, BodyId),
2043 /// An associated type.
2044 TyAlias(&'hir Ty<'hir>),
2047 // The name of the associated type for `Fn` return types.
2048 pub const FN_OUTPUT_NAME: Symbol = sym::Output;
2050 /// Bind a type to an associated type (i.e., `A = Foo`).
2052 /// Bindings like `A: Debug` are represented as a special type `A =
2053 /// $::Debug` that is understood by the astconv code.
2055 /// FIXME(alexreg): why have a separate type for the binding case,
2056 /// wouldn't it be better to make the `ty` field an enum like the
2060 /// enum TypeBindingKind {
2065 #[derive(Debug, HashStable_Generic)]
2066 pub struct TypeBinding<'hir> {
2068 #[stable_hasher(project(name))]
2070 pub gen_args: &'hir GenericArgs<'hir>,
2071 pub kind: TypeBindingKind<'hir>,
2075 // Represents the two kinds of type bindings.
2076 #[derive(Debug, HashStable_Generic)]
2077 pub enum TypeBindingKind<'hir> {
2078 /// E.g., `Foo<Bar: Send>`.
2079 Constraint { bounds: &'hir [GenericBound<'hir>] },
2080 /// E.g., `Foo<Bar = ()>`.
2081 Equality { ty: &'hir Ty<'hir> },
2084 impl TypeBinding<'_> {
2085 pub fn ty(&self) -> &Ty<'_> {
2087 TypeBindingKind::Equality { ref ty } => ty,
2088 _ => panic!("expected equality type binding for parenthesized generic args"),
2094 pub struct Ty<'hir> {
2096 pub kind: TyKind<'hir>,
2100 /// Not represented directly in the AST; referred to by name through a `ty_path`.
2101 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
2102 #[derive(HashStable_Generic)]
2113 /// All of the primitive types
2114 pub const ALL: [Self; 17] = [
2115 // any changes here should also be reflected in `PrimTy::from_name`
2116 Self::Int(IntTy::I8),
2117 Self::Int(IntTy::I16),
2118 Self::Int(IntTy::I32),
2119 Self::Int(IntTy::I64),
2120 Self::Int(IntTy::I128),
2121 Self::Int(IntTy::Isize),
2122 Self::Uint(UintTy::U8),
2123 Self::Uint(UintTy::U16),
2124 Self::Uint(UintTy::U32),
2125 Self::Uint(UintTy::U64),
2126 Self::Uint(UintTy::U128),
2127 Self::Uint(UintTy::Usize),
2128 Self::Float(FloatTy::F32),
2129 Self::Float(FloatTy::F64),
2135 /// Like [`PrimTy::name`], but returns a &str instead of a symbol.
2138 pub fn name_str(self) -> &'static str {
2140 PrimTy::Int(i) => i.name_str(),
2141 PrimTy::Uint(u) => u.name_str(),
2142 PrimTy::Float(f) => f.name_str(),
2143 PrimTy::Str => "str",
2144 PrimTy::Bool => "bool",
2145 PrimTy::Char => "char",
2149 pub fn name(self) -> Symbol {
2151 PrimTy::Int(i) => i.name(),
2152 PrimTy::Uint(u) => u.name(),
2153 PrimTy::Float(f) => f.name(),
2154 PrimTy::Str => sym::str,
2155 PrimTy::Bool => sym::bool,
2156 PrimTy::Char => sym::char,
2160 /// Returns the matching `PrimTy` for a `Symbol` such as "str" or "i32".
2161 /// Returns `None` if no matching type is found.
2162 pub fn from_name(name: Symbol) -> Option<Self> {
2163 let ty = match name {
2164 // any changes here should also be reflected in `PrimTy::ALL`
2165 sym::i8 => Self::Int(IntTy::I8),
2166 sym::i16 => Self::Int(IntTy::I16),
2167 sym::i32 => Self::Int(IntTy::I32),
2168 sym::i64 => Self::Int(IntTy::I64),
2169 sym::i128 => Self::Int(IntTy::I128),
2170 sym::isize => Self::Int(IntTy::Isize),
2171 sym::u8 => Self::Uint(UintTy::U8),
2172 sym::u16 => Self::Uint(UintTy::U16),
2173 sym::u32 => Self::Uint(UintTy::U32),
2174 sym::u64 => Self::Uint(UintTy::U64),
2175 sym::u128 => Self::Uint(UintTy::U128),
2176 sym::usize => Self::Uint(UintTy::Usize),
2177 sym::f32 => Self::Float(FloatTy::F32),
2178 sym::f64 => Self::Float(FloatTy::F64),
2179 sym::bool => Self::Bool,
2180 sym::char => Self::Char,
2181 sym::str => Self::Str,
2188 #[derive(Debug, HashStable_Generic)]
2189 pub struct BareFnTy<'hir> {
2190 pub unsafety: Unsafety,
2192 pub generic_params: &'hir [GenericParam<'hir>],
2193 pub decl: &'hir FnDecl<'hir>,
2194 pub param_names: &'hir [Ident],
2197 #[derive(Debug, HashStable_Generic)]
2198 pub struct OpaqueTy<'hir> {
2199 pub generics: Generics<'hir>,
2200 pub bounds: GenericBounds<'hir>,
2201 pub impl_trait_fn: Option<DefId>,
2202 pub origin: OpaqueTyOrigin,
2205 /// From whence the opaque type came.
2206 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2207 pub enum OpaqueTyOrigin {
2212 /// type aliases: `type Foo = impl Trait;`
2216 /// The various kinds of types recognized by the compiler.
2217 #[derive(Debug, HashStable_Generic)]
2218 pub enum TyKind<'hir> {
2219 /// A variable length slice (i.e., `[T]`).
2220 Slice(&'hir Ty<'hir>),
2221 /// A fixed length array (i.e., `[T; n]`).
2222 Array(&'hir Ty<'hir>, AnonConst),
2223 /// A raw pointer (i.e., `*const T` or `*mut T`).
2225 /// A reference (i.e., `&'a T` or `&'a mut T`).
2226 Rptr(Lifetime, MutTy<'hir>),
2227 /// A bare function (e.g., `fn(usize) -> bool`).
2228 BareFn(&'hir BareFnTy<'hir>),
2229 /// The never type (`!`).
2231 /// A tuple (`(A, B, C, D, ...)`).
2232 Tup(&'hir [Ty<'hir>]),
2233 /// A path to a type definition (`module::module::...::Type`), or an
2234 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2236 /// Type parameters may be stored in each `PathSegment`.
2238 /// An opaque type definition itself. This is currently only used for the
2239 /// `opaque type Foo: Trait` item that `impl Trait` in desugars to.
2241 /// The generic argument list contains the lifetimes (and in the future
2242 /// possibly parameters) that are actually bound on the `impl Trait`.
2243 OpaqueDef(ItemId, &'hir [GenericArg<'hir>]),
2244 /// A trait object type `Bound1 + Bound2 + Bound3`
2245 /// where `Bound` is a trait or a lifetime.
2246 TraitObject(&'hir [PolyTraitRef<'hir>], Lifetime, TraitObjectSyntax),
2249 /// `TyKind::Infer` means the type should be inferred instead of it having been
2250 /// specified. This can appear anywhere in a type.
2252 /// Placeholder for a type that has failed to be defined.
2256 #[derive(Debug, HashStable_Generic)]
2257 pub enum InlineAsmOperand<'hir> {
2259 reg: InlineAsmRegOrRegClass,
2263 reg: InlineAsmRegOrRegClass,
2265 expr: Option<Expr<'hir>>,
2268 reg: InlineAsmRegOrRegClass,
2273 reg: InlineAsmRegOrRegClass,
2275 in_expr: Expr<'hir>,
2276 out_expr: Option<Expr<'hir>>,
2279 anon_const: AnonConst,
2286 impl<'hir> InlineAsmOperand<'hir> {
2287 pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
2289 Self::In { reg, .. }
2290 | Self::Out { reg, .. }
2291 | Self::InOut { reg, .. }
2292 | Self::SplitInOut { reg, .. } => Some(reg),
2293 Self::Const { .. } | Self::Sym { .. } => None,
2297 pub fn is_clobber(&self) -> bool {
2300 InlineAsmOperand::Out { reg: InlineAsmRegOrRegClass::Reg(_), late: _, expr: None }
2305 #[derive(Debug, HashStable_Generic)]
2306 pub struct InlineAsm<'hir> {
2307 pub template: &'hir [InlineAsmTemplatePiece],
2308 pub template_strs: &'hir [(Symbol, Option<Symbol>, Span)],
2309 pub operands: &'hir [(InlineAsmOperand<'hir>, Span)],
2310 pub options: InlineAsmOptions,
2311 pub line_spans: &'hir [Span],
2314 #[derive(Copy, Clone, Encodable, Decodable, Debug, Hash, HashStable_Generic, PartialEq)]
2315 pub struct LlvmInlineAsmOutput {
2316 pub constraint: Symbol,
2318 pub is_indirect: bool,
2322 // NOTE(eddyb) This is used within MIR as well, so unlike the rest of the HIR,
2323 // it needs to be `Clone` and `Decodable` and use plain `Vec<T>` instead of
2324 // arena-allocated slice.
2325 #[derive(Clone, Encodable, Decodable, Debug, Hash, HashStable_Generic, PartialEq)]
2326 pub struct LlvmInlineAsmInner {
2328 pub asm_str_style: StrStyle,
2329 pub outputs: Vec<LlvmInlineAsmOutput>,
2330 pub inputs: Vec<Symbol>,
2331 pub clobbers: Vec<Symbol>,
2333 pub alignstack: bool,
2334 pub dialect: LlvmAsmDialect,
2337 #[derive(Debug, HashStable_Generic)]
2338 pub struct LlvmInlineAsm<'hir> {
2339 pub inner: LlvmInlineAsmInner,
2340 pub outputs_exprs: &'hir [Expr<'hir>],
2341 pub inputs_exprs: &'hir [Expr<'hir>],
2344 /// Represents a parameter in a function header.
2345 #[derive(Debug, HashStable_Generic)]
2346 pub struct Param<'hir> {
2348 pub pat: &'hir Pat<'hir>,
2353 /// Represents the header (not the body) of a function declaration.
2354 #[derive(Debug, HashStable_Generic)]
2355 pub struct FnDecl<'hir> {
2356 /// The types of the function's parameters.
2358 /// Additional argument data is stored in the function's [body](Body::params).
2359 pub inputs: &'hir [Ty<'hir>],
2360 pub output: FnRetTy<'hir>,
2361 pub c_variadic: bool,
2362 /// Does the function have an implicit self?
2363 pub implicit_self: ImplicitSelfKind,
2366 /// Represents what type of implicit self a function has, if any.
2367 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2368 pub enum ImplicitSelfKind {
2369 /// Represents a `fn x(self);`.
2371 /// Represents a `fn x(mut self);`.
2373 /// Represents a `fn x(&self);`.
2375 /// Represents a `fn x(&mut self);`.
2377 /// Represents when a function does not have a self argument or
2378 /// when a function has a `self: X` argument.
2382 impl ImplicitSelfKind {
2383 /// Does this represent an implicit self?
2384 pub fn has_implicit_self(&self) -> bool {
2385 !matches!(*self, ImplicitSelfKind::None)
2389 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable, Debug)]
2390 #[derive(HashStable_Generic)]
2396 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable, HashStable_Generic)]
2397 pub enum Defaultness {
2398 Default { has_value: bool },
2403 pub fn has_value(&self) -> bool {
2405 Defaultness::Default { has_value } => has_value,
2406 Defaultness::Final => true,
2410 pub fn is_final(&self) -> bool {
2411 *self == Defaultness::Final
2414 pub fn is_default(&self) -> bool {
2415 matches!(*self, Defaultness::Default { .. })
2419 #[derive(Debug, HashStable_Generic)]
2420 pub enum FnRetTy<'hir> {
2421 /// Return type is not specified.
2423 /// Functions default to `()` and
2424 /// closures default to inference. Span points to where return
2425 /// type would be inserted.
2426 DefaultReturn(Span),
2427 /// Everything else.
2428 Return(&'hir Ty<'hir>),
2433 pub fn span(&self) -> Span {
2435 Self::DefaultReturn(span) => span,
2436 Self::Return(ref ty) => ty.span,
2441 #[derive(Encodable, Debug)]
2442 pub struct Mod<'hir> {
2443 /// A span from the first token past `{` to the last token until `}`.
2444 /// For `mod foo;`, the inner span ranges from the first token
2445 /// to the last token in the external file.
2447 pub item_ids: &'hir [ItemId],
2450 #[derive(Debug, HashStable_Generic)]
2451 pub struct EnumDef<'hir> {
2452 pub variants: &'hir [Variant<'hir>],
2455 #[derive(Debug, HashStable_Generic)]
2456 pub struct Variant<'hir> {
2457 /// Name of the variant.
2458 #[stable_hasher(project(name))]
2460 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2462 /// Fields and constructor id of the variant.
2463 pub data: VariantData<'hir>,
2464 /// Explicit discriminant (e.g., `Foo = 1`).
2465 pub disr_expr: Option<AnonConst>,
2470 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2472 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2473 /// Also produced for each element of a list `use`, e.g.
2474 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2477 /// Glob import, e.g., `use foo::*`.
2480 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2481 /// an additional `use foo::{}` for performing checks such as
2482 /// unstable feature gating. May be removed in the future.
2486 /// References to traits in impls.
2488 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2489 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2490 /// trait being referred to but just a unique `HirId` that serves as a key
2491 /// within the resolution map.
2492 #[derive(Clone, Debug, HashStable_Generic)]
2493 pub struct TraitRef<'hir> {
2494 pub path: &'hir Path<'hir>,
2495 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2496 #[stable_hasher(ignore)]
2497 pub hir_ref_id: HirId,
2501 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2502 pub fn trait_def_id(&self) -> Option<DefId> {
2503 match self.path.res {
2504 Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
2506 _ => unreachable!(),
2511 #[derive(Clone, Debug, HashStable_Generic)]
2512 pub struct PolyTraitRef<'hir> {
2513 /// The `'a` in `for<'a> Foo<&'a T>`.
2514 pub bound_generic_params: &'hir [GenericParam<'hir>],
2516 /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
2517 pub trait_ref: TraitRef<'hir>,
2522 pub type Visibility<'hir> = Spanned<VisibilityKind<'hir>>;
2524 #[derive(Copy, Clone, Debug)]
2525 pub enum VisibilityKind<'hir> {
2528 Restricted { path: &'hir Path<'hir>, hir_id: HirId },
2532 impl VisibilityKind<'_> {
2533 pub fn is_pub(&self) -> bool {
2534 matches!(*self, VisibilityKind::Public)
2537 pub fn is_pub_restricted(&self) -> bool {
2539 VisibilityKind::Public | VisibilityKind::Inherited => false,
2540 VisibilityKind::Crate(..) | VisibilityKind::Restricted { .. } => true,
2545 #[derive(Debug, HashStable_Generic)]
2546 pub struct FieldDef<'hir> {
2548 #[stable_hasher(project(name))]
2550 pub vis: Visibility<'hir>,
2552 pub ty: &'hir Ty<'hir>,
2556 // Still necessary in couple of places
2557 pub fn is_positional(&self) -> bool {
2558 let first = self.ident.as_str().as_bytes()[0];
2559 (b'0'..=b'9').contains(&first)
2563 /// Fields and constructor IDs of enum variants and structs.
2564 #[derive(Debug, HashStable_Generic)]
2565 pub enum VariantData<'hir> {
2566 /// A struct variant.
2568 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2569 Struct(&'hir [FieldDef<'hir>], /* recovered */ bool),
2570 /// A tuple variant.
2572 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2573 Tuple(&'hir [FieldDef<'hir>], HirId),
2576 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2580 impl VariantData<'hir> {
2581 /// Return the fields of this variant.
2582 pub fn fields(&self) -> &'hir [FieldDef<'hir>] {
2584 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2589 /// Return the `HirId` of this variant's constructor, if it has one.
2590 pub fn ctor_hir_id(&self) -> Option<HirId> {
2592 VariantData::Struct(_, _) => None,
2593 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2598 // The bodies for items are stored "out of line", in a separate
2599 // hashmap in the `Crate`. Here we just record the hir-id of the item
2600 // so it can fetched later.
2601 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug, Hash)]
2603 pub def_id: LocalDefId,
2608 pub fn hir_id(&self) -> HirId {
2609 // Items are always HIR owners.
2610 HirId::make_owner(self.def_id)
2616 /// The name might be a dummy name in case of anonymous items
2618 pub struct Item<'hir> {
2620 pub def_id: LocalDefId,
2621 pub kind: ItemKind<'hir>,
2622 pub vis: Visibility<'hir>,
2628 pub fn hir_id(&self) -> HirId {
2629 // Items are always HIR owners.
2630 HirId::make_owner(self.def_id)
2633 pub fn item_id(&self) -> ItemId {
2634 ItemId { def_id: self.def_id }
2638 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2639 #[derive(Encodable, Decodable, HashStable_Generic)]
2646 pub fn prefix_str(&self) -> &'static str {
2648 Self::Unsafe => "unsafe ",
2654 impl fmt::Display for Unsafety {
2655 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2656 f.write_str(match *self {
2657 Self::Unsafe => "unsafe",
2658 Self::Normal => "normal",
2663 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2664 #[derive(Encodable, Decodable, HashStable_Generic)]
2665 pub enum Constness {
2670 impl fmt::Display for Constness {
2671 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2672 f.write_str(match *self {
2673 Self::Const => "const",
2674 Self::NotConst => "non-const",
2679 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2680 pub struct FnHeader {
2681 pub unsafety: Unsafety,
2682 pub constness: Constness,
2683 pub asyncness: IsAsync,
2688 pub fn is_const(&self) -> bool {
2689 matches!(&self.constness, Constness::Const)
2693 #[derive(Debug, HashStable_Generic)]
2694 pub enum ItemKind<'hir> {
2695 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2697 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2698 ExternCrate(Option<Symbol>),
2700 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2704 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2705 Use(&'hir Path<'hir>, UseKind),
2707 /// A `static` item.
2708 Static(&'hir Ty<'hir>, Mutability, BodyId),
2710 Const(&'hir Ty<'hir>, BodyId),
2711 /// A function declaration.
2712 Fn(FnSig<'hir>, Generics<'hir>, BodyId),
2713 /// A MBE macro definition (`macro_rules!` or `macro`).
2714 Macro(ast::MacroDef),
2717 /// An external module, e.g. `extern { .. }`.
2718 ForeignMod { abi: Abi, items: &'hir [ForeignItemRef] },
2719 /// Module-level inline assembly (from `global_asm!`).
2720 GlobalAsm(&'hir InlineAsm<'hir>),
2721 /// A type alias, e.g., `type Foo = Bar<u8>`.
2722 TyAlias(&'hir Ty<'hir>, Generics<'hir>),
2723 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2724 OpaqueTy(OpaqueTy<'hir>),
2725 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2726 Enum(EnumDef<'hir>, Generics<'hir>),
2727 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2728 Struct(VariantData<'hir>, Generics<'hir>),
2729 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2730 Union(VariantData<'hir>, Generics<'hir>),
2731 /// A trait definition.
2732 Trait(IsAuto, Unsafety, Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
2734 TraitAlias(Generics<'hir>, GenericBounds<'hir>),
2736 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2740 #[derive(Debug, HashStable_Generic)]
2741 pub struct Impl<'hir> {
2742 pub unsafety: Unsafety,
2743 pub polarity: ImplPolarity,
2744 pub defaultness: Defaultness,
2745 // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata
2746 // decoding as `Span`s cannot be decoded when a `Session` is not available.
2747 pub defaultness_span: Option<Span>,
2748 pub constness: Constness,
2749 pub generics: Generics<'hir>,
2751 /// The trait being implemented, if any.
2752 pub of_trait: Option<TraitRef<'hir>>,
2754 pub self_ty: &'hir Ty<'hir>,
2755 pub items: &'hir [ImplItemRef],
2759 pub fn generics(&self) -> Option<&Generics<'_>> {
2761 ItemKind::Fn(_, ref generics, _)
2762 | ItemKind::TyAlias(_, ref generics)
2763 | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
2764 | ItemKind::Enum(_, ref generics)
2765 | ItemKind::Struct(_, ref generics)
2766 | ItemKind::Union(_, ref generics)
2767 | ItemKind::Trait(_, _, ref generics, _, _)
2768 | ItemKind::Impl(Impl { ref generics, .. }) => generics,
2773 pub fn descr(&self) -> &'static str {
2775 ItemKind::ExternCrate(..) => "extern crate",
2776 ItemKind::Use(..) => "`use` import",
2777 ItemKind::Static(..) => "static item",
2778 ItemKind::Const(..) => "constant item",
2779 ItemKind::Fn(..) => "function",
2780 ItemKind::Macro(..) => "macro",
2781 ItemKind::Mod(..) => "module",
2782 ItemKind::ForeignMod { .. } => "extern block",
2783 ItemKind::GlobalAsm(..) => "global asm item",
2784 ItemKind::TyAlias(..) => "type alias",
2785 ItemKind::OpaqueTy(..) => "opaque type",
2786 ItemKind::Enum(..) => "enum",
2787 ItemKind::Struct(..) => "struct",
2788 ItemKind::Union(..) => "union",
2789 ItemKind::Trait(..) => "trait",
2790 ItemKind::TraitAlias(..) => "trait alias",
2791 ItemKind::Impl(..) => "implementation",
2796 /// A reference from an trait to one of its associated items. This
2797 /// contains the item's id, naturally, but also the item's name and
2798 /// some other high-level details (like whether it is an associated
2799 /// type or method, and whether it is public). This allows other
2800 /// passes to find the impl they want without loading the ID (which
2801 /// means fewer edges in the incremental compilation graph).
2802 #[derive(Encodable, Debug, HashStable_Generic)]
2803 pub struct TraitItemRef {
2804 pub id: TraitItemId,
2805 #[stable_hasher(project(name))]
2807 pub kind: AssocItemKind,
2809 pub defaultness: Defaultness,
2812 /// A reference from an impl to one of its associated items. This
2813 /// contains the item's ID, naturally, but also the item's name and
2814 /// some other high-level details (like whether it is an associated
2815 /// type or method, and whether it is public). This allows other
2816 /// passes to find the impl they want without loading the ID (which
2817 /// means fewer edges in the incremental compilation graph).
2818 #[derive(Debug, HashStable_Generic)]
2819 pub struct ImplItemRef {
2821 #[stable_hasher(project(name))]
2823 pub kind: AssocItemKind,
2825 pub defaultness: Defaultness,
2828 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2829 pub enum AssocItemKind {
2831 Fn { has_self: bool },
2835 // The bodies for items are stored "out of line", in a separate
2836 // hashmap in the `Crate`. Here we just record the hir-id of the item
2837 // so it can fetched later.
2838 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
2839 pub struct ForeignItemId {
2840 pub def_id: LocalDefId,
2843 impl ForeignItemId {
2845 pub fn hir_id(&self) -> HirId {
2846 // Items are always HIR owners.
2847 HirId::make_owner(self.def_id)
2851 /// A reference from a foreign block to one of its items. This
2852 /// contains the item's ID, naturally, but also the item's name and
2853 /// some other high-level details (like whether it is an associated
2854 /// type or method, and whether it is public). This allows other
2855 /// passes to find the impl they want without loading the ID (which
2856 /// means fewer edges in the incremental compilation graph).
2857 #[derive(Debug, HashStable_Generic)]
2858 pub struct ForeignItemRef {
2859 pub id: ForeignItemId,
2860 #[stable_hasher(project(name))]
2866 pub struct ForeignItem<'hir> {
2868 pub kind: ForeignItemKind<'hir>,
2869 pub def_id: LocalDefId,
2871 pub vis: Visibility<'hir>,
2874 impl ForeignItem<'_> {
2876 pub fn hir_id(&self) -> HirId {
2877 // Items are always HIR owners.
2878 HirId::make_owner(self.def_id)
2881 pub fn foreign_item_id(&self) -> ForeignItemId {
2882 ForeignItemId { def_id: self.def_id }
2886 /// An item within an `extern` block.
2887 #[derive(Debug, HashStable_Generic)]
2888 pub enum ForeignItemKind<'hir> {
2889 /// A foreign function.
2890 Fn(&'hir FnDecl<'hir>, &'hir [Ident], Generics<'hir>),
2891 /// A foreign static item (`static ext: u8`).
2892 Static(&'hir Ty<'hir>, Mutability),
2897 /// A variable captured by a closure.
2898 #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)]
2900 // First span where it is accessed (there can be multiple).
2904 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2905 // has length > 0 if the trait is found through an chain of imports, starting with the
2906 // import/use statement in the scope where the trait is used.
2907 #[derive(Encodable, Decodable, Clone, Debug)]
2908 pub struct TraitCandidate {
2910 pub import_ids: SmallVec<[LocalDefId; 1]>,
2913 #[derive(Copy, Clone, Debug, HashStable_Generic)]
2914 pub enum OwnerNode<'hir> {
2915 Item(&'hir Item<'hir>),
2916 ForeignItem(&'hir ForeignItem<'hir>),
2917 TraitItem(&'hir TraitItem<'hir>),
2918 ImplItem(&'hir ImplItem<'hir>),
2919 Crate(&'hir Mod<'hir>),
2922 impl<'hir> OwnerNode<'hir> {
2923 pub fn ident(&self) -> Option<Ident> {
2925 OwnerNode::Item(Item { ident, .. })
2926 | OwnerNode::ForeignItem(ForeignItem { ident, .. })
2927 | OwnerNode::ImplItem(ImplItem { ident, .. })
2928 | OwnerNode::TraitItem(TraitItem { ident, .. }) => Some(*ident),
2929 OwnerNode::Crate(..) => None,
2933 pub fn span(&self) -> Span {
2935 OwnerNode::Item(Item { span, .. })
2936 | OwnerNode::ForeignItem(ForeignItem { span, .. })
2937 | OwnerNode::ImplItem(ImplItem { span, .. })
2938 | OwnerNode::TraitItem(TraitItem { span, .. })
2939 | OwnerNode::Crate(Mod { inner: span, .. }) => *span,
2943 pub fn fn_decl(&self) -> Option<&FnDecl<'hir>> {
2945 OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
2946 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
2947 | OwnerNode::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
2948 OwnerNode::ForeignItem(ForeignItem {
2949 kind: ForeignItemKind::Fn(fn_decl, _, _),
2951 }) => Some(fn_decl),
2956 pub fn body_id(&self) -> Option<BodyId> {
2958 OwnerNode::TraitItem(TraitItem {
2959 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
2962 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
2963 | OwnerNode::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
2968 pub fn generics(&self) -> Option<&'hir Generics<'hir>> {
2970 OwnerNode::TraitItem(TraitItem { generics, .. })
2971 | OwnerNode::ImplItem(ImplItem { generics, .. }) => Some(generics),
2972 OwnerNode::Item(item) => item.kind.generics(),
2977 pub fn def_id(self) -> LocalDefId {
2979 OwnerNode::Item(Item { def_id, .. })
2980 | OwnerNode::TraitItem(TraitItem { def_id, .. })
2981 | OwnerNode::ImplItem(ImplItem { def_id, .. })
2982 | OwnerNode::ForeignItem(ForeignItem { def_id, .. }) => *def_id,
2983 OwnerNode::Crate(..) => crate::CRATE_HIR_ID.owner,
2987 pub fn expect_item(self) -> &'hir Item<'hir> {
2989 OwnerNode::Item(n) => n,
2994 pub fn expect_foreign_item(self) -> &'hir ForeignItem<'hir> {
2996 OwnerNode::ForeignItem(n) => n,
3001 pub fn expect_impl_item(self) -> &'hir ImplItem<'hir> {
3003 OwnerNode::ImplItem(n) => n,
3008 pub fn expect_trait_item(self) -> &'hir TraitItem<'hir> {
3010 OwnerNode::TraitItem(n) => n,
3016 impl<'hir> Into<OwnerNode<'hir>> for &'hir Item<'hir> {
3017 fn into(self) -> OwnerNode<'hir> {
3018 OwnerNode::Item(self)
3022 impl<'hir> Into<OwnerNode<'hir>> for &'hir ForeignItem<'hir> {
3023 fn into(self) -> OwnerNode<'hir> {
3024 OwnerNode::ForeignItem(self)
3028 impl<'hir> Into<OwnerNode<'hir>> for &'hir ImplItem<'hir> {
3029 fn into(self) -> OwnerNode<'hir> {
3030 OwnerNode::ImplItem(self)
3034 impl<'hir> Into<OwnerNode<'hir>> for &'hir TraitItem<'hir> {
3035 fn into(self) -> OwnerNode<'hir> {
3036 OwnerNode::TraitItem(self)
3040 impl<'hir> Into<Node<'hir>> for OwnerNode<'hir> {
3041 fn into(self) -> Node<'hir> {
3043 OwnerNode::Item(n) => Node::Item(n),
3044 OwnerNode::ForeignItem(n) => Node::ForeignItem(n),
3045 OwnerNode::ImplItem(n) => Node::ImplItem(n),
3046 OwnerNode::TraitItem(n) => Node::TraitItem(n),
3047 OwnerNode::Crate(n) => Node::Crate(n),
3052 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3053 pub enum Node<'hir> {
3054 Param(&'hir Param<'hir>),
3055 Item(&'hir Item<'hir>),
3056 ForeignItem(&'hir ForeignItem<'hir>),
3057 TraitItem(&'hir TraitItem<'hir>),
3058 ImplItem(&'hir ImplItem<'hir>),
3059 Variant(&'hir Variant<'hir>),
3060 Field(&'hir FieldDef<'hir>),
3061 AnonConst(&'hir AnonConst),
3062 Expr(&'hir Expr<'hir>),
3063 Stmt(&'hir Stmt<'hir>),
3064 PathSegment(&'hir PathSegment<'hir>),
3066 TraitRef(&'hir TraitRef<'hir>),
3067 Binding(&'hir Pat<'hir>),
3068 Pat(&'hir Pat<'hir>),
3069 Arm(&'hir Arm<'hir>),
3070 Block(&'hir Block<'hir>),
3071 Local(&'hir Local<'hir>),
3073 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
3074 /// with synthesized constructors.
3075 Ctor(&'hir VariantData<'hir>),
3077 Lifetime(&'hir Lifetime),
3078 GenericParam(&'hir GenericParam<'hir>),
3079 Visibility(&'hir Visibility<'hir>),
3081 Crate(&'hir Mod<'hir>),
3083 Infer(&'hir InferArg),
3086 impl<'hir> Node<'hir> {
3087 /// Get the identifier of this `Node`, if applicable.
3091 /// Calling `.ident()` on a [`Node::Ctor`] will return `None`
3092 /// because `Ctor`s do not have identifiers themselves.
3093 /// Instead, call `.ident()` on the parent struct/variant, like so:
3095 /// ```ignore (illustrative)
3098 /// .and_then(|ctor_id| tcx.hir().find(tcx.hir().get_parent_node(ctor_id)))
3099 /// .and_then(|parent| parent.ident())
3101 pub fn ident(&self) -> Option<Ident> {
3103 Node::TraitItem(TraitItem { ident, .. })
3104 | Node::ImplItem(ImplItem { ident, .. })
3105 | Node::ForeignItem(ForeignItem { ident, .. })
3106 | Node::Field(FieldDef { ident, .. })
3107 | Node::Variant(Variant { ident, .. })
3108 | Node::Item(Item { ident, .. })
3109 | Node::PathSegment(PathSegment { ident, .. }) => Some(*ident),
3110 Node::Lifetime(lt) => Some(lt.name.ident()),
3111 Node::GenericParam(p) => Some(p.name.ident()),
3113 | Node::AnonConst(..)
3122 | Node::Visibility(..)
3125 | Node::TraitRef(..)
3126 | Node::Infer(..) => None,
3130 pub fn fn_decl(&self) -> Option<&FnDecl<'hir>> {
3132 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3133 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3134 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3135 Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
3142 pub fn body_id(&self) -> Option<BodyId> {
3144 Node::TraitItem(TraitItem {
3145 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3148 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3149 | Node::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3154 pub fn generics(&self) -> Option<&'hir Generics<'hir>> {
3156 Node::TraitItem(TraitItem { generics, .. })
3157 | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
3158 Node::Item(item) => item.kind.generics(),
3163 pub fn hir_id(&self) -> Option<HirId> {
3165 Node::Item(Item { def_id, .. })
3166 | Node::TraitItem(TraitItem { def_id, .. })
3167 | Node::ImplItem(ImplItem { def_id, .. })
3168 | Node::ForeignItem(ForeignItem { def_id, .. }) => Some(HirId::make_owner(*def_id)),
3169 Node::Field(FieldDef { hir_id, .. })
3170 | Node::AnonConst(AnonConst { hir_id, .. })
3171 | Node::Expr(Expr { hir_id, .. })
3172 | Node::Stmt(Stmt { hir_id, .. })
3173 | Node::Ty(Ty { hir_id, .. })
3174 | Node::Binding(Pat { hir_id, .. })
3175 | Node::Pat(Pat { hir_id, .. })
3176 | Node::Arm(Arm { hir_id, .. })
3177 | Node::Block(Block { hir_id, .. })
3178 | Node::Local(Local { hir_id, .. })
3179 | Node::Lifetime(Lifetime { hir_id, .. })
3180 | Node::Param(Param { hir_id, .. })
3181 | Node::Infer(InferArg { hir_id, .. })
3182 | Node::GenericParam(GenericParam { hir_id, .. }) => Some(*hir_id),
3183 Node::TraitRef(TraitRef { hir_ref_id, .. }) => Some(*hir_ref_id),
3184 Node::PathSegment(PathSegment { hir_id, .. }) => *hir_id,
3185 Node::Variant(Variant { id, .. }) => Some(*id),
3186 Node::Ctor(variant) => variant.ctor_hir_id(),
3187 Node::Crate(_) | Node::Visibility(_) => None,
3191 /// Returns `Constness::Const` when this node is a const fn/impl/item.
3192 pub fn constness_for_typeck(&self) -> Constness {
3195 kind: ItemKind::Fn(FnSig { header: FnHeader { constness, .. }, .. }, ..),
3198 | Node::TraitItem(TraitItem {
3199 kind: TraitItemKind::Fn(FnSig { header: FnHeader { constness, .. }, .. }, ..),
3202 | Node::ImplItem(ImplItem {
3203 kind: ImplItemKind::Fn(FnSig { header: FnHeader { constness, .. }, .. }, ..),
3206 | Node::Item(Item { kind: ItemKind::Impl(Impl { constness, .. }), .. }) => *constness,
3208 Node::Item(Item { kind: ItemKind::Const(..), .. })
3209 | Node::TraitItem(TraitItem { kind: TraitItemKind::Const(..), .. })
3210 | Node::ImplItem(ImplItem { kind: ImplItemKind::Const(..), .. }) => Constness::Const,
3212 _ => Constness::NotConst,
3216 pub fn as_owner(self) -> Option<OwnerNode<'hir>> {
3218 Node::Item(i) => Some(OwnerNode::Item(i)),
3219 Node::ForeignItem(i) => Some(OwnerNode::ForeignItem(i)),
3220 Node::TraitItem(i) => Some(OwnerNode::TraitItem(i)),
3221 Node::ImplItem(i) => Some(OwnerNode::ImplItem(i)),
3222 Node::Crate(i) => Some(OwnerNode::Crate(i)),
3228 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3229 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
3231 rustc_data_structures::static_assert_size!(super::Block<'static>, 48);
3232 rustc_data_structures::static_assert_size!(super::Expr<'static>, 64);
3233 rustc_data_structures::static_assert_size!(super::Pat<'static>, 88);
3234 rustc_data_structures::static_assert_size!(super::QPath<'static>, 24);
3235 rustc_data_structures::static_assert_size!(super::Ty<'static>, 72);
3237 rustc_data_structures::static_assert_size!(super::Item<'static>, 184);
3238 rustc_data_structures::static_assert_size!(super::TraitItem<'static>, 128);
3239 rustc_data_structures::static_assert_size!(super::ImplItem<'static>, 152);
3240 rustc_data_structures::static_assert_size!(super::ForeignItem<'static>, 136);