1 use crate::def::{CtorKind, DefKind, Res};
2 use crate::def_id::DefId;
3 crate use crate::hir_id::{HirId, ItemLocalId};
4 use crate::intravisit::FnKind;
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::fingerprint::Fingerprint;
14 use rustc_data_structures::fx::FxHashMap;
15 use rustc_data_structures::sorted_map::SortedMap;
16 use rustc_index::vec::IndexVec;
17 use rustc_macros::HashStable_Generic;
18 use rustc_span::source_map::Spanned;
19 use rustc_span::symbol::{kw, sym, Ident, Symbol};
20 use rustc_span::{def_id::LocalDefId, BytePos};
21 use rustc_span::{MultiSpan, Span, DUMMY_SP};
22 use rustc_target::asm::InlineAsmRegOrRegClass;
23 use rustc_target::spec::abi::Abi;
25 use smallvec::SmallVec;
28 #[derive(Copy, Clone, Encodable, HashStable_Generic)]
33 /// Either "`'a`", referring to a named lifetime definition,
34 /// or "``" (i.e., `kw::Empty`), for elision placeholders.
36 /// HIR lowering inserts these placeholders in type paths that
37 /// refer to type definitions needing lifetime parameters,
38 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
39 pub name: LifetimeName,
42 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
43 #[derive(HashStable_Generic)]
45 /// Some user-given name like `T` or `'x`.
48 /// Synthetic name generated when user elided a lifetime in an impl header.
50 /// E.g., the lifetimes in cases like these:
53 /// impl Foo<'_> for u32
55 /// in that case, we rewrite to
57 /// impl<'f> Foo for &'f u32
58 /// impl<'f> Foo<'f> for u32
60 /// where `'f` is something like `Fresh(0)`. The indices are
61 /// unique per impl, but not necessarily continuous.
64 /// Indicates an illegal name was given and an error has been
65 /// reported (so we should squelch other derived errors). Occurs
66 /// when, e.g., `'_` is used in the wrong place.
71 pub fn ident(&self) -> Ident {
73 ParamName::Plain(ident) => ident,
74 ParamName::Fresh(_) | ParamName::Error => {
75 Ident::with_dummy_span(kw::UnderscoreLifetime)
80 pub fn normalize_to_macros_2_0(&self) -> ParamName {
82 ParamName::Plain(ident) => ParamName::Plain(ident.normalize_to_macros_2_0()),
83 param_name => param_name,
88 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
89 #[derive(HashStable_Generic)]
90 pub enum LifetimeName {
91 /// User-given names or fresh (synthetic) names.
94 /// User wrote nothing (e.g., the lifetime in `&u32`).
96 /// The bool indicates whether the user should have written something.
99 /// Implicit lifetime in a context like `dyn Foo`. This is
100 /// distinguished from implicit lifetimes elsewhere because the
101 /// lifetime that they default to must appear elsewhere within the
102 /// enclosing type. This means that, in an `impl Trait` context, we
103 /// don't have to create a parameter for them. That is, `impl
104 /// Trait<Item = &u32>` expands to an opaque type like `type
105 /// Foo<'a> = impl Trait<Item = &'a u32>`, but `impl Trait<item =
106 /// dyn Bar>` expands to `type Foo = impl Trait<Item = dyn Bar +
107 /// 'static>`. The latter uses `ImplicitObjectLifetimeDefault` so
108 /// that surrounding code knows not to create a lifetime
110 ImplicitObjectLifetimeDefault,
112 /// Indicates an error during lowering (usually `'_` in wrong place)
113 /// that was already reported.
116 /// User wrote specifies `'_`.
119 /// User wrote `'static`.
124 pub fn ident(&self) -> Ident {
126 LifetimeName::ImplicitObjectLifetimeDefault
127 | LifetimeName::Implicit(_)
128 | LifetimeName::Error => Ident::empty(),
129 LifetimeName::Underscore => Ident::with_dummy_span(kw::UnderscoreLifetime),
130 LifetimeName::Static => Ident::with_dummy_span(kw::StaticLifetime),
131 LifetimeName::Param(param_name) => param_name.ident(),
135 pub fn is_elided(&self) -> bool {
137 LifetimeName::ImplicitObjectLifetimeDefault
138 | LifetimeName::Implicit(_)
139 | LifetimeName::Underscore => true,
141 // It might seem surprising that `Fresh(_)` counts as
142 // *not* elided -- but this is because, as far as the code
143 // in the compiler is concerned -- `Fresh(_)` variants act
144 // equivalently to "some fresh name". They correspond to
145 // early-bound regions on an impl, in other words.
146 LifetimeName::Error | LifetimeName::Param(_) | LifetimeName::Static => false,
150 fn is_static(&self) -> bool {
151 self == &LifetimeName::Static
154 pub fn normalize_to_macros_2_0(&self) -> LifetimeName {
156 LifetimeName::Param(param_name) => {
157 LifetimeName::Param(param_name.normalize_to_macros_2_0())
159 lifetime_name => lifetime_name,
164 impl fmt::Display for Lifetime {
165 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166 self.name.ident().fmt(f)
170 impl fmt::Debug for Lifetime {
171 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
172 write!(f, "lifetime({}: {})", self.hir_id, self.name.ident())
177 pub fn is_elided(&self) -> bool {
178 self.name.is_elided()
181 pub fn is_static(&self) -> bool {
182 self.name.is_static()
186 /// A `Path` is essentially Rust's notion of a name; for instance,
187 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
188 /// along with a bunch of supporting information.
189 #[derive(Debug, HashStable_Generic)]
190 pub struct Path<'hir> {
192 /// The resolution for the path.
194 /// The segments in the path: the things separated by `::`.
195 pub segments: &'hir [PathSegment<'hir>],
199 pub fn is_global(&self) -> bool {
200 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
204 /// A segment of a path: an identifier, an optional lifetime, and a set of
206 #[derive(Debug, HashStable_Generic)]
207 pub struct PathSegment<'hir> {
208 /// The identifier portion of this path segment.
209 #[stable_hasher(project(name))]
211 // `id` and `res` are optional. We currently only use these in save-analysis,
212 // any path segments without these will not have save-analysis info and
213 // therefore will not have 'jump to def' in IDEs, but otherwise will not be
214 // affected. (In general, we don't bother to get the defs for synthesized
215 // segments, only for segments which have come from the AST).
216 pub hir_id: Option<HirId>,
217 pub res: Option<Res>,
219 /// Type/lifetime parameters attached to this path. They come in
220 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
221 /// this is more than just simple syntactic sugar; the use of
222 /// parens affects the region binding rules, so we preserve the
224 pub args: Option<&'hir GenericArgs<'hir>>,
226 /// Whether to infer remaining type parameters, if any.
227 /// This only applies to expression and pattern paths, and
228 /// out of those only the segments with no type parameters
229 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
230 pub infer_args: bool,
233 impl<'hir> PathSegment<'hir> {
234 /// Converts an identifier to the corresponding segment.
235 pub fn from_ident(ident: Ident) -> PathSegment<'hir> {
236 PathSegment { ident, hir_id: None, res: None, infer_args: true, args: None }
239 pub fn invalid() -> Self {
240 Self::from_ident(Ident::empty())
243 pub fn args(&self) -> &GenericArgs<'hir> {
244 if let Some(ref args) = self.args {
247 const DUMMY: &GenericArgs<'_> = &GenericArgs::none();
253 #[derive(Encodable, Debug, HashStable_Generic)]
254 pub struct ConstArg {
255 pub value: AnonConst,
259 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
267 pub fn is_type(self) -> bool {
268 matches!(self, InferKind::Type)
272 #[derive(Encodable, Debug, HashStable_Generic)]
273 pub struct InferArg {
280 pub fn to_ty(&self) -> Ty<'_> {
281 Ty { kind: TyKind::Infer, span: self.span, hir_id: self.hir_id }
285 #[derive(Debug, HashStable_Generic)]
286 pub enum GenericArg<'hir> {
293 impl GenericArg<'_> {
294 pub fn span(&self) -> Span {
296 GenericArg::Lifetime(l) => l.span,
297 GenericArg::Type(t) => t.span,
298 GenericArg::Const(c) => c.span,
299 GenericArg::Infer(i) => i.span,
303 pub fn id(&self) -> HirId {
305 GenericArg::Lifetime(l) => l.hir_id,
306 GenericArg::Type(t) => t.hir_id,
307 GenericArg::Const(c) => c.value.hir_id,
308 GenericArg::Infer(i) => i.hir_id,
312 pub fn is_const(&self) -> bool {
313 matches!(self, GenericArg::Const(_))
316 pub fn is_synthetic(&self) -> bool {
317 matches!(self, GenericArg::Lifetime(lifetime) if lifetime.name.ident() == Ident::empty())
320 pub fn descr(&self) -> &'static str {
322 GenericArg::Lifetime(_) => "lifetime",
323 GenericArg::Type(_) => "type",
324 GenericArg::Const(_) => "constant",
325 GenericArg::Infer(_) => "inferred",
329 pub fn to_ord(&self, feats: &rustc_feature::Features) -> ast::ParamKindOrd {
331 GenericArg::Lifetime(_) => ast::ParamKindOrd::Lifetime,
332 GenericArg::Type(_) => ast::ParamKindOrd::Type,
333 GenericArg::Const(_) => {
334 ast::ParamKindOrd::Const { unordered: feats.unordered_const_ty_params() }
336 GenericArg::Infer(_) => ast::ParamKindOrd::Infer,
341 #[derive(Debug, HashStable_Generic)]
342 pub struct GenericArgs<'hir> {
343 /// The generic arguments for this path segment.
344 pub args: &'hir [GenericArg<'hir>],
345 /// Bindings (equality constraints) on associated types, if present.
346 /// E.g., `Foo<A = Bar>`.
347 pub bindings: &'hir [TypeBinding<'hir>],
348 /// Were arguments written in parenthesized form `Fn(T) -> U`?
349 /// This is required mostly for pretty-printing and diagnostics,
350 /// but also for changing lifetime elision rules to be "function-like".
351 pub parenthesized: bool,
352 /// The span encompassing arguments and the surrounding brackets `<>` or `()`
353 /// Foo<A, B, AssocTy = D> Fn(T, U, V) -> W
354 /// ^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^
355 /// Note that this may be:
356 /// - empty, if there are no generic brackets (but there may be hidden lifetimes)
357 /// - dummy, if this was generated while desugaring
361 impl GenericArgs<'_> {
362 pub const fn none() -> Self {
363 Self { args: &[], bindings: &[], parenthesized: false, span_ext: DUMMY_SP }
366 pub fn inputs(&self) -> &[Ty<'_>] {
367 if self.parenthesized {
368 for arg in self.args {
370 GenericArg::Lifetime(_) => {}
371 GenericArg::Type(ref ty) => {
372 if let TyKind::Tup(ref tys) = ty.kind {
377 GenericArg::Const(_) => {}
378 GenericArg::Infer(_) => {}
382 panic!("GenericArgs::inputs: not a `Fn(T) -> U`");
386 pub fn has_type_params(&self) -> bool {
387 self.args.iter().any(|arg| matches!(arg, GenericArg::Type(_)))
390 pub fn has_err(&self) -> bool {
391 self.args.iter().any(|arg| match arg {
392 GenericArg::Type(ty) => matches!(ty.kind, TyKind::Err),
394 }) || self.bindings.iter().any(|arg| match arg.kind {
395 TypeBindingKind::Equality { ty } => matches!(ty.kind, TyKind::Err),
401 pub fn num_type_params(&self) -> usize {
402 self.args.iter().filter(|arg| matches!(arg, GenericArg::Type(_))).count()
406 pub fn num_lifetime_params(&self) -> usize {
407 self.args.iter().filter(|arg| matches!(arg, GenericArg::Lifetime(_))).count()
411 pub fn has_lifetime_params(&self) -> bool {
412 self.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)))
416 pub fn num_generic_params(&self) -> usize {
417 self.args.iter().filter(|arg| !matches!(arg, GenericArg::Lifetime(_))).count()
420 /// The span encompassing the text inside the surrounding brackets.
421 /// It will also include bindings if they aren't in the form `-> Ret`
422 /// Returns `None` if the span is empty (e.g. no brackets) or dummy
423 pub fn span(&self) -> Option<Span> {
424 let span_ext = self.span_ext()?;
425 Some(span_ext.with_lo(span_ext.lo() + BytePos(1)).with_hi(span_ext.hi() - BytePos(1)))
428 /// Returns span encompassing arguments and their surrounding `<>` or `()`
429 pub fn span_ext(&self) -> Option<Span> {
430 Some(self.span_ext).filter(|span| !span.is_empty())
433 pub fn is_empty(&self) -> bool {
438 /// A modifier on a bound, currently this is only used for `?Sized`, where the
439 /// modifier is `Maybe`. Negative bounds should also be handled here.
440 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
441 #[derive(HashStable_Generic)]
442 pub enum TraitBoundModifier {
448 /// The AST represents all type param bounds as types.
449 /// `typeck::collect::compute_bounds` matches these against
450 /// the "special" built-in traits (see `middle::lang_items`) and
451 /// detects `Copy`, `Send` and `Sync`.
452 #[derive(Clone, Debug, HashStable_Generic)]
453 pub enum GenericBound<'hir> {
454 Trait(PolyTraitRef<'hir>, TraitBoundModifier),
455 // FIXME(davidtwco): Introduce `PolyTraitRef::LangItem`
456 LangItemTrait(LangItem, Span, HirId, &'hir GenericArgs<'hir>),
460 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
461 rustc_data_structures::static_assert_size!(GenericBound<'_>, 48);
463 impl GenericBound<'_> {
464 pub fn trait_ref(&self) -> Option<&TraitRef<'_>> {
466 GenericBound::Trait(data, _) => Some(&data.trait_ref),
471 pub fn span(&self) -> Span {
473 GenericBound::Trait(t, ..) => t.span,
474 GenericBound::LangItemTrait(_, span, ..) => *span,
475 GenericBound::Outlives(l) => l.span,
480 pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
482 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
483 pub enum LifetimeParamKind {
484 // Indicates that the lifetime definition was explicitly declared (e.g., in
485 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
488 // Indicates that the lifetime definition was synthetically added
489 // as a result of an in-band lifetime usage (e.g., in
490 // `fn foo(x: &'a u8) -> &'a u8 { x }`).
493 // Indication that the lifetime was elided (e.g., in both cases in
494 // `fn foo(x: &u8) -> &'_ u8 { x }`).
497 // Indication that the lifetime name was somehow in error.
501 #[derive(Debug, HashStable_Generic)]
502 pub enum GenericParamKind<'hir> {
503 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
505 kind: LifetimeParamKind,
508 default: Option<&'hir Ty<'hir>>,
513 /// Optional default value for the const generic param
514 default: Option<AnonConst>,
518 #[derive(Debug, HashStable_Generic)]
519 pub struct GenericParam<'hir> {
522 pub bounds: GenericBounds<'hir>,
524 pub pure_wrt_drop: bool,
525 pub kind: GenericParamKind<'hir>,
528 impl GenericParam<'hir> {
529 pub fn bounds_span(&self) -> Option<Span> {
530 self.bounds.iter().fold(None, |span, bound| {
531 let span = span.map(|s| s.to(bound.span())).unwrap_or_else(|| bound.span());
539 pub struct GenericParamCount {
540 pub lifetimes: usize,
546 /// Represents lifetimes and type parameters attached to a declaration
547 /// of a function, enum, trait, etc.
548 #[derive(Debug, HashStable_Generic)]
549 pub struct Generics<'hir> {
550 pub params: &'hir [GenericParam<'hir>],
551 pub where_clause: WhereClause<'hir>,
555 impl Generics<'hir> {
556 pub const fn empty() -> Generics<'hir> {
559 where_clause: WhereClause { predicates: &[], span: DUMMY_SP },
564 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'_>> {
565 for param in self.params {
566 if name == param.name.ident().name {
573 pub fn spans(&self) -> MultiSpan {
574 if self.params.is_empty() {
577 self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
582 /// A where-clause in a definition.
583 #[derive(Debug, HashStable_Generic)]
584 pub struct WhereClause<'hir> {
585 pub predicates: &'hir [WherePredicate<'hir>],
586 // Only valid if predicates aren't empty.
590 impl WhereClause<'_> {
591 pub fn span(&self) -> Option<Span> {
592 if self.predicates.is_empty() { None } else { Some(self.span) }
595 /// The `WhereClause` under normal circumstances points at either the predicates or the empty
596 /// space where the `where` clause should be. Only of use for diagnostic suggestions.
597 pub fn span_for_predicates_or_empty_place(&self) -> Span {
601 /// `Span` where further predicates would be suggested, accounting for trailing commas, like
602 /// in `fn foo<T>(t: T) where T: Foo,` so we don't suggest two trailing commas.
603 pub fn tail_span_for_suggestion(&self) -> Span {
604 let end = self.span_for_predicates_or_empty_place().shrink_to_hi();
605 self.predicates.last().map_or(end, |p| p.span()).shrink_to_hi().to(end)
609 /// A single predicate in a where-clause.
610 #[derive(Debug, HashStable_Generic)]
611 pub enum WherePredicate<'hir> {
612 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
613 BoundPredicate(WhereBoundPredicate<'hir>),
614 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
615 RegionPredicate(WhereRegionPredicate<'hir>),
616 /// An equality predicate (unsupported).
617 EqPredicate(WhereEqPredicate<'hir>),
620 impl WherePredicate<'_> {
621 pub fn span(&self) -> Span {
623 WherePredicate::BoundPredicate(p) => p.span,
624 WherePredicate::RegionPredicate(p) => p.span,
625 WherePredicate::EqPredicate(p) => p.span,
630 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
631 #[derive(Debug, HashStable_Generic)]
632 pub struct WhereBoundPredicate<'hir> {
634 /// Any generics from a `for` binding.
635 pub bound_generic_params: &'hir [GenericParam<'hir>],
636 /// The type being bounded.
637 pub bounded_ty: &'hir Ty<'hir>,
638 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
639 pub bounds: GenericBounds<'hir>,
642 impl WhereBoundPredicate<'hir> {
643 /// Returns `true` if `param_def_id` matches the `bounded_ty` of this predicate.
644 pub fn is_param_bound(&self, param_def_id: DefId) -> bool {
645 let path = match self.bounded_ty.kind {
646 TyKind::Path(QPath::Resolved(None, path)) => path,
650 Res::Def(DefKind::TyParam, def_id) | Res::SelfTy(Some(def_id), None) => {
651 def_id == param_def_id
658 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
659 #[derive(Debug, HashStable_Generic)]
660 pub struct WhereRegionPredicate<'hir> {
662 pub lifetime: Lifetime,
663 pub bounds: GenericBounds<'hir>,
666 /// An equality predicate (e.g., `T = int`); currently unsupported.
667 #[derive(Debug, HashStable_Generic)]
668 pub struct WhereEqPredicate<'hir> {
671 pub lhs_ty: &'hir Ty<'hir>,
672 pub rhs_ty: &'hir Ty<'hir>,
675 /// HIR node coupled with its parent's id in the same HIR owner.
677 /// The parent is trash when the node is a HIR owner.
678 #[derive(Clone, Debug)]
679 pub struct ParentedNode<'tcx> {
680 pub parent: ItemLocalId,
681 pub node: Node<'tcx>,
684 /// Attributes owned by a HIR owner.
686 pub struct AttributeMap<'tcx> {
687 pub map: SortedMap<ItemLocalId, &'tcx [Attribute]>,
688 pub hash: Fingerprint,
691 impl<'tcx> AttributeMap<'tcx> {
692 pub const EMPTY: &'static AttributeMap<'static> =
693 &AttributeMap { map: SortedMap::new(), hash: Fingerprint::ZERO };
696 pub fn get(&self, id: ItemLocalId) -> &'tcx [Attribute] {
697 self.map.get(&id).copied().unwrap_or(&[])
701 /// Map of all HIR nodes inside the current owner.
702 /// These nodes are mapped by `ItemLocalId` alongside the index of their parent node.
703 /// The HIR tree, including bodies, is pre-hashed.
705 pub struct OwnerNodes<'tcx> {
706 /// Pre-computed hash of the full HIR.
707 pub hash_including_bodies: Fingerprint,
708 /// Pre-computed hash of the item signature, sithout recursing into the body.
709 pub hash_without_bodies: Fingerprint,
710 /// Full HIR for the current owner.
711 // The zeroth node's parent should never be accessed: the owner's parent is computed by the
712 // hir_owner_parent query. It is set to `ItemLocalId::INVALID` to force an ICE if accidentally
714 pub nodes: IndexVec<ItemLocalId, Option<ParentedNode<'tcx>>>,
715 /// Content of local bodies.
716 pub bodies: SortedMap<ItemLocalId, &'tcx Body<'tcx>>,
719 /// Full information resulting from lowering an AST node.
720 #[derive(Debug, HashStable_Generic)]
721 pub struct OwnerInfo<'hir> {
722 /// Contents of the HIR.
723 pub nodes: OwnerNodes<'hir>,
724 /// Map from each nested owner to its parent's local id.
725 pub parenting: FxHashMap<LocalDefId, ItemLocalId>,
726 /// Collected attributes of the HIR nodes.
727 pub attrs: AttributeMap<'hir>,
728 /// Map indicating what traits are in scope for places where this
729 /// is relevant; generated by resolve.
730 pub trait_map: FxHashMap<ItemLocalId, Box<[TraitCandidate]>>,
733 impl<'tcx> OwnerInfo<'tcx> {
735 pub fn node(&self) -> OwnerNode<'tcx> {
736 use rustc_index::vec::Idx;
737 let node = self.nodes.nodes[ItemLocalId::new(0)].as_ref().unwrap().node;
738 let node = node.as_owner().unwrap(); // Indexing must ensure it is an OwnerNode.
743 /// The top-level data structure that stores the entire contents of
744 /// the crate currently being compiled.
746 /// For more details, see the [rustc dev guide].
748 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
750 pub struct Crate<'hir> {
751 pub owners: IndexVec<LocalDefId, Option<OwnerInfo<'hir>>>,
752 pub hir_hash: Fingerprint,
755 /// A block of statements `{ .. }`, which may have a label (in this case the
756 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
757 /// the `rules` being anything but `DefaultBlock`.
758 #[derive(Debug, HashStable_Generic)]
759 pub struct Block<'hir> {
760 /// Statements in a block.
761 pub stmts: &'hir [Stmt<'hir>],
762 /// An expression at the end of the block
763 /// without a semicolon, if any.
764 pub expr: Option<&'hir Expr<'hir>>,
765 #[stable_hasher(ignore)]
767 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
768 pub rules: BlockCheckMode,
770 /// If true, then there may exist `break 'a` values that aim to
771 /// break out of this block early.
772 /// Used by `'label: {}` blocks and by `try {}` blocks.
773 pub targeted_by_break: bool,
776 #[derive(Debug, HashStable_Generic)]
777 pub struct Pat<'hir> {
778 #[stable_hasher(ignore)]
780 pub kind: PatKind<'hir>,
782 // Whether to use default binding modes.
783 // At present, this is false only for destructuring assignment.
784 pub default_binding_modes: bool,
787 impl<'hir> Pat<'hir> {
788 // FIXME(#19596) this is a workaround, but there should be a better way
789 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) -> bool {
796 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
797 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
798 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
799 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
800 Slice(before, slice, after) => {
801 before.iter().chain(slice).chain(after.iter()).all(|p| p.walk_short_(it))
806 /// Walk the pattern in left-to-right order,
807 /// short circuiting (with `.all(..)`) if `false` is returned.
809 /// Note that when visiting e.g. `Tuple(ps)`,
810 /// if visiting `ps[0]` returns `false`,
811 /// then `ps[1]` will not be visited.
812 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) -> bool {
813 self.walk_short_(&mut it)
816 // FIXME(#19596) this is a workaround, but there should be a better way
817 fn walk_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) {
824 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
825 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
826 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
827 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
828 Slice(before, slice, after) => {
829 before.iter().chain(slice).chain(after.iter()).for_each(|p| p.walk_(it))
834 /// Walk the pattern in left-to-right order.
836 /// If `it(pat)` returns `false`, the children are not visited.
837 pub fn walk(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) {
841 /// Walk the pattern in left-to-right order.
843 /// If you always want to recurse, prefer this method over `walk`.
844 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
852 /// A single field in a struct pattern.
854 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
855 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
856 /// except `is_shorthand` is true.
857 #[derive(Debug, HashStable_Generic)]
858 pub struct PatField<'hir> {
859 #[stable_hasher(ignore)]
861 /// The identifier for the field.
862 #[stable_hasher(project(name))]
864 /// The pattern the field is destructured to.
865 pub pat: &'hir Pat<'hir>,
866 pub is_shorthand: bool,
870 /// Explicit binding annotations given in the HIR for a binding. Note
871 /// that this is not the final binding *mode* that we infer after type
873 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
874 pub enum BindingAnnotation {
875 /// No binding annotation given: this means that the final binding mode
876 /// will depend on whether we have skipped through a `&` reference
877 /// when matching. For example, the `x` in `Some(x)` will have binding
878 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
879 /// ultimately be inferred to be by-reference.
881 /// Note that implicit reference skipping is not implemented yet (#42640).
884 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
887 /// Annotated as `ref`, like `ref x`
890 /// Annotated as `ref mut x`.
894 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
900 impl fmt::Display for RangeEnd {
901 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
902 f.write_str(match self {
903 RangeEnd::Included => "..=",
904 RangeEnd::Excluded => "..",
909 #[derive(Debug, HashStable_Generic)]
910 pub enum PatKind<'hir> {
911 /// Represents a wildcard pattern (i.e., `_`).
914 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
915 /// The `HirId` is the canonical ID for the variable being bound,
916 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
917 /// which is the pattern ID of the first `x`.
918 Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
920 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
921 /// The `bool` is `true` in the presence of a `..`.
922 Struct(QPath<'hir>, &'hir [PatField<'hir>], bool),
924 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
925 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
926 /// `0 <= position <= subpats.len()`
927 TupleStruct(QPath<'hir>, &'hir [Pat<'hir>], Option<usize>),
929 /// An or-pattern `A | B | C`.
930 /// Invariant: `pats.len() >= 2`.
931 Or(&'hir [Pat<'hir>]),
933 /// A path pattern for a unit struct/variant or a (maybe-associated) constant.
936 /// A tuple pattern (e.g., `(a, b)`).
937 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
938 /// `0 <= position <= subpats.len()`
939 Tuple(&'hir [Pat<'hir>], Option<usize>),
942 Box(&'hir Pat<'hir>),
944 /// A reference pattern (e.g., `&mut (a, b)`).
945 Ref(&'hir Pat<'hir>, Mutability),
948 Lit(&'hir Expr<'hir>),
950 /// A range pattern (e.g., `1..=2` or `1..2`).
951 Range(Option<&'hir Expr<'hir>>, Option<&'hir Expr<'hir>>, RangeEnd),
953 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
955 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
956 /// If `slice` exists, then `after` can be non-empty.
958 /// The representation for e.g., `[a, b, .., c, d]` is:
960 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
962 Slice(&'hir [Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [Pat<'hir>]),
965 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
967 /// The `+` operator (addition).
969 /// The `-` operator (subtraction).
971 /// The `*` operator (multiplication).
973 /// The `/` operator (division).
975 /// The `%` operator (modulus).
977 /// The `&&` operator (logical and).
979 /// The `||` operator (logical or).
981 /// The `^` operator (bitwise xor).
983 /// The `&` operator (bitwise and).
985 /// The `|` operator (bitwise or).
987 /// The `<<` operator (shift left).
989 /// The `>>` operator (shift right).
991 /// The `==` operator (equality).
993 /// The `<` operator (less than).
995 /// The `<=` operator (less than or equal to).
997 /// The `!=` operator (not equal to).
999 /// The `>=` operator (greater than or equal to).
1001 /// The `>` operator (greater than).
1006 pub fn as_str(self) -> &'static str {
1008 BinOpKind::Add => "+",
1009 BinOpKind::Sub => "-",
1010 BinOpKind::Mul => "*",
1011 BinOpKind::Div => "/",
1012 BinOpKind::Rem => "%",
1013 BinOpKind::And => "&&",
1014 BinOpKind::Or => "||",
1015 BinOpKind::BitXor => "^",
1016 BinOpKind::BitAnd => "&",
1017 BinOpKind::BitOr => "|",
1018 BinOpKind::Shl => "<<",
1019 BinOpKind::Shr => ">>",
1020 BinOpKind::Eq => "==",
1021 BinOpKind::Lt => "<",
1022 BinOpKind::Le => "<=",
1023 BinOpKind::Ne => "!=",
1024 BinOpKind::Ge => ">=",
1025 BinOpKind::Gt => ">",
1029 pub fn is_lazy(self) -> bool {
1030 matches!(self, BinOpKind::And | BinOpKind::Or)
1033 pub fn is_shift(self) -> bool {
1034 matches!(self, BinOpKind::Shl | BinOpKind::Shr)
1037 pub fn is_comparison(self) -> bool {
1044 | BinOpKind::Ge => true,
1056 | BinOpKind::Shr => false,
1060 /// Returns `true` if the binary operator takes its arguments by value.
1061 pub fn is_by_value(self) -> bool {
1062 !self.is_comparison()
1066 impl Into<ast::BinOpKind> for BinOpKind {
1067 fn into(self) -> ast::BinOpKind {
1069 BinOpKind::Add => ast::BinOpKind::Add,
1070 BinOpKind::Sub => ast::BinOpKind::Sub,
1071 BinOpKind::Mul => ast::BinOpKind::Mul,
1072 BinOpKind::Div => ast::BinOpKind::Div,
1073 BinOpKind::Rem => ast::BinOpKind::Rem,
1074 BinOpKind::And => ast::BinOpKind::And,
1075 BinOpKind::Or => ast::BinOpKind::Or,
1076 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1077 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1078 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1079 BinOpKind::Shl => ast::BinOpKind::Shl,
1080 BinOpKind::Shr => ast::BinOpKind::Shr,
1081 BinOpKind::Eq => ast::BinOpKind::Eq,
1082 BinOpKind::Lt => ast::BinOpKind::Lt,
1083 BinOpKind::Le => ast::BinOpKind::Le,
1084 BinOpKind::Ne => ast::BinOpKind::Ne,
1085 BinOpKind::Ge => ast::BinOpKind::Ge,
1086 BinOpKind::Gt => ast::BinOpKind::Gt,
1091 pub type BinOp = Spanned<BinOpKind>;
1093 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1095 /// The `*` operator (deferencing).
1097 /// The `!` operator (logical negation).
1099 /// The `-` operator (negation).
1104 pub fn as_str(self) -> &'static str {
1112 /// Returns `true` if the unary operator takes its argument by value.
1113 pub fn is_by_value(self) -> bool {
1114 matches!(self, Self::Neg | Self::Not)
1119 #[derive(Debug, HashStable_Generic)]
1120 pub struct Stmt<'hir> {
1122 pub kind: StmtKind<'hir>,
1126 /// The contents of a statement.
1127 #[derive(Debug, HashStable_Generic)]
1128 pub enum StmtKind<'hir> {
1129 /// A local (`let`) binding.
1130 Local(&'hir Local<'hir>),
1132 /// An item binding.
1135 /// An expression without a trailing semi-colon (must have unit type).
1136 Expr(&'hir Expr<'hir>),
1138 /// An expression with a trailing semi-colon (may have any type).
1139 Semi(&'hir Expr<'hir>),
1142 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1143 #[derive(Debug, HashStable_Generic)]
1144 pub struct Local<'hir> {
1145 pub pat: &'hir Pat<'hir>,
1146 /// Type annotation, if any (otherwise the type will be inferred).
1147 pub ty: Option<&'hir Ty<'hir>>,
1148 /// Initializer expression to set the value, if any.
1149 pub init: Option<&'hir Expr<'hir>>,
1152 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1153 /// desugaring. Otherwise will be `Normal`.
1154 pub source: LocalSource,
1157 /// Represents a single arm of a `match` expression, e.g.
1158 /// `<pat> (if <guard>) => <body>`.
1159 #[derive(Debug, HashStable_Generic)]
1160 pub struct Arm<'hir> {
1161 #[stable_hasher(ignore)]
1164 /// If this pattern and the optional guard matches, then `body` is evaluated.
1165 pub pat: &'hir Pat<'hir>,
1166 /// Optional guard clause.
1167 pub guard: Option<Guard<'hir>>,
1168 /// The expression the arm evaluates to if this arm matches.
1169 pub body: &'hir Expr<'hir>,
1172 #[derive(Debug, HashStable_Generic)]
1173 pub enum Guard<'hir> {
1174 If(&'hir Expr<'hir>),
1175 // FIXME use ExprKind::Let for this.
1176 IfLet(&'hir Pat<'hir>, &'hir Expr<'hir>),
1179 #[derive(Debug, HashStable_Generic)]
1180 pub struct ExprField<'hir> {
1181 #[stable_hasher(ignore)]
1184 pub expr: &'hir Expr<'hir>,
1186 pub is_shorthand: bool,
1189 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1190 pub enum BlockCheckMode {
1192 UnsafeBlock(UnsafeSource),
1195 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1196 pub enum UnsafeSource {
1201 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Hash, Debug)]
1206 /// The body of a function, closure, or constant value. In the case of
1207 /// a function, the body contains not only the function body itself
1208 /// (which is an expression), but also the argument patterns, since
1209 /// those are something that the caller doesn't really care about.
1214 /// fn foo((x, y): (u32, u32)) -> u32 {
1219 /// Here, the `Body` associated with `foo()` would contain:
1221 /// - an `params` array containing the `(x, y)` pattern
1222 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1223 /// - `generator_kind` would be `None`
1225 /// All bodies have an **owner**, which can be accessed via the HIR
1226 /// map using `body_owner_def_id()`.
1228 pub struct Body<'hir> {
1229 pub params: &'hir [Param<'hir>],
1230 pub value: Expr<'hir>,
1231 pub generator_kind: Option<GeneratorKind>,
1235 pub fn id(&self) -> BodyId {
1236 BodyId { hir_id: self.value.hir_id }
1239 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1244 /// The type of source expression that caused this generator to be created.
1257 pub enum GeneratorKind {
1258 /// An explicit `async` block or the body of an async function.
1259 Async(AsyncGeneratorKind),
1261 /// A generator literal created via a `yield` inside a closure.
1265 impl fmt::Display for GeneratorKind {
1266 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1268 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1269 GeneratorKind::Gen => f.write_str("generator"),
1274 impl GeneratorKind {
1275 pub fn descr(&self) -> &'static str {
1277 GeneratorKind::Async(ask) => ask.descr(),
1278 GeneratorKind::Gen => "generator",
1283 /// In the case of a generator created as part of an async construct,
1284 /// which kind of async construct caused it to be created?
1286 /// This helps error messages but is also used to drive coercions in
1287 /// type-checking (see #60424).
1300 pub enum AsyncGeneratorKind {
1301 /// An explicit `async` block written by the user.
1304 /// An explicit `async` block written by the user.
1307 /// The `async` block generated as the body of an async function.
1311 impl fmt::Display for AsyncGeneratorKind {
1312 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1313 f.write_str(match self {
1314 AsyncGeneratorKind::Block => "`async` block",
1315 AsyncGeneratorKind::Closure => "`async` closure body",
1316 AsyncGeneratorKind::Fn => "`async fn` body",
1321 impl AsyncGeneratorKind {
1322 pub fn descr(&self) -> &'static str {
1324 AsyncGeneratorKind::Block => "`async` block",
1325 AsyncGeneratorKind::Closure => "`async` closure body",
1326 AsyncGeneratorKind::Fn => "`async fn` body",
1331 #[derive(Copy, Clone, Debug)]
1332 pub enum BodyOwnerKind {
1333 /// Functions and methods.
1339 /// Constants and associated constants.
1342 /// Initializer of a `static` item.
1346 impl BodyOwnerKind {
1347 pub fn is_fn_or_closure(self) -> bool {
1349 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1350 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1355 /// The kind of an item that requires const-checking.
1356 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1357 pub enum ConstContext {
1361 /// A `static` or `static mut`.
1364 /// A `const`, associated `const`, or other const context.
1366 /// Other contexts include:
1367 /// - Array length expressions
1368 /// - Enum discriminants
1369 /// - Const generics
1371 /// For the most part, other contexts are treated just like a regular `const`, so they are
1372 /// lumped into the same category.
1377 /// A description of this const context that can appear between backticks in an error message.
1379 /// E.g. `const` or `static mut`.
1380 pub fn keyword_name(self) -> &'static str {
1382 Self::Const => "const",
1383 Self::Static(Mutability::Not) => "static",
1384 Self::Static(Mutability::Mut) => "static mut",
1385 Self::ConstFn => "const fn",
1390 /// A colloquial, trivially pluralizable description of this const context for use in error
1392 impl fmt::Display for ConstContext {
1393 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1395 Self::Const => write!(f, "constant"),
1396 Self::Static(_) => write!(f, "static"),
1397 Self::ConstFn => write!(f, "constant function"),
1403 pub type Lit = Spanned<LitKind>;
1405 /// A constant (expression) that's not an item or associated item,
1406 /// but needs its own `DefId` for type-checking, const-eval, etc.
1407 /// These are usually found nested inside types (e.g., array lengths)
1408 /// or expressions (e.g., repeat counts), and also used to define
1409 /// explicit discriminant values for enum variants.
1411 /// You can check if this anon const is a default in a const param
1412 /// `const N: usize = { ... }` with `tcx.hir().opt_const_param_default_param_hir_id(..)`
1413 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1414 pub struct AnonConst {
1421 pub struct Expr<'hir> {
1423 pub kind: ExprKind<'hir>,
1428 pub fn precedence(&self) -> ExprPrecedence {
1430 ExprKind::Box(_) => ExprPrecedence::Box,
1431 ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1432 ExprKind::Array(_) => ExprPrecedence::Array,
1433 ExprKind::Call(..) => ExprPrecedence::Call,
1434 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1435 ExprKind::Tup(_) => ExprPrecedence::Tup,
1436 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1437 ExprKind::Unary(..) => ExprPrecedence::Unary,
1438 ExprKind::Lit(_) => ExprPrecedence::Lit,
1439 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1440 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1441 ExprKind::If(..) => ExprPrecedence::If,
1442 ExprKind::Let(..) => ExprPrecedence::Let,
1443 ExprKind::Loop(..) => ExprPrecedence::Loop,
1444 ExprKind::Match(..) => ExprPrecedence::Match,
1445 ExprKind::Closure(..) => ExprPrecedence::Closure,
1446 ExprKind::Block(..) => ExprPrecedence::Block,
1447 ExprKind::Assign(..) => ExprPrecedence::Assign,
1448 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1449 ExprKind::Field(..) => ExprPrecedence::Field,
1450 ExprKind::Index(..) => ExprPrecedence::Index,
1451 ExprKind::Path(..) => ExprPrecedence::Path,
1452 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1453 ExprKind::Break(..) => ExprPrecedence::Break,
1454 ExprKind::Continue(..) => ExprPrecedence::Continue,
1455 ExprKind::Ret(..) => ExprPrecedence::Ret,
1456 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1457 ExprKind::LlvmInlineAsm(..) => ExprPrecedence::InlineAsm,
1458 ExprKind::Struct(..) => ExprPrecedence::Struct,
1459 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1460 ExprKind::Yield(..) => ExprPrecedence::Yield,
1461 ExprKind::Err => ExprPrecedence::Err,
1465 // Whether this looks like a place expr, without checking for deref
1467 // This will return `true` in some potentially surprising cases such as
1468 // `CONSTANT.field`.
1469 pub fn is_syntactic_place_expr(&self) -> bool {
1470 self.is_place_expr(|_| true)
1473 /// Whether this is a place expression.
1475 /// `allow_projections_from` should return `true` if indexing a field or index expression based
1476 /// on the given expression should be considered a place expression.
1477 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1479 ExprKind::Path(QPath::Resolved(_, ref path)) => {
1480 matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static, _) | Res::Err)
1483 // Type ascription inherits its place expression kind from its
1485 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1486 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1488 ExprKind::Unary(UnOp::Deref, _) => true,
1490 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1491 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1494 // Lang item paths cannot currently be local variables or statics.
1495 ExprKind::Path(QPath::LangItem(..)) => false,
1497 // Partially qualified paths in expressions can only legally
1498 // refer to associated items which are always rvalues.
1499 ExprKind::Path(QPath::TypeRelative(..))
1500 | ExprKind::Call(..)
1501 | ExprKind::MethodCall(..)
1502 | ExprKind::Struct(..)
1505 | ExprKind::Match(..)
1506 | ExprKind::Closure(..)
1507 | ExprKind::Block(..)
1508 | ExprKind::Repeat(..)
1509 | ExprKind::Array(..)
1510 | ExprKind::Break(..)
1511 | ExprKind::Continue(..)
1514 | ExprKind::Loop(..)
1515 | ExprKind::Assign(..)
1516 | ExprKind::InlineAsm(..)
1517 | ExprKind::LlvmInlineAsm(..)
1518 | ExprKind::AssignOp(..)
1520 | ExprKind::ConstBlock(..)
1521 | ExprKind::Unary(..)
1523 | ExprKind::AddrOf(..)
1524 | ExprKind::Binary(..)
1525 | ExprKind::Yield(..)
1526 | ExprKind::Cast(..)
1527 | ExprKind::DropTemps(..)
1528 | ExprKind::Err => false,
1532 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1533 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1534 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1535 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1536 /// beyond remembering to call this function before doing analysis on it.
1537 pub fn peel_drop_temps(&self) -> &Self {
1538 let mut expr = self;
1539 while let ExprKind::DropTemps(inner) = &expr.kind {
1545 pub fn peel_blocks(&self) -> &Self {
1546 let mut expr = self;
1547 while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind {
1553 pub fn can_have_side_effects(&self) -> bool {
1554 match self.peel_drop_temps().kind {
1555 ExprKind::Path(_) | ExprKind::Lit(_) => false,
1556 ExprKind::Type(base, _)
1557 | ExprKind::Unary(_, base)
1558 | ExprKind::Field(base, _)
1559 | ExprKind::Index(base, _)
1560 | ExprKind::AddrOf(.., base)
1561 | ExprKind::Cast(base, _) => {
1562 // This isn't exactly true for `Index` and all `Unnary`, but we are using this
1563 // method exclusively for diagnostics and there's a *cultural* pressure against
1564 // them being used only for its side-effects.
1565 base.can_have_side_effects()
1567 ExprKind::Struct(_, fields, init) => fields
1569 .map(|field| field.expr)
1570 .chain(init.into_iter())
1571 .all(|e| e.can_have_side_effects()),
1573 ExprKind::Array(args)
1574 | ExprKind::Tup(args)
1578 ExprKind::Path(QPath::Resolved(
1580 Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. },
1585 ) => args.iter().all(|arg| arg.can_have_side_effects()),
1587 | ExprKind::Match(..)
1588 | ExprKind::MethodCall(..)
1589 | ExprKind::Call(..)
1590 | ExprKind::Closure(..)
1591 | ExprKind::Block(..)
1592 | ExprKind::Repeat(..)
1593 | ExprKind::Break(..)
1594 | ExprKind::Continue(..)
1597 | ExprKind::Loop(..)
1598 | ExprKind::Assign(..)
1599 | ExprKind::InlineAsm(..)
1600 | ExprKind::LlvmInlineAsm(..)
1601 | ExprKind::AssignOp(..)
1602 | ExprKind::ConstBlock(..)
1604 | ExprKind::Binary(..)
1605 | ExprKind::Yield(..)
1606 | ExprKind::DropTemps(..)
1607 | ExprKind::Err => true,
1612 /// Checks if the specified expression is a built-in range literal.
1613 /// (See: `LoweringContext::lower_expr()`).
1614 pub fn is_range_literal(expr: &Expr<'_>) -> bool {
1616 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1617 ExprKind::Struct(ref qpath, _, _) => matches!(
1622 | LangItem::RangeFrom
1623 | LangItem::RangeFull
1624 | LangItem::RangeToInclusive,
1629 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1630 ExprKind::Call(ref func, _) => {
1631 matches!(func.kind, ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, _)))
1638 #[derive(Debug, HashStable_Generic)]
1639 pub enum ExprKind<'hir> {
1640 /// A `box x` expression.
1641 Box(&'hir Expr<'hir>),
1642 /// Allow anonymous constants from an inline `const` block
1643 ConstBlock(AnonConst),
1644 /// An array (e.g., `[a, b, c, d]`).
1645 Array(&'hir [Expr<'hir>]),
1646 /// A function call.
1648 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1649 /// and the second field is the list of arguments.
1650 /// This also represents calling the constructor of
1651 /// tuple-like ADTs such as tuple structs and enum variants.
1652 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1653 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1655 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1656 /// (within the angle brackets).
1657 /// The first element of the vector of `Expr`s is the expression that evaluates
1658 /// to the object on which the method is being called on (the receiver),
1659 /// and the remaining elements are the rest of the arguments.
1660 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1661 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1662 /// The final `Span` represents the span of the function and arguments
1663 /// (e.g. `foo::<Bar, Baz>(a, b, c, d)` in `x.foo::<Bar, Baz>(a, b, c, d)`
1665 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1666 /// the `hir_id` of the `MethodCall` node itself.
1668 /// [`type_dependent_def_id`]: ../ty/struct.TypeckResults.html#method.type_dependent_def_id
1669 MethodCall(&'hir PathSegment<'hir>, Span, &'hir [Expr<'hir>], Span),
1670 /// A tuple (e.g., `(a, b, c, d)`).
1671 Tup(&'hir [Expr<'hir>]),
1672 /// A binary operation (e.g., `a + b`, `a * b`).
1673 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1674 /// A unary operation (e.g., `!x`, `*x`).
1675 Unary(UnOp, &'hir Expr<'hir>),
1676 /// A literal (e.g., `1`, `"foo"`).
1678 /// A cast (e.g., `foo as f64`).
1679 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1680 /// A type reference (e.g., `Foo`).
1681 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1682 /// Wraps the expression in a terminating scope.
1683 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1685 /// This construct only exists to tweak the drop order in HIR lowering.
1686 /// An example of that is the desugaring of `for` loops.
1687 DropTemps(&'hir Expr<'hir>),
1688 /// A `let $pat = $expr` expression.
1690 /// These are not `Local` and only occur as expressions.
1691 /// The `let Some(x) = foo()` in `if let Some(x) = foo()` is an example of `Let(..)`.
1692 Let(&'hir Pat<'hir>, &'hir Expr<'hir>, Span),
1693 /// An `if` block, with an optional else block.
1695 /// I.e., `if <expr> { <expr> } else { <expr> }`.
1696 If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
1697 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1699 /// I.e., `'label: loop { <block> }`.
1701 /// The `Span` is the loop header (`for x in y`/`while let pat = expr`).
1702 Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span),
1703 /// A `match` block, with a source that indicates whether or not it is
1704 /// the result of a desugaring, and if so, which kind.
1705 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1706 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1708 /// The `Span` is the argument block `|...|`.
1710 /// This may also be a generator literal or an `async block` as indicated by the
1711 /// `Option<Movability>`.
1712 Closure(CaptureBy, &'hir FnDecl<'hir>, BodyId, Span, Option<Movability>),
1713 /// A block (e.g., `'label: { ... }`).
1714 Block(&'hir Block<'hir>, Option<Label>),
1716 /// An assignment (e.g., `a = foo()`).
1717 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1718 /// An assignment with an operator.
1721 AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1722 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1723 Field(&'hir Expr<'hir>, Ident),
1724 /// An indexing operation (`foo[2]`).
1725 Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1727 /// Path to a definition, possibly containing lifetime or type parameters.
1730 /// A referencing operation (i.e., `&a` or `&mut a`).
1731 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1732 /// A `break`, with an optional label to break.
1733 Break(Destination, Option<&'hir Expr<'hir>>),
1734 /// A `continue`, with an optional label.
1735 Continue(Destination),
1736 /// A `return`, with an optional value to be returned.
1737 Ret(Option<&'hir Expr<'hir>>),
1739 /// Inline assembly (from `asm!`), with its outputs and inputs.
1740 InlineAsm(&'hir InlineAsm<'hir>),
1741 /// Inline assembly (from `llvm_asm!`), with its outputs and inputs.
1742 LlvmInlineAsm(&'hir LlvmInlineAsm<'hir>),
1744 /// A struct or struct-like variant literal expression.
1746 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1747 /// where `base` is the `Option<Expr>`.
1748 Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], Option<&'hir Expr<'hir>>),
1750 /// An array literal constructed from one repeated element.
1752 /// E.g., `[1; 5]`. The first expression is the element
1753 /// to be repeated; the second is the number of times to repeat it.
1754 Repeat(&'hir Expr<'hir>, AnonConst),
1756 /// A suspension point for generators (i.e., `yield <expr>`).
1757 Yield(&'hir Expr<'hir>, YieldSource),
1759 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1763 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1765 /// To resolve the path to a `DefId`, call [`qpath_res`].
1767 /// [`qpath_res`]: ../rustc_middle/ty/struct.TypeckResults.html#method.qpath_res
1768 #[derive(Debug, HashStable_Generic)]
1769 pub enum QPath<'hir> {
1770 /// Path to a definition, optionally "fully-qualified" with a `Self`
1771 /// type, if the path points to an associated item in a trait.
1773 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1774 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1775 /// even though they both have the same two-segment `Clone::clone` `Path`.
1776 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
1778 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1779 /// Will be resolved by type-checking to an associated item.
1781 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1782 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1783 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1784 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
1786 /// Reference to a `#[lang = "foo"]` item.
1787 LangItem(LangItem, Span),
1790 impl<'hir> QPath<'hir> {
1791 /// Returns the span of this `QPath`.
1792 pub fn span(&self) -> Span {
1794 QPath::Resolved(_, path) => path.span,
1795 QPath::TypeRelative(qself, ps) => qself.span.to(ps.ident.span),
1796 QPath::LangItem(_, span) => span,
1800 /// Returns the span of the qself of this `QPath`. For example, `()` in
1801 /// `<() as Trait>::method`.
1802 pub fn qself_span(&self) -> Span {
1804 QPath::Resolved(_, path) => path.span,
1805 QPath::TypeRelative(qself, _) => qself.span,
1806 QPath::LangItem(_, span) => span,
1810 /// Returns the span of the last segment of this `QPath`. For example, `method` in
1811 /// `<() as Trait>::method`.
1812 pub fn last_segment_span(&self) -> Span {
1814 QPath::Resolved(_, path) => path.segments.last().unwrap().ident.span,
1815 QPath::TypeRelative(_, segment) => segment.ident.span,
1816 QPath::LangItem(_, span) => span,
1821 /// Hints at the original code for a let statement.
1822 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1823 pub enum LocalSource {
1824 /// A `match _ { .. }`.
1826 /// When lowering async functions, we create locals within the `async move` so that
1827 /// all parameters are dropped after the future is polled.
1829 /// ```ignore (pseudo-Rust)
1830 /// async fn foo(<pattern> @ x: Type) {
1832 /// let <pattern> = x;
1837 /// A desugared `<expr>.await`.
1839 /// A desugared `expr = expr`, where the LHS is a tuple, struct or array.
1840 /// The span is that of the `=` sign.
1841 AssignDesugar(Span),
1844 /// Hints at the original code for a `match _ { .. }`.
1845 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
1846 #[derive(HashStable_Generic)]
1847 pub enum MatchSource {
1848 /// A `match _ { .. }`.
1850 /// A desugared `for _ in _ { .. }` loop.
1852 /// A desugared `?` operator.
1854 /// A desugared `<expr>.await`.
1860 pub const fn name(self) -> &'static str {
1864 ForLoopDesugar => "for",
1866 AwaitDesugar => ".await",
1871 /// The loop type that yielded an `ExprKind::Loop`.
1872 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1873 pub enum LoopSource {
1874 /// A `loop { .. }` loop.
1876 /// A `while _ { .. }` loop.
1878 /// A `for _ in _ { .. }` loop.
1883 pub fn name(self) -> &'static str {
1885 LoopSource::Loop => "loop",
1886 LoopSource::While => "while",
1887 LoopSource::ForLoop => "for",
1892 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1893 pub enum LoopIdError {
1895 UnlabeledCfInWhileCondition,
1899 impl fmt::Display for LoopIdError {
1900 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1901 f.write_str(match self {
1902 LoopIdError::OutsideLoopScope => "not inside loop scope",
1903 LoopIdError::UnlabeledCfInWhileCondition => {
1904 "unlabeled control flow (break or continue) in while condition"
1906 LoopIdError::UnresolvedLabel => "label not found",
1911 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1912 pub struct Destination {
1913 // This is `Some(_)` iff there is an explicit user-specified `label
1914 pub label: Option<Label>,
1916 // These errors are caught and then reported during the diagnostics pass in
1917 // librustc_passes/loops.rs
1918 pub target_id: Result<HirId, LoopIdError>,
1921 /// The yield kind that caused an `ExprKind::Yield`.
1922 #[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
1923 pub enum YieldSource {
1924 /// An `<expr>.await`.
1925 Await { expr: Option<HirId> },
1926 /// A plain `yield`.
1931 pub fn is_await(&self) -> bool {
1933 YieldSource::Await { .. } => true,
1934 YieldSource::Yield => false,
1939 impl fmt::Display for YieldSource {
1940 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1941 f.write_str(match self {
1942 YieldSource::Await { .. } => "`await`",
1943 YieldSource::Yield => "`yield`",
1948 impl From<GeneratorKind> for YieldSource {
1949 fn from(kind: GeneratorKind) -> Self {
1951 // Guess based on the kind of the current generator.
1952 GeneratorKind::Gen => Self::Yield,
1953 GeneratorKind::Async(_) => Self::Await { expr: None },
1958 // N.B., if you change this, you'll probably want to change the corresponding
1959 // type structure in middle/ty.rs as well.
1960 #[derive(Debug, HashStable_Generic)]
1961 pub struct MutTy<'hir> {
1962 pub ty: &'hir Ty<'hir>,
1963 pub mutbl: Mutability,
1966 /// Represents a function's signature in a trait declaration,
1967 /// trait implementation, or a free function.
1968 #[derive(Debug, HashStable_Generic)]
1969 pub struct FnSig<'hir> {
1970 pub header: FnHeader,
1971 pub decl: &'hir FnDecl<'hir>,
1975 // The bodies for items are stored "out of line", in a separate
1976 // hashmap in the `Crate`. Here we just record the hir-id of the item
1977 // so it can fetched later.
1978 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
1979 pub struct TraitItemId {
1980 pub def_id: LocalDefId,
1985 pub fn hir_id(&self) -> HirId {
1986 // Items are always HIR owners.
1987 HirId::make_owner(self.def_id)
1991 /// Represents an item declaration within a trait declaration,
1992 /// possibly including a default implementation. A trait item is
1993 /// either required (meaning it doesn't have an implementation, just a
1994 /// signature) or provided (meaning it has a default implementation).
1996 pub struct TraitItem<'hir> {
1998 pub def_id: LocalDefId,
1999 pub generics: Generics<'hir>,
2000 pub kind: TraitItemKind<'hir>,
2004 impl TraitItem<'_> {
2006 pub fn hir_id(&self) -> HirId {
2007 // Items are always HIR owners.
2008 HirId::make_owner(self.def_id)
2011 pub fn trait_item_id(&self) -> TraitItemId {
2012 TraitItemId { def_id: self.def_id }
2016 /// Represents a trait method's body (or just argument names).
2017 #[derive(Encodable, Debug, HashStable_Generic)]
2018 pub enum TraitFn<'hir> {
2019 /// No default body in the trait, just a signature.
2020 Required(&'hir [Ident]),
2022 /// Both signature and body are provided in the trait.
2026 /// Represents a trait method or associated constant or type
2027 #[derive(Debug, HashStable_Generic)]
2028 pub enum TraitItemKind<'hir> {
2029 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
2030 Const(&'hir Ty<'hir>, Option<BodyId>),
2031 /// An associated function with an optional body.
2032 Fn(FnSig<'hir>, TraitFn<'hir>),
2033 /// An associated type with (possibly empty) bounds and optional concrete
2035 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
2038 // The bodies for items are stored "out of line", in a separate
2039 // hashmap in the `Crate`. Here we just record the hir-id of the item
2040 // so it can fetched later.
2041 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
2042 pub struct ImplItemId {
2043 pub def_id: LocalDefId,
2048 pub fn hir_id(&self) -> HirId {
2049 // Items are always HIR owners.
2050 HirId::make_owner(self.def_id)
2054 /// Represents anything within an `impl` block.
2056 pub struct ImplItem<'hir> {
2058 pub def_id: LocalDefId,
2059 pub vis: Visibility<'hir>,
2060 pub defaultness: Defaultness,
2061 pub generics: Generics<'hir>,
2062 pub kind: ImplItemKind<'hir>,
2068 pub fn hir_id(&self) -> HirId {
2069 // Items are always HIR owners.
2070 HirId::make_owner(self.def_id)
2073 pub fn impl_item_id(&self) -> ImplItemId {
2074 ImplItemId { def_id: self.def_id }
2078 /// Represents various kinds of content within an `impl`.
2079 #[derive(Debug, HashStable_Generic)]
2080 pub enum ImplItemKind<'hir> {
2081 /// An associated constant of the given type, set to the constant result
2082 /// of the expression.
2083 Const(&'hir Ty<'hir>, BodyId),
2084 /// An associated function implementation with the given signature and body.
2085 Fn(FnSig<'hir>, BodyId),
2086 /// An associated type.
2087 TyAlias(&'hir Ty<'hir>),
2090 // The name of the associated type for `Fn` return types.
2091 pub const FN_OUTPUT_NAME: Symbol = sym::Output;
2093 /// Bind a type to an associated type (i.e., `A = Foo`).
2095 /// Bindings like `A: Debug` are represented as a special type `A =
2096 /// $::Debug` that is understood by the astconv code.
2098 /// FIXME(alexreg): why have a separate type for the binding case,
2099 /// wouldn't it be better to make the `ty` field an enum like the
2103 /// enum TypeBindingKind {
2108 #[derive(Debug, HashStable_Generic)]
2109 pub struct TypeBinding<'hir> {
2111 #[stable_hasher(project(name))]
2113 pub gen_args: &'hir GenericArgs<'hir>,
2114 pub kind: TypeBindingKind<'hir>,
2118 // Represents the two kinds of type bindings.
2119 #[derive(Debug, HashStable_Generic)]
2120 pub enum TypeBindingKind<'hir> {
2121 /// E.g., `Foo<Bar: Send>`.
2122 Constraint { bounds: &'hir [GenericBound<'hir>] },
2123 /// E.g., `Foo<Bar = ()>`.
2124 Equality { ty: &'hir Ty<'hir> },
2127 impl TypeBinding<'_> {
2128 pub fn ty(&self) -> &Ty<'_> {
2130 TypeBindingKind::Equality { ref ty } => ty,
2131 _ => panic!("expected equality type binding for parenthesized generic args"),
2137 pub struct Ty<'hir> {
2139 pub kind: TyKind<'hir>,
2143 /// Not represented directly in the AST; referred to by name through a `ty_path`.
2144 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
2145 #[derive(HashStable_Generic)]
2156 /// All of the primitive types
2157 pub const ALL: [Self; 17] = [
2158 // any changes here should also be reflected in `PrimTy::from_name`
2159 Self::Int(IntTy::I8),
2160 Self::Int(IntTy::I16),
2161 Self::Int(IntTy::I32),
2162 Self::Int(IntTy::I64),
2163 Self::Int(IntTy::I128),
2164 Self::Int(IntTy::Isize),
2165 Self::Uint(UintTy::U8),
2166 Self::Uint(UintTy::U16),
2167 Self::Uint(UintTy::U32),
2168 Self::Uint(UintTy::U64),
2169 Self::Uint(UintTy::U128),
2170 Self::Uint(UintTy::Usize),
2171 Self::Float(FloatTy::F32),
2172 Self::Float(FloatTy::F64),
2178 /// Like [`PrimTy::name`], but returns a &str instead of a symbol.
2181 pub fn name_str(self) -> &'static str {
2183 PrimTy::Int(i) => i.name_str(),
2184 PrimTy::Uint(u) => u.name_str(),
2185 PrimTy::Float(f) => f.name_str(),
2186 PrimTy::Str => "str",
2187 PrimTy::Bool => "bool",
2188 PrimTy::Char => "char",
2192 pub fn name(self) -> Symbol {
2194 PrimTy::Int(i) => i.name(),
2195 PrimTy::Uint(u) => u.name(),
2196 PrimTy::Float(f) => f.name(),
2197 PrimTy::Str => sym::str,
2198 PrimTy::Bool => sym::bool,
2199 PrimTy::Char => sym::char,
2203 /// Returns the matching `PrimTy` for a `Symbol` such as "str" or "i32".
2204 /// Returns `None` if no matching type is found.
2205 pub fn from_name(name: Symbol) -> Option<Self> {
2206 let ty = match name {
2207 // any changes here should also be reflected in `PrimTy::ALL`
2208 sym::i8 => Self::Int(IntTy::I8),
2209 sym::i16 => Self::Int(IntTy::I16),
2210 sym::i32 => Self::Int(IntTy::I32),
2211 sym::i64 => Self::Int(IntTy::I64),
2212 sym::i128 => Self::Int(IntTy::I128),
2213 sym::isize => Self::Int(IntTy::Isize),
2214 sym::u8 => Self::Uint(UintTy::U8),
2215 sym::u16 => Self::Uint(UintTy::U16),
2216 sym::u32 => Self::Uint(UintTy::U32),
2217 sym::u64 => Self::Uint(UintTy::U64),
2218 sym::u128 => Self::Uint(UintTy::U128),
2219 sym::usize => Self::Uint(UintTy::Usize),
2220 sym::f32 => Self::Float(FloatTy::F32),
2221 sym::f64 => Self::Float(FloatTy::F64),
2222 sym::bool => Self::Bool,
2223 sym::char => Self::Char,
2224 sym::str => Self::Str,
2231 #[derive(Debug, HashStable_Generic)]
2232 pub struct BareFnTy<'hir> {
2233 pub unsafety: Unsafety,
2235 pub generic_params: &'hir [GenericParam<'hir>],
2236 pub decl: &'hir FnDecl<'hir>,
2237 pub param_names: &'hir [Ident],
2240 #[derive(Debug, HashStable_Generic)]
2241 pub struct OpaqueTy<'hir> {
2242 pub generics: Generics<'hir>,
2243 pub bounds: GenericBounds<'hir>,
2244 pub impl_trait_fn: Option<DefId>,
2245 pub origin: OpaqueTyOrigin,
2248 /// From whence the opaque type came.
2249 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2250 pub enum OpaqueTyOrigin {
2255 /// type aliases: `type Foo = impl Trait;`
2259 /// The various kinds of types recognized by the compiler.
2260 #[derive(Debug, HashStable_Generic)]
2261 pub enum TyKind<'hir> {
2262 /// A variable length slice (i.e., `[T]`).
2263 Slice(&'hir Ty<'hir>),
2264 /// A fixed length array (i.e., `[T; n]`).
2265 Array(&'hir Ty<'hir>, AnonConst),
2266 /// A raw pointer (i.e., `*const T` or `*mut T`).
2268 /// A reference (i.e., `&'a T` or `&'a mut T`).
2269 Rptr(Lifetime, MutTy<'hir>),
2270 /// A bare function (e.g., `fn(usize) -> bool`).
2271 BareFn(&'hir BareFnTy<'hir>),
2272 /// The never type (`!`).
2274 /// A tuple (`(A, B, C, D, ...)`).
2275 Tup(&'hir [Ty<'hir>]),
2276 /// A path to a type definition (`module::module::...::Type`), or an
2277 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2279 /// Type parameters may be stored in each `PathSegment`.
2281 /// An opaque type definition itself. This is only used for `impl Trait`.
2283 /// The generic argument list contains the lifetimes (and in the future
2284 /// possibly parameters) that are actually bound on the `impl Trait`.
2285 OpaqueDef(ItemId, &'hir [GenericArg<'hir>]),
2286 /// A trait object type `Bound1 + Bound2 + Bound3`
2287 /// where `Bound` is a trait or a lifetime.
2288 TraitObject(&'hir [PolyTraitRef<'hir>], Lifetime, TraitObjectSyntax),
2291 /// `TyKind::Infer` means the type should be inferred instead of it having been
2292 /// specified. This can appear anywhere in a type.
2294 /// Placeholder for a type that has failed to be defined.
2298 #[derive(Debug, HashStable_Generic)]
2299 pub enum InlineAsmOperand<'hir> {
2301 reg: InlineAsmRegOrRegClass,
2305 reg: InlineAsmRegOrRegClass,
2307 expr: Option<Expr<'hir>>,
2310 reg: InlineAsmRegOrRegClass,
2315 reg: InlineAsmRegOrRegClass,
2317 in_expr: Expr<'hir>,
2318 out_expr: Option<Expr<'hir>>,
2321 anon_const: AnonConst,
2328 impl<'hir> InlineAsmOperand<'hir> {
2329 pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
2331 Self::In { reg, .. }
2332 | Self::Out { reg, .. }
2333 | Self::InOut { reg, .. }
2334 | Self::SplitInOut { reg, .. } => Some(reg),
2335 Self::Const { .. } | Self::Sym { .. } => None,
2339 pub fn is_clobber(&self) -> bool {
2342 InlineAsmOperand::Out { reg: InlineAsmRegOrRegClass::Reg(_), late: _, expr: None }
2347 #[derive(Debug, HashStable_Generic)]
2348 pub struct InlineAsm<'hir> {
2349 pub template: &'hir [InlineAsmTemplatePiece],
2350 pub template_strs: &'hir [(Symbol, Option<Symbol>, Span)],
2351 pub operands: &'hir [(InlineAsmOperand<'hir>, Span)],
2352 pub options: InlineAsmOptions,
2353 pub line_spans: &'hir [Span],
2356 #[derive(Copy, Clone, Encodable, Decodable, Debug, Hash, HashStable_Generic, PartialEq)]
2357 pub struct LlvmInlineAsmOutput {
2358 pub constraint: Symbol,
2360 pub is_indirect: bool,
2364 // NOTE(eddyb) This is used within MIR as well, so unlike the rest of the HIR,
2365 // it needs to be `Clone` and `Decodable` and use plain `Vec<T>` instead of
2366 // arena-allocated slice.
2367 #[derive(Clone, Encodable, Decodable, Debug, Hash, HashStable_Generic, PartialEq)]
2368 pub struct LlvmInlineAsmInner {
2370 pub asm_str_style: StrStyle,
2371 pub outputs: Vec<LlvmInlineAsmOutput>,
2372 pub inputs: Vec<Symbol>,
2373 pub clobbers: Vec<Symbol>,
2375 pub alignstack: bool,
2376 pub dialect: LlvmAsmDialect,
2379 #[derive(Debug, HashStable_Generic)]
2380 pub struct LlvmInlineAsm<'hir> {
2381 pub inner: LlvmInlineAsmInner,
2382 pub outputs_exprs: &'hir [Expr<'hir>],
2383 pub inputs_exprs: &'hir [Expr<'hir>],
2386 /// Represents a parameter in a function header.
2387 #[derive(Debug, HashStable_Generic)]
2388 pub struct Param<'hir> {
2390 pub pat: &'hir Pat<'hir>,
2395 /// Represents the header (not the body) of a function declaration.
2396 #[derive(Debug, HashStable_Generic)]
2397 pub struct FnDecl<'hir> {
2398 /// The types of the function's parameters.
2400 /// Additional argument data is stored in the function's [body](Body::params).
2401 pub inputs: &'hir [Ty<'hir>],
2402 pub output: FnRetTy<'hir>,
2403 pub c_variadic: bool,
2404 /// Does the function have an implicit self?
2405 pub implicit_self: ImplicitSelfKind,
2408 /// Represents what type of implicit self a function has, if any.
2409 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2410 pub enum ImplicitSelfKind {
2411 /// Represents a `fn x(self);`.
2413 /// Represents a `fn x(mut self);`.
2415 /// Represents a `fn x(&self);`.
2417 /// Represents a `fn x(&mut self);`.
2419 /// Represents when a function does not have a self argument or
2420 /// when a function has a `self: X` argument.
2424 impl ImplicitSelfKind {
2425 /// Does this represent an implicit self?
2426 pub fn has_implicit_self(&self) -> bool {
2427 !matches!(*self, ImplicitSelfKind::None)
2431 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable, Debug)]
2432 #[derive(HashStable_Generic)]
2438 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable, HashStable_Generic)]
2439 pub enum Defaultness {
2440 Default { has_value: bool },
2445 pub fn has_value(&self) -> bool {
2447 Defaultness::Default { has_value } => has_value,
2448 Defaultness::Final => true,
2452 pub fn is_final(&self) -> bool {
2453 *self == Defaultness::Final
2456 pub fn is_default(&self) -> bool {
2457 matches!(*self, Defaultness::Default { .. })
2461 #[derive(Debug, HashStable_Generic)]
2462 pub enum FnRetTy<'hir> {
2463 /// Return type is not specified.
2465 /// Functions default to `()` and
2466 /// closures default to inference. Span points to where return
2467 /// type would be inserted.
2468 DefaultReturn(Span),
2469 /// Everything else.
2470 Return(&'hir Ty<'hir>),
2475 pub fn span(&self) -> Span {
2477 Self::DefaultReturn(span) => span,
2478 Self::Return(ref ty) => ty.span,
2483 #[derive(Encodable, Debug)]
2484 pub struct Mod<'hir> {
2485 /// A span from the first token past `{` to the last token until `}`.
2486 /// For `mod foo;`, the inner span ranges from the first token
2487 /// to the last token in the external file.
2489 pub item_ids: &'hir [ItemId],
2492 #[derive(Debug, HashStable_Generic)]
2493 pub struct EnumDef<'hir> {
2494 pub variants: &'hir [Variant<'hir>],
2497 #[derive(Debug, HashStable_Generic)]
2498 pub struct Variant<'hir> {
2499 /// Name of the variant.
2500 #[stable_hasher(project(name))]
2502 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2504 /// Fields and constructor id of the variant.
2505 pub data: VariantData<'hir>,
2506 /// Explicit discriminant (e.g., `Foo = 1`).
2507 pub disr_expr: Option<AnonConst>,
2512 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2514 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2515 /// Also produced for each element of a list `use`, e.g.
2516 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2519 /// Glob import, e.g., `use foo::*`.
2522 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2523 /// an additional `use foo::{}` for performing checks such as
2524 /// unstable feature gating. May be removed in the future.
2528 /// References to traits in impls.
2530 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2531 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2532 /// trait being referred to but just a unique `HirId` that serves as a key
2533 /// within the resolution map.
2534 #[derive(Clone, Debug, HashStable_Generic)]
2535 pub struct TraitRef<'hir> {
2536 pub path: &'hir Path<'hir>,
2537 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2538 #[stable_hasher(ignore)]
2539 pub hir_ref_id: HirId,
2543 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2544 pub fn trait_def_id(&self) -> Option<DefId> {
2545 match self.path.res {
2546 Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
2548 _ => unreachable!(),
2553 #[derive(Clone, Debug, HashStable_Generic)]
2554 pub struct PolyTraitRef<'hir> {
2555 /// The `'a` in `for<'a> Foo<&'a T>`.
2556 pub bound_generic_params: &'hir [GenericParam<'hir>],
2558 /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
2559 pub trait_ref: TraitRef<'hir>,
2564 pub type Visibility<'hir> = Spanned<VisibilityKind<'hir>>;
2566 #[derive(Copy, Clone, Debug)]
2567 pub enum VisibilityKind<'hir> {
2570 Restricted { path: &'hir Path<'hir>, hir_id: HirId },
2574 impl VisibilityKind<'_> {
2575 pub fn is_pub(&self) -> bool {
2576 matches!(*self, VisibilityKind::Public)
2579 pub fn is_pub_restricted(&self) -> bool {
2581 VisibilityKind::Public | VisibilityKind::Inherited => false,
2582 VisibilityKind::Crate(..) | VisibilityKind::Restricted { .. } => true,
2587 #[derive(Debug, HashStable_Generic)]
2588 pub struct FieldDef<'hir> {
2590 #[stable_hasher(project(name))]
2592 pub vis: Visibility<'hir>,
2594 pub ty: &'hir Ty<'hir>,
2598 // Still necessary in couple of places
2599 pub fn is_positional(&self) -> bool {
2600 let first = self.ident.as_str().as_bytes()[0];
2601 (b'0'..=b'9').contains(&first)
2605 /// Fields and constructor IDs of enum variants and structs.
2606 #[derive(Debug, HashStable_Generic)]
2607 pub enum VariantData<'hir> {
2608 /// A struct variant.
2610 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2611 Struct(&'hir [FieldDef<'hir>], /* recovered */ bool),
2612 /// A tuple variant.
2614 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2615 Tuple(&'hir [FieldDef<'hir>], HirId),
2618 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2622 impl VariantData<'hir> {
2623 /// Return the fields of this variant.
2624 pub fn fields(&self) -> &'hir [FieldDef<'hir>] {
2626 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2631 /// Return the `HirId` of this variant's constructor, if it has one.
2632 pub fn ctor_hir_id(&self) -> Option<HirId> {
2634 VariantData::Struct(_, _) => None,
2635 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2640 // The bodies for items are stored "out of line", in a separate
2641 // hashmap in the `Crate`. Here we just record the hir-id of the item
2642 // so it can fetched later.
2643 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug, Hash)]
2645 pub def_id: LocalDefId,
2650 pub fn hir_id(&self) -> HirId {
2651 // Items are always HIR owners.
2652 HirId::make_owner(self.def_id)
2658 /// The name might be a dummy name in case of anonymous items
2660 pub struct Item<'hir> {
2662 pub def_id: LocalDefId,
2663 pub kind: ItemKind<'hir>,
2664 pub vis: Visibility<'hir>,
2670 pub fn hir_id(&self) -> HirId {
2671 // Items are always HIR owners.
2672 HirId::make_owner(self.def_id)
2675 pub fn item_id(&self) -> ItemId {
2676 ItemId { def_id: self.def_id }
2680 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2681 #[derive(Encodable, Decodable, HashStable_Generic)]
2688 pub fn prefix_str(&self) -> &'static str {
2690 Self::Unsafe => "unsafe ",
2696 impl fmt::Display for Unsafety {
2697 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2698 f.write_str(match *self {
2699 Self::Unsafe => "unsafe",
2700 Self::Normal => "normal",
2705 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2706 #[derive(Encodable, Decodable, HashStable_Generic)]
2707 pub enum Constness {
2712 impl fmt::Display for Constness {
2713 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2714 f.write_str(match *self {
2715 Self::Const => "const",
2716 Self::NotConst => "non-const",
2721 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2722 pub struct FnHeader {
2723 pub unsafety: Unsafety,
2724 pub constness: Constness,
2725 pub asyncness: IsAsync,
2730 pub fn is_const(&self) -> bool {
2731 matches!(&self.constness, Constness::Const)
2735 #[derive(Debug, HashStable_Generic)]
2736 pub enum ItemKind<'hir> {
2737 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2739 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2740 ExternCrate(Option<Symbol>),
2742 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2746 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2747 Use(&'hir Path<'hir>, UseKind),
2749 /// A `static` item.
2750 Static(&'hir Ty<'hir>, Mutability, BodyId),
2752 Const(&'hir Ty<'hir>, BodyId),
2753 /// A function declaration.
2754 Fn(FnSig<'hir>, Generics<'hir>, BodyId),
2755 /// A MBE macro definition (`macro_rules!` or `macro`).
2756 Macro(ast::MacroDef),
2759 /// An external module, e.g. `extern { .. }`.
2760 ForeignMod { abi: Abi, items: &'hir [ForeignItemRef] },
2761 /// Module-level inline assembly (from `global_asm!`).
2762 GlobalAsm(&'hir InlineAsm<'hir>),
2763 /// A type alias, e.g., `type Foo = Bar<u8>`.
2764 TyAlias(&'hir Ty<'hir>, Generics<'hir>),
2765 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2766 OpaqueTy(OpaqueTy<'hir>),
2767 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2768 Enum(EnumDef<'hir>, Generics<'hir>),
2769 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2770 Struct(VariantData<'hir>, Generics<'hir>),
2771 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2772 Union(VariantData<'hir>, Generics<'hir>),
2773 /// A trait definition.
2774 Trait(IsAuto, Unsafety, Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
2776 TraitAlias(Generics<'hir>, GenericBounds<'hir>),
2778 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2782 #[derive(Debug, HashStable_Generic)]
2783 pub struct Impl<'hir> {
2784 pub unsafety: Unsafety,
2785 pub polarity: ImplPolarity,
2786 pub defaultness: Defaultness,
2787 // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata
2788 // decoding as `Span`s cannot be decoded when a `Session` is not available.
2789 pub defaultness_span: Option<Span>,
2790 pub constness: Constness,
2791 pub generics: Generics<'hir>,
2793 /// The trait being implemented, if any.
2794 pub of_trait: Option<TraitRef<'hir>>,
2796 pub self_ty: &'hir Ty<'hir>,
2797 pub items: &'hir [ImplItemRef],
2801 pub fn generics(&self) -> Option<&Generics<'_>> {
2803 ItemKind::Fn(_, ref generics, _)
2804 | ItemKind::TyAlias(_, ref generics)
2805 | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
2806 | ItemKind::Enum(_, ref generics)
2807 | ItemKind::Struct(_, ref generics)
2808 | ItemKind::Union(_, ref generics)
2809 | ItemKind::Trait(_, _, ref generics, _, _)
2810 | ItemKind::Impl(Impl { ref generics, .. }) => generics,
2815 pub fn descr(&self) -> &'static str {
2817 ItemKind::ExternCrate(..) => "extern crate",
2818 ItemKind::Use(..) => "`use` import",
2819 ItemKind::Static(..) => "static item",
2820 ItemKind::Const(..) => "constant item",
2821 ItemKind::Fn(..) => "function",
2822 ItemKind::Macro(..) => "macro",
2823 ItemKind::Mod(..) => "module",
2824 ItemKind::ForeignMod { .. } => "extern block",
2825 ItemKind::GlobalAsm(..) => "global asm item",
2826 ItemKind::TyAlias(..) => "type alias",
2827 ItemKind::OpaqueTy(..) => "opaque type",
2828 ItemKind::Enum(..) => "enum",
2829 ItemKind::Struct(..) => "struct",
2830 ItemKind::Union(..) => "union",
2831 ItemKind::Trait(..) => "trait",
2832 ItemKind::TraitAlias(..) => "trait alias",
2833 ItemKind::Impl(..) => "implementation",
2838 /// A reference from an trait to one of its associated items. This
2839 /// contains the item's id, naturally, but also the item's name and
2840 /// some other high-level details (like whether it is an associated
2841 /// type or method, and whether it is public). This allows other
2842 /// passes to find the impl they want without loading the ID (which
2843 /// means fewer edges in the incremental compilation graph).
2844 #[derive(Encodable, Debug, HashStable_Generic)]
2845 pub struct TraitItemRef {
2846 pub id: TraitItemId,
2847 #[stable_hasher(project(name))]
2849 pub kind: AssocItemKind,
2851 pub defaultness: Defaultness,
2854 /// A reference from an impl to one of its associated items. This
2855 /// contains the item's ID, naturally, but also the item's name and
2856 /// some other high-level details (like whether it is an associated
2857 /// type or method, and whether it is public). This allows other
2858 /// passes to find the impl they want without loading the ID (which
2859 /// means fewer edges in the incremental compilation graph).
2860 #[derive(Debug, HashStable_Generic)]
2861 pub struct ImplItemRef {
2863 #[stable_hasher(project(name))]
2865 pub kind: AssocItemKind,
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 {
2901 pub id: ForeignItemId,
2902 #[stable_hasher(project(name))]
2908 pub struct ForeignItem<'hir> {
2910 pub kind: ForeignItemKind<'hir>,
2911 pub def_id: LocalDefId,
2913 pub vis: Visibility<'hir>,
2916 impl ForeignItem<'_> {
2918 pub fn hir_id(&self) -> HirId {
2919 // Items are always HIR owners.
2920 HirId::make_owner(self.def_id)
2923 pub fn foreign_item_id(&self) -> ForeignItemId {
2924 ForeignItemId { def_id: self.def_id }
2928 /// An item within an `extern` block.
2929 #[derive(Debug, HashStable_Generic)]
2930 pub enum ForeignItemKind<'hir> {
2931 /// A foreign function.
2932 Fn(&'hir FnDecl<'hir>, &'hir [Ident], Generics<'hir>),
2933 /// A foreign static item (`static ext: u8`).
2934 Static(&'hir Ty<'hir>, Mutability),
2939 /// A variable captured by a closure.
2940 #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)]
2942 // First span where it is accessed (there can be multiple).
2946 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2947 // has length > 0 if the trait is found through an chain of imports, starting with the
2948 // import/use statement in the scope where the trait is used.
2949 #[derive(Encodable, Decodable, Clone, Debug)]
2950 pub struct TraitCandidate {
2952 pub import_ids: SmallVec<[LocalDefId; 1]>,
2955 #[derive(Copy, Clone, Debug, HashStable_Generic)]
2956 pub enum OwnerNode<'hir> {
2957 Item(&'hir Item<'hir>),
2958 ForeignItem(&'hir ForeignItem<'hir>),
2959 TraitItem(&'hir TraitItem<'hir>),
2960 ImplItem(&'hir ImplItem<'hir>),
2961 Crate(&'hir Mod<'hir>),
2964 impl<'hir> OwnerNode<'hir> {
2965 pub fn ident(&self) -> Option<Ident> {
2967 OwnerNode::Item(Item { ident, .. })
2968 | OwnerNode::ForeignItem(ForeignItem { ident, .. })
2969 | OwnerNode::ImplItem(ImplItem { ident, .. })
2970 | OwnerNode::TraitItem(TraitItem { ident, .. }) => Some(*ident),
2971 OwnerNode::Crate(..) => None,
2975 pub fn span(&self) -> Span {
2977 OwnerNode::Item(Item { span, .. })
2978 | OwnerNode::ForeignItem(ForeignItem { span, .. })
2979 | OwnerNode::ImplItem(ImplItem { span, .. })
2980 | OwnerNode::TraitItem(TraitItem { span, .. })
2981 | OwnerNode::Crate(Mod { inner: span, .. }) => *span,
2985 pub fn fn_decl(&self) -> Option<&FnDecl<'hir>> {
2987 OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
2988 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
2989 | OwnerNode::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
2990 OwnerNode::ForeignItem(ForeignItem {
2991 kind: ForeignItemKind::Fn(fn_decl, _, _),
2993 }) => Some(fn_decl),
2998 pub fn body_id(&self) -> Option<BodyId> {
3000 OwnerNode::TraitItem(TraitItem {
3001 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3004 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3005 | OwnerNode::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3010 pub fn generics(&self) -> Option<&'hir Generics<'hir>> {
3012 OwnerNode::TraitItem(TraitItem { generics, .. })
3013 | OwnerNode::ImplItem(ImplItem { generics, .. }) => Some(generics),
3014 OwnerNode::Item(item) => item.kind.generics(),
3019 pub fn def_id(self) -> LocalDefId {
3021 OwnerNode::Item(Item { def_id, .. })
3022 | OwnerNode::TraitItem(TraitItem { def_id, .. })
3023 | OwnerNode::ImplItem(ImplItem { def_id, .. })
3024 | OwnerNode::ForeignItem(ForeignItem { def_id, .. }) => *def_id,
3025 OwnerNode::Crate(..) => crate::CRATE_HIR_ID.owner,
3029 pub fn expect_item(self) -> &'hir Item<'hir> {
3031 OwnerNode::Item(n) => n,
3036 pub fn expect_foreign_item(self) -> &'hir ForeignItem<'hir> {
3038 OwnerNode::ForeignItem(n) => n,
3043 pub fn expect_impl_item(self) -> &'hir ImplItem<'hir> {
3045 OwnerNode::ImplItem(n) => n,
3050 pub fn expect_trait_item(self) -> &'hir TraitItem<'hir> {
3052 OwnerNode::TraitItem(n) => n,
3058 impl<'hir> Into<OwnerNode<'hir>> for &'hir Item<'hir> {
3059 fn into(self) -> OwnerNode<'hir> {
3060 OwnerNode::Item(self)
3064 impl<'hir> Into<OwnerNode<'hir>> for &'hir ForeignItem<'hir> {
3065 fn into(self) -> OwnerNode<'hir> {
3066 OwnerNode::ForeignItem(self)
3070 impl<'hir> Into<OwnerNode<'hir>> for &'hir ImplItem<'hir> {
3071 fn into(self) -> OwnerNode<'hir> {
3072 OwnerNode::ImplItem(self)
3076 impl<'hir> Into<OwnerNode<'hir>> for &'hir TraitItem<'hir> {
3077 fn into(self) -> OwnerNode<'hir> {
3078 OwnerNode::TraitItem(self)
3082 impl<'hir> Into<Node<'hir>> for OwnerNode<'hir> {
3083 fn into(self) -> Node<'hir> {
3085 OwnerNode::Item(n) => Node::Item(n),
3086 OwnerNode::ForeignItem(n) => Node::ForeignItem(n),
3087 OwnerNode::ImplItem(n) => Node::ImplItem(n),
3088 OwnerNode::TraitItem(n) => Node::TraitItem(n),
3089 OwnerNode::Crate(n) => Node::Crate(n),
3094 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3095 pub enum Node<'hir> {
3096 Param(&'hir Param<'hir>),
3097 Item(&'hir Item<'hir>),
3098 ForeignItem(&'hir ForeignItem<'hir>),
3099 TraitItem(&'hir TraitItem<'hir>),
3100 ImplItem(&'hir ImplItem<'hir>),
3101 Variant(&'hir Variant<'hir>),
3102 Field(&'hir FieldDef<'hir>),
3103 AnonConst(&'hir AnonConst),
3104 Expr(&'hir Expr<'hir>),
3105 Stmt(&'hir Stmt<'hir>),
3106 PathSegment(&'hir PathSegment<'hir>),
3108 TraitRef(&'hir TraitRef<'hir>),
3109 Binding(&'hir Pat<'hir>),
3110 Pat(&'hir Pat<'hir>),
3111 Arm(&'hir Arm<'hir>),
3112 Block(&'hir Block<'hir>),
3113 Local(&'hir Local<'hir>),
3115 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
3116 /// with synthesized constructors.
3117 Ctor(&'hir VariantData<'hir>),
3119 Lifetime(&'hir Lifetime),
3120 GenericParam(&'hir GenericParam<'hir>),
3121 Visibility(&'hir Visibility<'hir>),
3123 Crate(&'hir Mod<'hir>),
3125 Infer(&'hir InferArg),
3128 impl<'hir> Node<'hir> {
3129 /// Get the identifier of this `Node`, if applicable.
3133 /// Calling `.ident()` on a [`Node::Ctor`] will return `None`
3134 /// because `Ctor`s do not have identifiers themselves.
3135 /// Instead, call `.ident()` on the parent struct/variant, like so:
3137 /// ```ignore (illustrative)
3140 /// .and_then(|ctor_id| tcx.hir().find(tcx.hir().get_parent_node(ctor_id)))
3141 /// .and_then(|parent| parent.ident())
3143 pub fn ident(&self) -> Option<Ident> {
3145 Node::TraitItem(TraitItem { ident, .. })
3146 | Node::ImplItem(ImplItem { ident, .. })
3147 | Node::ForeignItem(ForeignItem { ident, .. })
3148 | Node::Field(FieldDef { ident, .. })
3149 | Node::Variant(Variant { ident, .. })
3150 | Node::Item(Item { ident, .. })
3151 | Node::PathSegment(PathSegment { ident, .. }) => Some(*ident),
3152 Node::Lifetime(lt) => Some(lt.name.ident()),
3153 Node::GenericParam(p) => Some(p.name.ident()),
3155 | Node::AnonConst(..)
3164 | Node::Visibility(..)
3167 | Node::TraitRef(..)
3168 | Node::Infer(..) => None,
3172 pub fn fn_decl(&self) -> Option<&FnDecl<'hir>> {
3174 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3175 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3176 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3177 Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
3184 pub fn body_id(&self) -> Option<BodyId> {
3186 Node::TraitItem(TraitItem {
3187 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3190 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3191 | Node::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3196 pub fn generics(&self) -> Option<&'hir Generics<'hir>> {
3198 Node::TraitItem(TraitItem { generics, .. })
3199 | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
3200 Node::Item(item) => item.kind.generics(),
3205 pub fn hir_id(&self) -> Option<HirId> {
3207 Node::Item(Item { def_id, .. })
3208 | Node::TraitItem(TraitItem { def_id, .. })
3209 | Node::ImplItem(ImplItem { def_id, .. })
3210 | Node::ForeignItem(ForeignItem { def_id, .. }) => Some(HirId::make_owner(*def_id)),
3211 Node::Field(FieldDef { hir_id, .. })
3212 | Node::AnonConst(AnonConst { hir_id, .. })
3213 | Node::Expr(Expr { hir_id, .. })
3214 | Node::Stmt(Stmt { hir_id, .. })
3215 | Node::Ty(Ty { hir_id, .. })
3216 | Node::Binding(Pat { hir_id, .. })
3217 | Node::Pat(Pat { hir_id, .. })
3218 | Node::Arm(Arm { hir_id, .. })
3219 | Node::Block(Block { hir_id, .. })
3220 | Node::Local(Local { hir_id, .. })
3221 | Node::Lifetime(Lifetime { hir_id, .. })
3222 | Node::Param(Param { hir_id, .. })
3223 | Node::Infer(InferArg { hir_id, .. })
3224 | Node::GenericParam(GenericParam { hir_id, .. }) => Some(*hir_id),
3225 Node::TraitRef(TraitRef { hir_ref_id, .. }) => Some(*hir_ref_id),
3226 Node::PathSegment(PathSegment { hir_id, .. }) => *hir_id,
3227 Node::Variant(Variant { id, .. }) => Some(*id),
3228 Node::Ctor(variant) => variant.ctor_hir_id(),
3229 Node::Crate(_) | Node::Visibility(_) => None,
3233 pub fn as_owner(self) -> Option<OwnerNode<'hir>> {
3235 Node::Item(i) => Some(OwnerNode::Item(i)),
3236 Node::ForeignItem(i) => Some(OwnerNode::ForeignItem(i)),
3237 Node::TraitItem(i) => Some(OwnerNode::TraitItem(i)),
3238 Node::ImplItem(i) => Some(OwnerNode::ImplItem(i)),
3239 Node::Crate(i) => Some(OwnerNode::Crate(i)),
3244 pub fn fn_kind(self) -> Option<FnKind<'hir>> {
3246 Node::Item(i) => match i.kind {
3247 ItemKind::Fn(ref sig, ref generics, _) => {
3248 Some(FnKind::ItemFn(i.ident, generics, sig.header, &i.vis))
3252 Node::TraitItem(ti) => match ti.kind {
3253 TraitItemKind::Fn(ref sig, TraitFn::Provided(_)) => {
3254 Some(FnKind::Method(ti.ident, sig, None))
3258 Node::ImplItem(ii) => match ii.kind {
3259 ImplItemKind::Fn(ref sig, _) => Some(FnKind::Method(ii.ident, sig, Some(&ii.vis))),
3262 Node::Expr(e) => match e.kind {
3263 ExprKind::Closure(..) => Some(FnKind::Closure),
3271 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3272 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
3274 rustc_data_structures::static_assert_size!(super::Block<'static>, 48);
3275 rustc_data_structures::static_assert_size!(super::Expr<'static>, 64);
3276 rustc_data_structures::static_assert_size!(super::Pat<'static>, 88);
3277 rustc_data_structures::static_assert_size!(super::QPath<'static>, 24);
3278 rustc_data_structures::static_assert_size!(super::Ty<'static>, 80);
3280 rustc_data_structures::static_assert_size!(super::Item<'static>, 184);
3281 rustc_data_structures::static_assert_size!(super::TraitItem<'static>, 128);
3282 rustc_data_structures::static_assert_size!(super::ImplItem<'static>, 152);
3283 rustc_data_structures::static_assert_size!(super::ForeignItem<'static>, 136);