1 use crate::def::{CtorKind, DefKind, Res};
2 use crate::def_id::{DefId, CRATE_DEF_ID};
3 crate use crate::hir_id::{HirId, ItemLocalId};
4 use crate::{itemlikevisit, LangItem};
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_data_structures::sync::{par_for_each_in, Send, Sync};
14 use rustc_index::vec::IndexVec;
15 use rustc_macros::HashStable_Generic;
16 use rustc_span::source_map::Spanned;
17 use rustc_span::symbol::{kw, sym, Ident, Symbol};
18 use rustc_span::{def_id::LocalDefId, BytePos};
19 use rustc_span::{MultiSpan, Span, DUMMY_SP};
20 use rustc_target::asm::InlineAsmRegOrRegClass;
21 use rustc_target::spec::abi::Abi;
23 use smallvec::SmallVec;
24 use std::collections::BTreeMap;
27 #[derive(Copy, Clone, Encodable, HashStable_Generic)]
32 /// Either "`'a`", referring to a named lifetime definition,
33 /// or "``" (i.e., `kw::Empty`), for elision placeholders.
35 /// HIR lowering inserts these placeholders in type paths that
36 /// refer to type definitions needing lifetime parameters,
37 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
38 pub name: LifetimeName,
41 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
42 #[derive(HashStable_Generic)]
44 /// Some user-given name like `T` or `'x`.
47 /// Synthetic name generated when user elided a lifetime in an impl header.
49 /// E.g., the lifetimes in cases like these:
52 /// impl Foo<'_> for u32
54 /// in that case, we rewrite to
56 /// impl<'f> Foo for &'f u32
57 /// impl<'f> Foo<'f> for u32
59 /// where `'f` is something like `Fresh(0)`. The indices are
60 /// unique per impl, but not necessarily continuous.
63 /// Indicates an illegal name was given and an error has been
64 /// reported (so we should squelch other derived errors). Occurs
65 /// when, e.g., `'_` is used in the wrong place.
70 pub fn ident(&self) -> Ident {
72 ParamName::Plain(ident) => ident,
73 ParamName::Fresh(_) | ParamName::Error => {
74 Ident::with_dummy_span(kw::UnderscoreLifetime)
79 pub fn normalize_to_macros_2_0(&self) -> ParamName {
81 ParamName::Plain(ident) => ParamName::Plain(ident.normalize_to_macros_2_0()),
82 param_name => param_name,
87 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
88 #[derive(HashStable_Generic)]
89 pub enum LifetimeName {
90 /// User-given names or fresh (synthetic) names.
93 /// User wrote nothing (e.g., the lifetime in `&u32`).
96 /// Implicit lifetime in a context like `dyn Foo`. This is
97 /// distinguished from implicit lifetimes elsewhere because the
98 /// lifetime that they default to must appear elsewhere within the
99 /// enclosing type. This means that, in an `impl Trait` context, we
100 /// don't have to create a parameter for them. That is, `impl
101 /// Trait<Item = &u32>` expands to an opaque type like `type
102 /// Foo<'a> = impl Trait<Item = &'a u32>`, but `impl Trait<item =
103 /// dyn Bar>` expands to `type Foo = impl Trait<Item = dyn Bar +
104 /// 'static>`. The latter uses `ImplicitObjectLifetimeDefault` so
105 /// that surrounding code knows not to create a lifetime
107 ImplicitObjectLifetimeDefault,
109 /// Indicates an error during lowering (usually `'_` in wrong place)
110 /// that was already reported.
113 /// User wrote specifies `'_`.
116 /// User wrote `'static`.
121 pub fn ident(&self) -> Ident {
123 LifetimeName::ImplicitObjectLifetimeDefault
124 | LifetimeName::Implicit
125 | LifetimeName::Error => Ident::invalid(),
126 LifetimeName::Underscore => Ident::with_dummy_span(kw::UnderscoreLifetime),
127 LifetimeName::Static => Ident::with_dummy_span(kw::StaticLifetime),
128 LifetimeName::Param(param_name) => param_name.ident(),
132 pub fn is_elided(&self) -> bool {
134 LifetimeName::ImplicitObjectLifetimeDefault
135 | LifetimeName::Implicit
136 | LifetimeName::Underscore => true,
138 // It might seem surprising that `Fresh(_)` counts as
139 // *not* elided -- but this is because, as far as the code
140 // in the compiler is concerned -- `Fresh(_)` variants act
141 // equivalently to "some fresh name". They correspond to
142 // early-bound regions on an impl, in other words.
143 LifetimeName::Error | LifetimeName::Param(_) | LifetimeName::Static => false,
147 fn is_static(&self) -> bool {
148 self == &LifetimeName::Static
151 pub fn normalize_to_macros_2_0(&self) -> LifetimeName {
153 LifetimeName::Param(param_name) => {
154 LifetimeName::Param(param_name.normalize_to_macros_2_0())
156 lifetime_name => lifetime_name,
161 impl fmt::Display for Lifetime {
162 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163 self.name.ident().fmt(f)
167 impl fmt::Debug for Lifetime {
168 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
169 write!(f, "lifetime({}: {})", self.hir_id, self.name.ident())
174 pub fn is_elided(&self) -> bool {
175 self.name.is_elided()
178 pub fn is_static(&self) -> bool {
179 self.name.is_static()
183 /// A `Path` is essentially Rust's notion of a name; for instance,
184 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
185 /// along with a bunch of supporting information.
186 #[derive(Debug, HashStable_Generic)]
187 pub struct Path<'hir> {
189 /// The resolution for the path.
191 /// The segments in the path: the things separated by `::`.
192 pub segments: &'hir [PathSegment<'hir>],
196 pub fn is_global(&self) -> bool {
197 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
201 /// A segment of a path: an identifier, an optional lifetime, and a set of
203 #[derive(Debug, HashStable_Generic)]
204 pub struct PathSegment<'hir> {
205 /// The identifier portion of this path segment.
206 #[stable_hasher(project(name))]
208 // `id` and `res` are optional. We currently only use these in save-analysis,
209 // any path segments without these will not have save-analysis info and
210 // therefore will not have 'jump to def' in IDEs, but otherwise will not be
211 // affected. (In general, we don't bother to get the defs for synthesized
212 // segments, only for segments which have come from the AST).
213 pub hir_id: Option<HirId>,
214 pub res: Option<Res>,
216 /// Type/lifetime parameters attached to this path. They come in
217 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
218 /// this is more than just simple syntactic sugar; the use of
219 /// parens affects the region binding rules, so we preserve the
221 pub args: Option<&'hir GenericArgs<'hir>>,
223 /// Whether to infer remaining type parameters, if any.
224 /// This only applies to expression and pattern paths, and
225 /// out of those only the segments with no type parameters
226 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
227 pub infer_args: bool,
230 impl<'hir> PathSegment<'hir> {
231 /// Converts an identifier to the corresponding segment.
232 pub fn from_ident(ident: Ident) -> PathSegment<'hir> {
233 PathSegment { ident, hir_id: None, res: None, infer_args: true, args: None }
236 pub fn invalid() -> Self {
237 Self::from_ident(Ident::invalid())
240 pub fn args(&self) -> &GenericArgs<'hir> {
241 if let Some(ref args) = self.args {
244 const DUMMY: &GenericArgs<'_> = &GenericArgs::none();
250 #[derive(Encodable, Debug, HashStable_Generic)]
251 pub struct ConstArg {
252 pub value: AnonConst,
256 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
264 pub fn is_type(self) -> bool {
265 matches!(self, InferKind::Type)
269 #[derive(Encodable, Debug, HashStable_Generic)]
270 pub struct InferArg {
277 pub fn to_ty(&self) -> Ty<'_> {
278 Ty { kind: TyKind::Infer, span: self.span, hir_id: self.hir_id }
282 #[derive(Debug, HashStable_Generic)]
283 pub enum GenericArg<'hir> {
290 impl GenericArg<'_> {
291 pub fn span(&self) -> Span {
293 GenericArg::Lifetime(l) => l.span,
294 GenericArg::Type(t) => t.span,
295 GenericArg::Const(c) => c.span,
296 GenericArg::Infer(i) => i.span,
300 pub fn id(&self) -> HirId {
302 GenericArg::Lifetime(l) => l.hir_id,
303 GenericArg::Type(t) => t.hir_id,
304 GenericArg::Const(c) => c.value.hir_id,
305 GenericArg::Infer(i) => i.hir_id,
309 pub fn is_const(&self) -> bool {
310 matches!(self, GenericArg::Const(_))
313 pub fn is_synthetic(&self) -> bool {
314 matches!(self, GenericArg::Lifetime(lifetime) if lifetime.name.ident() == Ident::invalid())
317 pub fn descr(&self) -> &'static str {
319 GenericArg::Lifetime(_) => "lifetime",
320 GenericArg::Type(_) => "type",
321 GenericArg::Const(_) => "constant",
322 GenericArg::Infer(_) => "inferred",
326 pub fn to_ord(&self, feats: &rustc_feature::Features) -> ast::ParamKindOrd {
328 GenericArg::Lifetime(_) => ast::ParamKindOrd::Lifetime,
329 GenericArg::Type(_) => ast::ParamKindOrd::Type,
330 GenericArg::Const(_) => {
331 ast::ParamKindOrd::Const { unordered: feats.unordered_const_ty_params() }
333 GenericArg::Infer(_) => ast::ParamKindOrd::Infer,
338 #[derive(Debug, HashStable_Generic)]
339 pub struct GenericArgs<'hir> {
340 /// The generic arguments for this path segment.
341 pub args: &'hir [GenericArg<'hir>],
342 /// Bindings (equality constraints) on associated types, if present.
343 /// E.g., `Foo<A = Bar>`.
344 pub bindings: &'hir [TypeBinding<'hir>],
345 /// Were arguments written in parenthesized form `Fn(T) -> U`?
346 /// This is required mostly for pretty-printing and diagnostics,
347 /// but also for changing lifetime elision rules to be "function-like".
348 pub parenthesized: bool,
349 /// The span encompassing arguments and the surrounding brackets `<>` or `()`
350 /// Foo<A, B, AssocTy = D> Fn(T, U, V) -> W
351 /// ^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^
352 /// Note that this may be:
353 /// - empty, if there are no generic brackets (but there may be hidden lifetimes)
354 /// - dummy, if this was generated while desugaring
358 impl GenericArgs<'_> {
359 pub const fn none() -> Self {
360 Self { args: &[], bindings: &[], parenthesized: false, span_ext: DUMMY_SP }
363 pub fn inputs(&self) -> &[Ty<'_>] {
364 if self.parenthesized {
365 for arg in self.args {
367 GenericArg::Lifetime(_) => {}
368 GenericArg::Type(ref ty) => {
369 if let TyKind::Tup(ref tys) = ty.kind {
374 GenericArg::Const(_) => {}
375 GenericArg::Infer(_) => {}
379 panic!("GenericArgs::inputs: not a `Fn(T) -> U`");
383 pub fn has_type_params(&self) -> bool {
384 self.args.iter().any(|arg| matches!(arg, GenericArg::Type(_)))
388 pub fn num_type_params(&self) -> usize {
389 self.args.iter().filter(|arg| matches!(arg, GenericArg::Type(_))).count()
393 pub fn num_lifetime_params(&self) -> usize {
394 self.args.iter().filter(|arg| matches!(arg, GenericArg::Lifetime(_))).count()
398 pub fn has_lifetime_params(&self) -> bool {
399 self.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)))
403 pub fn num_generic_params(&self) -> usize {
404 self.args.iter().filter(|arg| !matches!(arg, GenericArg::Lifetime(_))).count()
407 /// The span encompassing the text inside the surrounding brackets.
408 /// It will also include bindings if they aren't in the form `-> Ret`
409 /// Returns `None` if the span is empty (e.g. no brackets) or dummy
410 pub fn span(&self) -> Option<Span> {
411 let span_ext = self.span_ext()?;
412 Some(span_ext.with_lo(span_ext.lo() + BytePos(1)).with_hi(span_ext.hi() - BytePos(1)))
415 /// Returns span encompassing arguments and their surrounding `<>` or `()`
416 pub fn span_ext(&self) -> Option<Span> {
417 Some(self.span_ext).filter(|span| !span.is_empty())
420 pub fn is_empty(&self) -> bool {
425 /// A modifier on a bound, currently this is only used for `?Sized`, where the
426 /// modifier is `Maybe`. Negative bounds should also be handled here.
427 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
428 #[derive(HashStable_Generic)]
429 pub enum TraitBoundModifier {
435 /// The AST represents all type param bounds as types.
436 /// `typeck::collect::compute_bounds` matches these against
437 /// the "special" built-in traits (see `middle::lang_items`) and
438 /// detects `Copy`, `Send` and `Sync`.
439 #[derive(Clone, Debug, HashStable_Generic)]
440 pub enum GenericBound<'hir> {
441 Trait(PolyTraitRef<'hir>, TraitBoundModifier),
442 // FIXME(davidtwco): Introduce `PolyTraitRef::LangItem`
443 LangItemTrait(LangItem, Span, HirId, &'hir GenericArgs<'hir>),
447 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
448 rustc_data_structures::static_assert_size!(GenericBound<'_>, 48);
450 impl GenericBound<'_> {
451 pub fn trait_ref(&self) -> Option<&TraitRef<'_>> {
453 GenericBound::Trait(data, _) => Some(&data.trait_ref),
458 pub fn span(&self) -> Span {
460 GenericBound::Trait(t, ..) => t.span,
461 GenericBound::LangItemTrait(_, span, ..) => *span,
462 GenericBound::Outlives(l) => l.span,
467 pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
469 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
470 pub enum LifetimeParamKind {
471 // Indicates that the lifetime definition was explicitly declared (e.g., in
472 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
475 // Indicates that the lifetime definition was synthetically added
476 // as a result of an in-band lifetime usage (e.g., in
477 // `fn foo(x: &'a u8) -> &'a u8 { x }`).
480 // Indication that the lifetime was elided (e.g., in both cases in
481 // `fn foo(x: &u8) -> &'_ u8 { x }`).
484 // Indication that the lifetime name was somehow in error.
488 #[derive(Debug, HashStable_Generic)]
489 pub enum GenericParamKind<'hir> {
490 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
492 kind: LifetimeParamKind,
495 default: Option<&'hir Ty<'hir>>,
496 synthetic: Option<SyntheticTyParamKind>,
500 /// Optional default value for the const generic param
501 default: Option<AnonConst>,
505 #[derive(Debug, HashStable_Generic)]
506 pub struct GenericParam<'hir> {
509 pub bounds: GenericBounds<'hir>,
511 pub pure_wrt_drop: bool,
512 pub kind: GenericParamKind<'hir>,
515 impl GenericParam<'hir> {
516 pub fn bounds_span(&self) -> Option<Span> {
517 self.bounds.iter().fold(None, |span, bound| {
518 let span = span.map(|s| s.to(bound.span())).unwrap_or_else(|| bound.span());
526 pub struct GenericParamCount {
527 pub lifetimes: usize,
533 /// Represents lifetimes and type parameters attached to a declaration
534 /// of a function, enum, trait, etc.
535 #[derive(Debug, HashStable_Generic)]
536 pub struct Generics<'hir> {
537 pub params: &'hir [GenericParam<'hir>],
538 pub where_clause: WhereClause<'hir>,
542 impl Generics<'hir> {
543 pub const fn empty() -> Generics<'hir> {
546 where_clause: WhereClause { predicates: &[], span: DUMMY_SP },
551 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'_>> {
552 for param in self.params {
553 if name == param.name.ident().name {
560 pub fn spans(&self) -> MultiSpan {
561 if self.params.is_empty() {
564 self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
569 /// Synthetic type parameters are converted to another form during lowering; this allows
570 /// us to track the original form they had, and is useful for error messages.
571 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
572 #[derive(HashStable_Generic)]
573 pub enum SyntheticTyParamKind {
575 // Created by the `#[rustc_synthetic]` attribute.
579 /// A where-clause in a definition.
580 #[derive(Debug, HashStable_Generic)]
581 pub struct WhereClause<'hir> {
582 pub predicates: &'hir [WherePredicate<'hir>],
583 // Only valid if predicates aren't empty.
587 impl WhereClause<'_> {
588 pub fn span(&self) -> Option<Span> {
589 if self.predicates.is_empty() { None } else { Some(self.span) }
592 /// The `WhereClause` under normal circumstances points at either the predicates or the empty
593 /// space where the `where` clause should be. Only of use for diagnostic suggestions.
594 pub fn span_for_predicates_or_empty_place(&self) -> Span {
598 /// `Span` where further predicates would be suggested, accounting for trailing commas, like
599 /// in `fn foo<T>(t: T) where T: Foo,` so we don't suggest two trailing commas.
600 pub fn tail_span_for_suggestion(&self) -> Span {
601 let end = self.span_for_predicates_or_empty_place().shrink_to_hi();
602 self.predicates.last().map_or(end, |p| p.span()).shrink_to_hi().to(end)
606 /// A single predicate in a where-clause.
607 #[derive(Debug, HashStable_Generic)]
608 pub enum WherePredicate<'hir> {
609 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
610 BoundPredicate(WhereBoundPredicate<'hir>),
611 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
612 RegionPredicate(WhereRegionPredicate<'hir>),
613 /// An equality predicate (unsupported).
614 EqPredicate(WhereEqPredicate<'hir>),
617 impl WherePredicate<'_> {
618 pub fn span(&self) -> Span {
620 WherePredicate::BoundPredicate(p) => p.span,
621 WherePredicate::RegionPredicate(p) => p.span,
622 WherePredicate::EqPredicate(p) => p.span,
627 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
628 #[derive(Debug, HashStable_Generic)]
629 pub struct WhereBoundPredicate<'hir> {
631 /// Any generics from a `for` binding.
632 pub bound_generic_params: &'hir [GenericParam<'hir>],
633 /// The type being bounded.
634 pub bounded_ty: &'hir Ty<'hir>,
635 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
636 pub bounds: GenericBounds<'hir>,
639 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
640 #[derive(Debug, HashStable_Generic)]
641 pub struct WhereRegionPredicate<'hir> {
643 pub lifetime: Lifetime,
644 pub bounds: GenericBounds<'hir>,
647 /// An equality predicate (e.g., `T = int`); currently unsupported.
648 #[derive(Debug, HashStable_Generic)]
649 pub struct WhereEqPredicate<'hir> {
652 pub lhs_ty: &'hir Ty<'hir>,
653 pub rhs_ty: &'hir Ty<'hir>,
656 /// The top-level data structure that stores the entire contents of
657 /// the crate currently being compiled.
659 /// For more details, see the [rustc dev guide].
661 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
663 pub struct Crate<'hir> {
664 pub owners: IndexVec<LocalDefId, Option<OwnerNode<'hir>>>,
665 pub bodies: BTreeMap<BodyId, Body<'hir>>,
667 /// Map indicating what traits are in scope for places where this
668 /// is relevant; generated by resolve.
669 pub trait_map: FxHashMap<LocalDefId, FxHashMap<ItemLocalId, Box<[TraitCandidate]>>>,
671 /// Collected attributes from HIR nodes.
672 pub attrs: BTreeMap<HirId, &'hir [Attribute]>,
676 pub fn module(&self) -> &'hir Mod<'hir> {
677 if let Some(OwnerNode::Crate(m)) = self.owners[CRATE_DEF_ID] { m } else { panic!() }
680 pub fn item(&self, id: ItemId) -> &'hir Item<'hir> {
681 self.owners[id.def_id].as_ref().unwrap().expect_item()
684 pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> {
685 self.owners[id.def_id].as_ref().unwrap().expect_trait_item()
688 pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> {
689 self.owners[id.def_id].as_ref().unwrap().expect_impl_item()
692 pub fn foreign_item(&self, id: ForeignItemId) -> &'hir ForeignItem<'hir> {
693 self.owners[id.def_id].as_ref().unwrap().expect_foreign_item()
696 pub fn body(&self, id: BodyId) -> &Body<'hir> {
702 /// Visits all items in the crate in some deterministic (but
703 /// unspecified) order. If you just need to process every item,
704 /// but don't care about nesting, this method is the best choice.
706 /// If you do care about nesting -- usually because your algorithm
707 /// follows lexical scoping rules -- then you want a different
708 /// approach. You should override `visit_nested_item` in your
709 /// visitor and then call `intravisit::walk_crate` instead.
710 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
712 V: itemlikevisit::ItemLikeVisitor<'hir>,
714 for owner in self.owners.iter().filter_map(Option::as_ref) {
716 OwnerNode::Item(item) => visitor.visit_item(item),
717 OwnerNode::ForeignItem(item) => visitor.visit_foreign_item(item),
718 OwnerNode::ImplItem(item) => visitor.visit_impl_item(item),
719 OwnerNode::TraitItem(item) => visitor.visit_trait_item(item),
720 OwnerNode::Crate(_) => {}
725 /// A parallel version of `visit_all_item_likes`.
726 pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
728 V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send,
730 par_for_each_in(&self.owners.raw, |owner| match owner {
731 Some(OwnerNode::Item(item)) => visitor.visit_item(item),
732 Some(OwnerNode::ForeignItem(item)) => visitor.visit_foreign_item(item),
733 Some(OwnerNode::ImplItem(item)) => visitor.visit_impl_item(item),
734 Some(OwnerNode::TraitItem(item)) => visitor.visit_trait_item(item),
735 Some(OwnerNode::Crate(_)) | None => {}
739 pub fn items<'hir>(&'hir self) -> impl Iterator<Item = &'hir Item<'hir>> + 'hir {
740 self.owners.iter().filter_map(|owner| match owner {
741 Some(OwnerNode::Item(item)) => Some(*item),
747 /// A block of statements `{ .. }`, which may have a label (in this case the
748 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
749 /// the `rules` being anything but `DefaultBlock`.
750 #[derive(Debug, HashStable_Generic)]
751 pub struct Block<'hir> {
752 /// Statements in a block.
753 pub stmts: &'hir [Stmt<'hir>],
754 /// An expression at the end of the block
755 /// without a semicolon, if any.
756 pub expr: Option<&'hir Expr<'hir>>,
757 #[stable_hasher(ignore)]
759 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
760 pub rules: BlockCheckMode,
762 /// If true, then there may exist `break 'a` values that aim to
763 /// break out of this block early.
764 /// Used by `'label: {}` blocks and by `try {}` blocks.
765 pub targeted_by_break: bool,
768 #[derive(Debug, HashStable_Generic)]
769 pub struct Pat<'hir> {
770 #[stable_hasher(ignore)]
772 pub kind: PatKind<'hir>,
774 // Whether to use default binding modes.
775 // At present, this is false only for destructuring assignment.
776 pub default_binding_modes: bool,
779 impl<'hir> Pat<'hir> {
780 // FIXME(#19596) this is a workaround, but there should be a better way
781 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) -> bool {
788 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
789 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
790 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
791 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
792 Slice(before, slice, after) => {
793 before.iter().chain(slice).chain(after.iter()).all(|p| p.walk_short_(it))
798 /// Walk the pattern in left-to-right order,
799 /// short circuiting (with `.all(..)`) if `false` is returned.
801 /// Note that when visiting e.g. `Tuple(ps)`,
802 /// if visiting `ps[0]` returns `false`,
803 /// then `ps[1]` will not be visited.
804 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) -> bool {
805 self.walk_short_(&mut it)
808 // FIXME(#19596) this is a workaround, but there should be a better way
809 fn walk_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) {
816 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
817 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
818 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
819 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
820 Slice(before, slice, after) => {
821 before.iter().chain(slice).chain(after.iter()).for_each(|p| p.walk_(it))
826 /// Walk the pattern in left-to-right order.
828 /// If `it(pat)` returns `false`, the children are not visited.
829 pub fn walk(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) {
833 /// Walk the pattern in left-to-right order.
835 /// If you always want to recurse, prefer this method over `walk`.
836 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
844 /// A single field in a struct pattern.
846 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
847 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
848 /// except `is_shorthand` is true.
849 #[derive(Debug, HashStable_Generic)]
850 pub struct PatField<'hir> {
851 #[stable_hasher(ignore)]
853 /// The identifier for the field.
854 #[stable_hasher(project(name))]
856 /// The pattern the field is destructured to.
857 pub pat: &'hir Pat<'hir>,
858 pub is_shorthand: bool,
862 /// Explicit binding annotations given in the HIR for a binding. Note
863 /// that this is not the final binding *mode* that we infer after type
865 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
866 pub enum BindingAnnotation {
867 /// No binding annotation given: this means that the final binding mode
868 /// will depend on whether we have skipped through a `&` reference
869 /// when matching. For example, the `x` in `Some(x)` will have binding
870 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
871 /// ultimately be inferred to be by-reference.
873 /// Note that implicit reference skipping is not implemented yet (#42640).
876 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
879 /// Annotated as `ref`, like `ref x`
882 /// Annotated as `ref mut x`.
886 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
892 impl fmt::Display for RangeEnd {
893 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
894 f.write_str(match self {
895 RangeEnd::Included => "..=",
896 RangeEnd::Excluded => "..",
901 #[derive(Debug, HashStable_Generic)]
902 pub enum PatKind<'hir> {
903 /// Represents a wildcard pattern (i.e., `_`).
906 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
907 /// The `HirId` is the canonical ID for the variable being bound,
908 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
909 /// which is the pattern ID of the first `x`.
910 Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
912 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
913 /// The `bool` is `true` in the presence of a `..`.
914 Struct(QPath<'hir>, &'hir [PatField<'hir>], bool),
916 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
917 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
918 /// `0 <= position <= subpats.len()`
919 TupleStruct(QPath<'hir>, &'hir [Pat<'hir>], Option<usize>),
921 /// An or-pattern `A | B | C`.
922 /// Invariant: `pats.len() >= 2`.
923 Or(&'hir [Pat<'hir>]),
925 /// A path pattern for a unit struct/variant or a (maybe-associated) constant.
928 /// A tuple pattern (e.g., `(a, b)`).
929 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
930 /// `0 <= position <= subpats.len()`
931 Tuple(&'hir [Pat<'hir>], Option<usize>),
934 Box(&'hir Pat<'hir>),
936 /// A reference pattern (e.g., `&mut (a, b)`).
937 Ref(&'hir Pat<'hir>, Mutability),
940 Lit(&'hir Expr<'hir>),
942 /// A range pattern (e.g., `1..=2` or `1..2`).
943 Range(Option<&'hir Expr<'hir>>, Option<&'hir Expr<'hir>>, RangeEnd),
945 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
947 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
948 /// If `slice` exists, then `after` can be non-empty.
950 /// The representation for e.g., `[a, b, .., c, d]` is:
952 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
954 Slice(&'hir [Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [Pat<'hir>]),
957 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
959 /// The `+` operator (addition).
961 /// The `-` operator (subtraction).
963 /// The `*` operator (multiplication).
965 /// The `/` operator (division).
967 /// The `%` operator (modulus).
969 /// The `&&` operator (logical and).
971 /// The `||` operator (logical or).
973 /// The `^` operator (bitwise xor).
975 /// The `&` operator (bitwise and).
977 /// The `|` operator (bitwise or).
979 /// The `<<` operator (shift left).
981 /// The `>>` operator (shift right).
983 /// The `==` operator (equality).
985 /// The `<` operator (less than).
987 /// The `<=` operator (less than or equal to).
989 /// The `!=` operator (not equal to).
991 /// The `>=` operator (greater than or equal to).
993 /// The `>` operator (greater than).
998 pub fn as_str(self) -> &'static str {
1000 BinOpKind::Add => "+",
1001 BinOpKind::Sub => "-",
1002 BinOpKind::Mul => "*",
1003 BinOpKind::Div => "/",
1004 BinOpKind::Rem => "%",
1005 BinOpKind::And => "&&",
1006 BinOpKind::Or => "||",
1007 BinOpKind::BitXor => "^",
1008 BinOpKind::BitAnd => "&",
1009 BinOpKind::BitOr => "|",
1010 BinOpKind::Shl => "<<",
1011 BinOpKind::Shr => ">>",
1012 BinOpKind::Eq => "==",
1013 BinOpKind::Lt => "<",
1014 BinOpKind::Le => "<=",
1015 BinOpKind::Ne => "!=",
1016 BinOpKind::Ge => ">=",
1017 BinOpKind::Gt => ">",
1021 pub fn is_lazy(self) -> bool {
1022 matches!(self, BinOpKind::And | BinOpKind::Or)
1025 pub fn is_shift(self) -> bool {
1026 matches!(self, BinOpKind::Shl | BinOpKind::Shr)
1029 pub fn is_comparison(self) -> bool {
1036 | BinOpKind::Ge => true,
1048 | BinOpKind::Shr => false,
1052 /// Returns `true` if the binary operator takes its arguments by value.
1053 pub fn is_by_value(self) -> bool {
1054 !self.is_comparison()
1058 impl Into<ast::BinOpKind> for BinOpKind {
1059 fn into(self) -> ast::BinOpKind {
1061 BinOpKind::Add => ast::BinOpKind::Add,
1062 BinOpKind::Sub => ast::BinOpKind::Sub,
1063 BinOpKind::Mul => ast::BinOpKind::Mul,
1064 BinOpKind::Div => ast::BinOpKind::Div,
1065 BinOpKind::Rem => ast::BinOpKind::Rem,
1066 BinOpKind::And => ast::BinOpKind::And,
1067 BinOpKind::Or => ast::BinOpKind::Or,
1068 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1069 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1070 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1071 BinOpKind::Shl => ast::BinOpKind::Shl,
1072 BinOpKind::Shr => ast::BinOpKind::Shr,
1073 BinOpKind::Eq => ast::BinOpKind::Eq,
1074 BinOpKind::Lt => ast::BinOpKind::Lt,
1075 BinOpKind::Le => ast::BinOpKind::Le,
1076 BinOpKind::Ne => ast::BinOpKind::Ne,
1077 BinOpKind::Ge => ast::BinOpKind::Ge,
1078 BinOpKind::Gt => ast::BinOpKind::Gt,
1083 pub type BinOp = Spanned<BinOpKind>;
1085 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1087 /// The `*` operator (deferencing).
1089 /// The `!` operator (logical negation).
1091 /// The `-` operator (negation).
1096 pub fn as_str(self) -> &'static str {
1104 /// Returns `true` if the unary operator takes its argument by value.
1105 pub fn is_by_value(self) -> bool {
1106 matches!(self, Self::Neg | Self::Not)
1111 #[derive(Debug, HashStable_Generic)]
1112 pub struct Stmt<'hir> {
1114 pub kind: StmtKind<'hir>,
1118 /// The contents of a statement.
1119 #[derive(Debug, HashStable_Generic)]
1120 pub enum StmtKind<'hir> {
1121 /// A local (`let`) binding.
1122 Local(&'hir Local<'hir>),
1124 /// An item binding.
1127 /// An expression without a trailing semi-colon (must have unit type).
1128 Expr(&'hir Expr<'hir>),
1130 /// An expression with a trailing semi-colon (may have any type).
1131 Semi(&'hir Expr<'hir>),
1134 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1135 #[derive(Debug, HashStable_Generic)]
1136 pub struct Local<'hir> {
1137 pub pat: &'hir Pat<'hir>,
1138 /// Type annotation, if any (otherwise the type will be inferred).
1139 pub ty: Option<&'hir Ty<'hir>>,
1140 /// Initializer expression to set the value, if any.
1141 pub init: Option<&'hir Expr<'hir>>,
1144 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1145 /// desugaring. Otherwise will be `Normal`.
1146 pub source: LocalSource,
1149 /// Represents a single arm of a `match` expression, e.g.
1150 /// `<pat> (if <guard>) => <body>`.
1151 #[derive(Debug, HashStable_Generic)]
1152 pub struct Arm<'hir> {
1153 #[stable_hasher(ignore)]
1156 /// If this pattern and the optional guard matches, then `body` is evaluated.
1157 pub pat: &'hir Pat<'hir>,
1158 /// Optional guard clause.
1159 pub guard: Option<Guard<'hir>>,
1160 /// The expression the arm evaluates to if this arm matches.
1161 pub body: &'hir Expr<'hir>,
1164 #[derive(Debug, HashStable_Generic)]
1165 pub enum Guard<'hir> {
1166 If(&'hir Expr<'hir>),
1167 // FIXME use ExprKind::Let for this.
1168 IfLet(&'hir Pat<'hir>, &'hir Expr<'hir>),
1171 #[derive(Debug, HashStable_Generic)]
1172 pub struct ExprField<'hir> {
1173 #[stable_hasher(ignore)]
1176 pub expr: &'hir Expr<'hir>,
1178 pub is_shorthand: bool,
1181 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1182 pub enum BlockCheckMode {
1184 UnsafeBlock(UnsafeSource),
1187 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1188 pub enum UnsafeSource {
1193 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Hash, Debug)]
1198 /// The body of a function, closure, or constant value. In the case of
1199 /// a function, the body contains not only the function body itself
1200 /// (which is an expression), but also the argument patterns, since
1201 /// those are something that the caller doesn't really care about.
1206 /// fn foo((x, y): (u32, u32)) -> u32 {
1211 /// Here, the `Body` associated with `foo()` would contain:
1213 /// - an `params` array containing the `(x, y)` pattern
1214 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1215 /// - `generator_kind` would be `None`
1217 /// All bodies have an **owner**, which can be accessed via the HIR
1218 /// map using `body_owner_def_id()`.
1220 pub struct Body<'hir> {
1221 pub params: &'hir [Param<'hir>],
1222 pub value: Expr<'hir>,
1223 pub generator_kind: Option<GeneratorKind>,
1227 pub fn id(&self) -> BodyId {
1228 BodyId { hir_id: self.value.hir_id }
1231 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1236 /// The type of source expression that caused this generator to be created.
1249 pub enum GeneratorKind {
1250 /// An explicit `async` block or the body of an async function.
1251 Async(AsyncGeneratorKind),
1253 /// A generator literal created via a `yield` inside a closure.
1257 impl fmt::Display for GeneratorKind {
1258 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1260 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1261 GeneratorKind::Gen => f.write_str("generator"),
1266 impl GeneratorKind {
1267 pub fn descr(&self) -> &'static str {
1269 GeneratorKind::Async(ask) => ask.descr(),
1270 GeneratorKind::Gen => "generator",
1275 /// In the case of a generator created as part of an async construct,
1276 /// which kind of async construct caused it to be created?
1278 /// This helps error messages but is also used to drive coercions in
1279 /// type-checking (see #60424).
1292 pub enum AsyncGeneratorKind {
1293 /// An explicit `async` block written by the user.
1296 /// An explicit `async` block written by the user.
1299 /// The `async` block generated as the body of an async function.
1303 impl fmt::Display for AsyncGeneratorKind {
1304 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1305 f.write_str(match self {
1306 AsyncGeneratorKind::Block => "`async` block",
1307 AsyncGeneratorKind::Closure => "`async` closure body",
1308 AsyncGeneratorKind::Fn => "`async fn` body",
1313 impl AsyncGeneratorKind {
1314 pub fn descr(&self) -> &'static str {
1316 AsyncGeneratorKind::Block => "`async` block",
1317 AsyncGeneratorKind::Closure => "`async` closure body",
1318 AsyncGeneratorKind::Fn => "`async fn` body",
1323 #[derive(Copy, Clone, Debug)]
1324 pub enum BodyOwnerKind {
1325 /// Functions and methods.
1331 /// Constants and associated constants.
1334 /// Initializer of a `static` item.
1338 impl BodyOwnerKind {
1339 pub fn is_fn_or_closure(self) -> bool {
1341 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1342 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1347 /// The kind of an item that requires const-checking.
1348 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1349 pub enum ConstContext {
1353 /// A `static` or `static mut`.
1356 /// A `const`, associated `const`, or other const context.
1358 /// Other contexts include:
1359 /// - Array length expressions
1360 /// - Enum discriminants
1361 /// - Const generics
1363 /// For the most part, other contexts are treated just like a regular `const`, so they are
1364 /// lumped into the same category.
1369 /// A description of this const context that can appear between backticks in an error message.
1371 /// E.g. `const` or `static mut`.
1372 pub fn keyword_name(self) -> &'static str {
1374 Self::Const => "const",
1375 Self::Static(Mutability::Not) => "static",
1376 Self::Static(Mutability::Mut) => "static mut",
1377 Self::ConstFn => "const fn",
1382 /// A colloquial, trivially pluralizable description of this const context for use in error
1384 impl fmt::Display for ConstContext {
1385 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1387 Self::Const => write!(f, "constant"),
1388 Self::Static(_) => write!(f, "static"),
1389 Self::ConstFn => write!(f, "constant function"),
1395 pub type Lit = Spanned<LitKind>;
1397 /// A constant (expression) that's not an item or associated item,
1398 /// but needs its own `DefId` for type-checking, const-eval, etc.
1399 /// These are usually found nested inside types (e.g., array lengths)
1400 /// or expressions (e.g., repeat counts), and also used to define
1401 /// explicit discriminant values for enum variants.
1403 /// You can check if this anon const is a default in a const param
1404 /// `const N: usize = { ... }` with `tcx.hir().opt_const_param_default_param_hir_id(..)`
1405 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1406 pub struct AnonConst {
1413 pub struct Expr<'hir> {
1415 pub kind: ExprKind<'hir>,
1420 pub fn precedence(&self) -> ExprPrecedence {
1422 ExprKind::Box(_) => ExprPrecedence::Box,
1423 ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1424 ExprKind::Array(_) => ExprPrecedence::Array,
1425 ExprKind::Call(..) => ExprPrecedence::Call,
1426 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1427 ExprKind::Tup(_) => ExprPrecedence::Tup,
1428 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1429 ExprKind::Unary(..) => ExprPrecedence::Unary,
1430 ExprKind::Lit(_) => ExprPrecedence::Lit,
1431 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1432 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1433 ExprKind::If(..) => ExprPrecedence::If,
1434 ExprKind::Let(..) => ExprPrecedence::Let,
1435 ExprKind::Loop(..) => ExprPrecedence::Loop,
1436 ExprKind::Match(..) => ExprPrecedence::Match,
1437 ExprKind::Closure(..) => ExprPrecedence::Closure,
1438 ExprKind::Block(..) => ExprPrecedence::Block,
1439 ExprKind::Assign(..) => ExprPrecedence::Assign,
1440 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1441 ExprKind::Field(..) => ExprPrecedence::Field,
1442 ExprKind::Index(..) => ExprPrecedence::Index,
1443 ExprKind::Path(..) => ExprPrecedence::Path,
1444 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1445 ExprKind::Break(..) => ExprPrecedence::Break,
1446 ExprKind::Continue(..) => ExprPrecedence::Continue,
1447 ExprKind::Ret(..) => ExprPrecedence::Ret,
1448 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1449 ExprKind::LlvmInlineAsm(..) => ExprPrecedence::InlineAsm,
1450 ExprKind::Struct(..) => ExprPrecedence::Struct,
1451 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1452 ExprKind::Yield(..) => ExprPrecedence::Yield,
1453 ExprKind::Err => ExprPrecedence::Err,
1457 // Whether this looks like a place expr, without checking for deref
1459 // This will return `true` in some potentially surprising cases such as
1460 // `CONSTANT.field`.
1461 pub fn is_syntactic_place_expr(&self) -> bool {
1462 self.is_place_expr(|_| true)
1465 /// Whether this is a place expression.
1467 /// `allow_projections_from` should return `true` if indexing a field or index expression based
1468 /// on the given expression should be considered a place expression.
1469 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1471 ExprKind::Path(QPath::Resolved(_, ref path)) => {
1472 matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static, _) | Res::Err)
1475 // Type ascription inherits its place expression kind from its
1477 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1478 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1480 ExprKind::Unary(UnOp::Deref, _) => true,
1482 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1483 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1486 // Lang item paths cannot currently be local variables or statics.
1487 ExprKind::Path(QPath::LangItem(..)) => false,
1489 // Partially qualified paths in expressions can only legally
1490 // refer to associated items which are always rvalues.
1491 ExprKind::Path(QPath::TypeRelative(..))
1492 | ExprKind::Call(..)
1493 | ExprKind::MethodCall(..)
1494 | ExprKind::Struct(..)
1497 | ExprKind::Match(..)
1498 | ExprKind::Closure(..)
1499 | ExprKind::Block(..)
1500 | ExprKind::Repeat(..)
1501 | ExprKind::Array(..)
1502 | ExprKind::Break(..)
1503 | ExprKind::Continue(..)
1506 | ExprKind::Loop(..)
1507 | ExprKind::Assign(..)
1508 | ExprKind::InlineAsm(..)
1509 | ExprKind::LlvmInlineAsm(..)
1510 | ExprKind::AssignOp(..)
1512 | ExprKind::ConstBlock(..)
1513 | ExprKind::Unary(..)
1515 | ExprKind::AddrOf(..)
1516 | ExprKind::Binary(..)
1517 | ExprKind::Yield(..)
1518 | ExprKind::Cast(..)
1519 | ExprKind::DropTemps(..)
1520 | ExprKind::Err => false,
1524 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1525 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1526 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1527 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1528 /// beyond remembering to call this function before doing analysis on it.
1529 pub fn peel_drop_temps(&self) -> &Self {
1530 let mut expr = self;
1531 while let ExprKind::DropTemps(inner) = &expr.kind {
1537 pub fn peel_blocks(&self) -> &Self {
1538 let mut expr = self;
1539 while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind {
1545 pub fn can_have_side_effects(&self) -> bool {
1546 match self.peel_drop_temps().kind {
1547 ExprKind::Path(_) | ExprKind::Lit(_) => false,
1548 ExprKind::Type(base, _)
1549 | ExprKind::Unary(_, base)
1550 | ExprKind::Field(base, _)
1551 | ExprKind::Index(base, _)
1552 | ExprKind::AddrOf(.., base)
1553 | ExprKind::Cast(base, _) => {
1554 // This isn't exactly true for `Index` and all `Unnary`, but we are using this
1555 // method exclusively for diagnostics and there's a *cultural* pressure against
1556 // them being used only for its side-effects.
1557 base.can_have_side_effects()
1559 ExprKind::Struct(_, fields, init) => fields
1561 .map(|field| field.expr)
1562 .chain(init.into_iter())
1563 .all(|e| e.can_have_side_effects()),
1565 ExprKind::Array(args)
1566 | ExprKind::Tup(args)
1570 ExprKind::Path(QPath::Resolved(
1572 Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. },
1577 ) => args.iter().all(|arg| arg.can_have_side_effects()),
1579 | ExprKind::Match(..)
1580 | ExprKind::MethodCall(..)
1581 | ExprKind::Call(..)
1582 | ExprKind::Closure(..)
1583 | ExprKind::Block(..)
1584 | ExprKind::Repeat(..)
1585 | ExprKind::Break(..)
1586 | ExprKind::Continue(..)
1589 | ExprKind::Loop(..)
1590 | ExprKind::Assign(..)
1591 | ExprKind::InlineAsm(..)
1592 | ExprKind::LlvmInlineAsm(..)
1593 | ExprKind::AssignOp(..)
1594 | ExprKind::ConstBlock(..)
1596 | ExprKind::Binary(..)
1597 | ExprKind::Yield(..)
1598 | ExprKind::DropTemps(..)
1599 | ExprKind::Err => true,
1604 /// Checks if the specified expression is a built-in range literal.
1605 /// (See: `LoweringContext::lower_expr()`).
1606 pub fn is_range_literal(expr: &Expr<'_>) -> bool {
1608 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1609 ExprKind::Struct(ref qpath, _, _) => matches!(
1614 | LangItem::RangeFrom
1615 | LangItem::RangeFull
1616 | LangItem::RangeToInclusive,
1621 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1622 ExprKind::Call(ref func, _) => {
1623 matches!(func.kind, ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, _)))
1630 #[derive(Debug, HashStable_Generic)]
1631 pub enum ExprKind<'hir> {
1632 /// A `box x` expression.
1633 Box(&'hir Expr<'hir>),
1634 /// Allow anonymous constants from an inline `const` block
1635 ConstBlock(AnonConst),
1636 /// An array (e.g., `[a, b, c, d]`).
1637 Array(&'hir [Expr<'hir>]),
1638 /// A function call.
1640 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1641 /// and the second field is the list of arguments.
1642 /// This also represents calling the constructor of
1643 /// tuple-like ADTs such as tuple structs and enum variants.
1644 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1645 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1647 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1648 /// (within the angle brackets).
1649 /// The first element of the vector of `Expr`s is the expression that evaluates
1650 /// to the object on which the method is being called on (the receiver),
1651 /// and the remaining elements are the rest of the arguments.
1652 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1653 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1654 /// The final `Span` represents the span of the function and arguments
1655 /// (e.g. `foo::<Bar, Baz>(a, b, c, d)` in `x.foo::<Bar, Baz>(a, b, c, d)`
1657 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1658 /// the `hir_id` of the `MethodCall` node itself.
1660 /// [`type_dependent_def_id`]: ../ty/struct.TypeckResults.html#method.type_dependent_def_id
1661 MethodCall(&'hir PathSegment<'hir>, Span, &'hir [Expr<'hir>], Span),
1662 /// A tuple (e.g., `(a, b, c, d)`).
1663 Tup(&'hir [Expr<'hir>]),
1664 /// A binary operation (e.g., `a + b`, `a * b`).
1665 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1666 /// A unary operation (e.g., `!x`, `*x`).
1667 Unary(UnOp, &'hir Expr<'hir>),
1668 /// A literal (e.g., `1`, `"foo"`).
1670 /// A cast (e.g., `foo as f64`).
1671 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1672 /// A type reference (e.g., `Foo`).
1673 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1674 /// Wraps the expression in a terminating scope.
1675 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1677 /// This construct only exists to tweak the drop order in HIR lowering.
1678 /// An example of that is the desugaring of `for` loops.
1679 DropTemps(&'hir Expr<'hir>),
1680 /// A `let $pat = $expr` expression.
1682 /// These are not `Local` and only occur as expressions.
1683 /// The `let Some(x) = foo()` in `if let Some(x) = foo()` is an example of `Let(..)`.
1684 Let(&'hir Pat<'hir>, &'hir Expr<'hir>, Span),
1685 /// An `if` block, with an optional else block.
1687 /// I.e., `if <expr> { <expr> } else { <expr> }`.
1688 If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
1689 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1691 /// I.e., `'label: loop { <block> }`.
1693 /// The `Span` is the loop header (`for x in y`/`while let pat = expr`).
1694 Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span),
1695 /// A `match` block, with a source that indicates whether or not it is
1696 /// the result of a desugaring, and if so, which kind.
1697 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1698 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1700 /// The `Span` is the argument block `|...|`.
1702 /// This may also be a generator literal or an `async block` as indicated by the
1703 /// `Option<Movability>`.
1704 Closure(CaptureBy, &'hir FnDecl<'hir>, BodyId, Span, Option<Movability>),
1705 /// A block (e.g., `'label: { ... }`).
1706 Block(&'hir Block<'hir>, Option<Label>),
1708 /// An assignment (e.g., `a = foo()`).
1709 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1710 /// An assignment with an operator.
1713 AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1714 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1715 Field(&'hir Expr<'hir>, Ident),
1716 /// An indexing operation (`foo[2]`).
1717 Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1719 /// Path to a definition, possibly containing lifetime or type parameters.
1722 /// A referencing operation (i.e., `&a` or `&mut a`).
1723 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1724 /// A `break`, with an optional label to break.
1725 Break(Destination, Option<&'hir Expr<'hir>>),
1726 /// A `continue`, with an optional label.
1727 Continue(Destination),
1728 /// A `return`, with an optional value to be returned.
1729 Ret(Option<&'hir Expr<'hir>>),
1731 /// Inline assembly (from `asm!`), with its outputs and inputs.
1732 InlineAsm(&'hir InlineAsm<'hir>),
1733 /// Inline assembly (from `llvm_asm!`), with its outputs and inputs.
1734 LlvmInlineAsm(&'hir LlvmInlineAsm<'hir>),
1736 /// A struct or struct-like variant literal expression.
1738 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1739 /// where `base` is the `Option<Expr>`.
1740 Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], Option<&'hir Expr<'hir>>),
1742 /// An array literal constructed from one repeated element.
1744 /// E.g., `[1; 5]`. The first expression is the element
1745 /// to be repeated; the second is the number of times to repeat it.
1746 Repeat(&'hir Expr<'hir>, AnonConst),
1748 /// A suspension point for generators (i.e., `yield <expr>`).
1749 Yield(&'hir Expr<'hir>, YieldSource),
1751 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1755 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1757 /// To resolve the path to a `DefId`, call [`qpath_res`].
1759 /// [`qpath_res`]: ../rustc_middle/ty/struct.TypeckResults.html#method.qpath_res
1760 #[derive(Debug, HashStable_Generic)]
1761 pub enum QPath<'hir> {
1762 /// Path to a definition, optionally "fully-qualified" with a `Self`
1763 /// type, if the path points to an associated item in a trait.
1765 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1766 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1767 /// even though they both have the same two-segment `Clone::clone` `Path`.
1768 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
1770 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1771 /// Will be resolved by type-checking to an associated item.
1773 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1774 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1775 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1776 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
1778 /// Reference to a `#[lang = "foo"]` item.
1779 LangItem(LangItem, Span),
1782 impl<'hir> QPath<'hir> {
1783 /// Returns the span of this `QPath`.
1784 pub fn span(&self) -> Span {
1786 QPath::Resolved(_, path) => path.span,
1787 QPath::TypeRelative(qself, ps) => qself.span.to(ps.ident.span),
1788 QPath::LangItem(_, span) => span,
1792 /// Returns the span of the qself of this `QPath`. For example, `()` in
1793 /// `<() as Trait>::method`.
1794 pub fn qself_span(&self) -> Span {
1796 QPath::Resolved(_, path) => path.span,
1797 QPath::TypeRelative(qself, _) => qself.span,
1798 QPath::LangItem(_, span) => span,
1802 /// Returns the span of the last segment of this `QPath`. For example, `method` in
1803 /// `<() as Trait>::method`.
1804 pub fn last_segment_span(&self) -> Span {
1806 QPath::Resolved(_, path) => path.segments.last().unwrap().ident.span,
1807 QPath::TypeRelative(_, segment) => segment.ident.span,
1808 QPath::LangItem(_, span) => span,
1813 /// Hints at the original code for a let statement.
1814 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1815 pub enum LocalSource {
1816 /// A `match _ { .. }`.
1818 /// A desugared `for _ in _ { .. }` loop.
1820 /// When lowering async functions, we create locals within the `async move` so that
1821 /// all parameters are dropped after the future is polled.
1823 /// ```ignore (pseudo-Rust)
1824 /// async fn foo(<pattern> @ x: Type) {
1826 /// let <pattern> = x;
1831 /// A desugared `<expr>.await`.
1833 /// A desugared `expr = expr`, where the LHS is a tuple, struct or array.
1834 /// The span is that of the `=` sign.
1835 AssignDesugar(Span),
1838 /// Hints at the original code for a `match _ { .. }`.
1839 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
1840 #[derive(HashStable_Generic)]
1841 pub enum MatchSource {
1842 /// A `match _ { .. }`.
1844 /// A desugared `for _ in _ { .. }` loop.
1846 /// A desugared `?` operator.
1848 /// A desugared `<expr>.await`.
1854 pub const fn name(self) -> &'static str {
1858 ForLoopDesugar => "for",
1860 AwaitDesugar => ".await",
1865 /// The loop type that yielded an `ExprKind::Loop`.
1866 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1867 pub enum LoopSource {
1868 /// A `loop { .. }` loop.
1870 /// A `while _ { .. }` loop.
1872 /// A `for _ in _ { .. }` loop.
1877 pub fn name(self) -> &'static str {
1879 LoopSource::Loop => "loop",
1880 LoopSource::While => "while",
1881 LoopSource::ForLoop => "for",
1886 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1887 pub enum LoopIdError {
1889 UnlabeledCfInWhileCondition,
1893 impl fmt::Display for LoopIdError {
1894 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1895 f.write_str(match self {
1896 LoopIdError::OutsideLoopScope => "not inside loop scope",
1897 LoopIdError::UnlabeledCfInWhileCondition => {
1898 "unlabeled control flow (break or continue) in while condition"
1900 LoopIdError::UnresolvedLabel => "label not found",
1905 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1906 pub struct Destination {
1907 // This is `Some(_)` iff there is an explicit user-specified `label
1908 pub label: Option<Label>,
1910 // These errors are caught and then reported during the diagnostics pass in
1911 // librustc_passes/loops.rs
1912 pub target_id: Result<HirId, LoopIdError>,
1915 /// The yield kind that caused an `ExprKind::Yield`.
1916 #[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
1917 pub enum YieldSource {
1918 /// An `<expr>.await`.
1919 Await { expr: Option<HirId> },
1920 /// A plain `yield`.
1925 pub fn is_await(&self) -> bool {
1927 YieldSource::Await { .. } => true,
1928 YieldSource::Yield => false,
1933 impl fmt::Display for YieldSource {
1934 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1935 f.write_str(match self {
1936 YieldSource::Await { .. } => "`await`",
1937 YieldSource::Yield => "`yield`",
1942 impl From<GeneratorKind> for YieldSource {
1943 fn from(kind: GeneratorKind) -> Self {
1945 // Guess based on the kind of the current generator.
1946 GeneratorKind::Gen => Self::Yield,
1947 GeneratorKind::Async(_) => Self::Await { expr: None },
1952 // N.B., if you change this, you'll probably want to change the corresponding
1953 // type structure in middle/ty.rs as well.
1954 #[derive(Debug, HashStable_Generic)]
1955 pub struct MutTy<'hir> {
1956 pub ty: &'hir Ty<'hir>,
1957 pub mutbl: Mutability,
1960 /// Represents a function's signature in a trait declaration,
1961 /// trait implementation, or a free function.
1962 #[derive(Debug, HashStable_Generic)]
1963 pub struct FnSig<'hir> {
1964 pub header: FnHeader,
1965 pub decl: &'hir FnDecl<'hir>,
1969 // The bodies for items are stored "out of line", in a separate
1970 // hashmap in the `Crate`. Here we just record the hir-id of the item
1971 // so it can fetched later.
1972 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
1973 pub struct TraitItemId {
1974 pub def_id: LocalDefId,
1979 pub fn hir_id(&self) -> HirId {
1980 // Items are always HIR owners.
1981 HirId::make_owner(self.def_id)
1985 /// Represents an item declaration within a trait declaration,
1986 /// possibly including a default implementation. A trait item is
1987 /// either required (meaning it doesn't have an implementation, just a
1988 /// signature) or provided (meaning it has a default implementation).
1990 pub struct TraitItem<'hir> {
1992 pub def_id: LocalDefId,
1993 pub generics: Generics<'hir>,
1994 pub kind: TraitItemKind<'hir>,
1998 impl TraitItem<'_> {
2000 pub fn hir_id(&self) -> HirId {
2001 // Items are always HIR owners.
2002 HirId::make_owner(self.def_id)
2005 pub fn trait_item_id(&self) -> TraitItemId {
2006 TraitItemId { def_id: self.def_id }
2010 /// Represents a trait method's body (or just argument names).
2011 #[derive(Encodable, Debug, HashStable_Generic)]
2012 pub enum TraitFn<'hir> {
2013 /// No default body in the trait, just a signature.
2014 Required(&'hir [Ident]),
2016 /// Both signature and body are provided in the trait.
2020 /// Represents a trait method or associated constant or type
2021 #[derive(Debug, HashStable_Generic)]
2022 pub enum TraitItemKind<'hir> {
2023 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
2024 Const(&'hir Ty<'hir>, Option<BodyId>),
2025 /// An associated function with an optional body.
2026 Fn(FnSig<'hir>, TraitFn<'hir>),
2027 /// An associated type with (possibly empty) bounds and optional concrete
2029 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
2032 // The bodies for items are stored "out of line", in a separate
2033 // hashmap in the `Crate`. Here we just record the hir-id of the item
2034 // so it can fetched later.
2035 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
2036 pub struct ImplItemId {
2037 pub def_id: LocalDefId,
2042 pub fn hir_id(&self) -> HirId {
2043 // Items are always HIR owners.
2044 HirId::make_owner(self.def_id)
2048 /// Represents anything within an `impl` block.
2050 pub struct ImplItem<'hir> {
2052 pub def_id: LocalDefId,
2053 pub vis: Visibility<'hir>,
2054 pub defaultness: Defaultness,
2055 pub generics: Generics<'hir>,
2056 pub kind: ImplItemKind<'hir>,
2062 pub fn hir_id(&self) -> HirId {
2063 // Items are always HIR owners.
2064 HirId::make_owner(self.def_id)
2067 pub fn impl_item_id(&self) -> ImplItemId {
2068 ImplItemId { def_id: self.def_id }
2072 /// Represents various kinds of content within an `impl`.
2073 #[derive(Debug, HashStable_Generic)]
2074 pub enum ImplItemKind<'hir> {
2075 /// An associated constant of the given type, set to the constant result
2076 /// of the expression.
2077 Const(&'hir Ty<'hir>, BodyId),
2078 /// An associated function implementation with the given signature and body.
2079 Fn(FnSig<'hir>, BodyId),
2080 /// An associated type.
2081 TyAlias(&'hir Ty<'hir>),
2084 // The name of the associated type for `Fn` return types.
2085 pub const FN_OUTPUT_NAME: Symbol = sym::Output;
2087 /// Bind a type to an associated type (i.e., `A = Foo`).
2089 /// Bindings like `A: Debug` are represented as a special type `A =
2090 /// $::Debug` that is understood by the astconv code.
2092 /// FIXME(alexreg): why have a separate type for the binding case,
2093 /// wouldn't it be better to make the `ty` field an enum like the
2097 /// enum TypeBindingKind {
2102 #[derive(Debug, HashStable_Generic)]
2103 pub struct TypeBinding<'hir> {
2105 #[stable_hasher(project(name))]
2107 pub gen_args: &'hir GenericArgs<'hir>,
2108 pub kind: TypeBindingKind<'hir>,
2112 // Represents the two kinds of type bindings.
2113 #[derive(Debug, HashStable_Generic)]
2114 pub enum TypeBindingKind<'hir> {
2115 /// E.g., `Foo<Bar: Send>`.
2116 Constraint { bounds: &'hir [GenericBound<'hir>] },
2117 /// E.g., `Foo<Bar = ()>`.
2118 Equality { ty: &'hir Ty<'hir> },
2121 impl TypeBinding<'_> {
2122 pub fn ty(&self) -> &Ty<'_> {
2124 TypeBindingKind::Equality { ref ty } => ty,
2125 _ => panic!("expected equality type binding for parenthesized generic args"),
2131 pub struct Ty<'hir> {
2133 pub kind: TyKind<'hir>,
2137 /// Not represented directly in the AST; referred to by name through a `ty_path`.
2138 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
2139 #[derive(HashStable_Generic)]
2150 /// All of the primitive types
2151 pub const ALL: [Self; 17] = [
2152 // any changes here should also be reflected in `PrimTy::from_name`
2153 Self::Int(IntTy::I8),
2154 Self::Int(IntTy::I16),
2155 Self::Int(IntTy::I32),
2156 Self::Int(IntTy::I64),
2157 Self::Int(IntTy::I128),
2158 Self::Int(IntTy::Isize),
2159 Self::Uint(UintTy::U8),
2160 Self::Uint(UintTy::U16),
2161 Self::Uint(UintTy::U32),
2162 Self::Uint(UintTy::U64),
2163 Self::Uint(UintTy::U128),
2164 Self::Uint(UintTy::Usize),
2165 Self::Float(FloatTy::F32),
2166 Self::Float(FloatTy::F64),
2172 /// Like [`PrimTy::name`], but returns a &str instead of a symbol.
2175 pub fn name_str(self) -> &'static str {
2177 PrimTy::Int(i) => i.name_str(),
2178 PrimTy::Uint(u) => u.name_str(),
2179 PrimTy::Float(f) => f.name_str(),
2180 PrimTy::Str => "str",
2181 PrimTy::Bool => "bool",
2182 PrimTy::Char => "char",
2186 pub fn name(self) -> Symbol {
2188 PrimTy::Int(i) => i.name(),
2189 PrimTy::Uint(u) => u.name(),
2190 PrimTy::Float(f) => f.name(),
2191 PrimTy::Str => sym::str,
2192 PrimTy::Bool => sym::bool,
2193 PrimTy::Char => sym::char,
2197 /// Returns the matching `PrimTy` for a `Symbol` such as "str" or "i32".
2198 /// Returns `None` if no matching type is found.
2199 pub fn from_name(name: Symbol) -> Option<Self> {
2200 let ty = match name {
2201 // any changes here should also be reflected in `PrimTy::ALL`
2202 sym::i8 => Self::Int(IntTy::I8),
2203 sym::i16 => Self::Int(IntTy::I16),
2204 sym::i32 => Self::Int(IntTy::I32),
2205 sym::i64 => Self::Int(IntTy::I64),
2206 sym::i128 => Self::Int(IntTy::I128),
2207 sym::isize => Self::Int(IntTy::Isize),
2208 sym::u8 => Self::Uint(UintTy::U8),
2209 sym::u16 => Self::Uint(UintTy::U16),
2210 sym::u32 => Self::Uint(UintTy::U32),
2211 sym::u64 => Self::Uint(UintTy::U64),
2212 sym::u128 => Self::Uint(UintTy::U128),
2213 sym::usize => Self::Uint(UintTy::Usize),
2214 sym::f32 => Self::Float(FloatTy::F32),
2215 sym::f64 => Self::Float(FloatTy::F64),
2216 sym::bool => Self::Bool,
2217 sym::char => Self::Char,
2218 sym::str => Self::Str,
2225 #[derive(Debug, HashStable_Generic)]
2226 pub struct BareFnTy<'hir> {
2227 pub unsafety: Unsafety,
2229 pub generic_params: &'hir [GenericParam<'hir>],
2230 pub decl: &'hir FnDecl<'hir>,
2231 pub param_names: &'hir [Ident],
2234 #[derive(Debug, HashStable_Generic)]
2235 pub struct OpaqueTy<'hir> {
2236 pub generics: Generics<'hir>,
2237 pub bounds: GenericBounds<'hir>,
2238 pub impl_trait_fn: Option<DefId>,
2239 pub origin: OpaqueTyOrigin,
2242 /// From whence the opaque type came.
2243 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2244 pub enum OpaqueTyOrigin {
2249 /// type aliases: `type Foo = impl Trait;`
2253 /// The various kinds of types recognized by the compiler.
2254 #[derive(Debug, HashStable_Generic)]
2255 pub enum TyKind<'hir> {
2256 /// A variable length slice (i.e., `[T]`).
2257 Slice(&'hir Ty<'hir>),
2258 /// A fixed length array (i.e., `[T; n]`).
2259 Array(&'hir Ty<'hir>, AnonConst),
2260 /// A raw pointer (i.e., `*const T` or `*mut T`).
2262 /// A reference (i.e., `&'a T` or `&'a mut T`).
2263 Rptr(Lifetime, MutTy<'hir>),
2264 /// A bare function (e.g., `fn(usize) -> bool`).
2265 BareFn(&'hir BareFnTy<'hir>),
2266 /// The never type (`!`).
2268 /// A tuple (`(A, B, C, D, ...)`).
2269 Tup(&'hir [Ty<'hir>]),
2270 /// A path to a type definition (`module::module::...::Type`), or an
2271 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2273 /// Type parameters may be stored in each `PathSegment`.
2275 /// An opaque type definition itself. This is currently only used for the
2276 /// `opaque type Foo: Trait` item that `impl Trait` in desugars to.
2278 /// The generic argument list contains the lifetimes (and in the future
2279 /// possibly parameters) that are actually bound on the `impl Trait`.
2280 OpaqueDef(ItemId, &'hir [GenericArg<'hir>]),
2281 /// A trait object type `Bound1 + Bound2 + Bound3`
2282 /// where `Bound` is a trait or a lifetime.
2283 TraitObject(&'hir [PolyTraitRef<'hir>], Lifetime, TraitObjectSyntax),
2286 /// `TyKind::Infer` means the type should be inferred instead of it having been
2287 /// specified. This can appear anywhere in a type.
2289 /// Placeholder for a type that has failed to be defined.
2293 #[derive(Debug, HashStable_Generic)]
2294 pub enum InlineAsmOperand<'hir> {
2296 reg: InlineAsmRegOrRegClass,
2300 reg: InlineAsmRegOrRegClass,
2302 expr: Option<Expr<'hir>>,
2305 reg: InlineAsmRegOrRegClass,
2310 reg: InlineAsmRegOrRegClass,
2312 in_expr: Expr<'hir>,
2313 out_expr: Option<Expr<'hir>>,
2316 anon_const: AnonConst,
2323 impl<'hir> InlineAsmOperand<'hir> {
2324 pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
2326 Self::In { reg, .. }
2327 | Self::Out { reg, .. }
2328 | Self::InOut { reg, .. }
2329 | Self::SplitInOut { reg, .. } => Some(reg),
2330 Self::Const { .. } | Self::Sym { .. } => None,
2335 #[derive(Debug, HashStable_Generic)]
2336 pub struct InlineAsm<'hir> {
2337 pub template: &'hir [InlineAsmTemplatePiece],
2338 pub template_strs: &'hir [(Symbol, Option<Symbol>, Span)],
2339 pub operands: &'hir [(InlineAsmOperand<'hir>, Span)],
2340 pub options: InlineAsmOptions,
2341 pub line_spans: &'hir [Span],
2344 #[derive(Copy, Clone, Encodable, Decodable, Debug, Hash, HashStable_Generic, PartialEq)]
2345 pub struct LlvmInlineAsmOutput {
2346 pub constraint: Symbol,
2348 pub is_indirect: bool,
2352 // NOTE(eddyb) This is used within MIR as well, so unlike the rest of the HIR,
2353 // it needs to be `Clone` and `Decodable` and use plain `Vec<T>` instead of
2354 // arena-allocated slice.
2355 #[derive(Clone, Encodable, Decodable, Debug, Hash, HashStable_Generic, PartialEq)]
2356 pub struct LlvmInlineAsmInner {
2358 pub asm_str_style: StrStyle,
2359 pub outputs: Vec<LlvmInlineAsmOutput>,
2360 pub inputs: Vec<Symbol>,
2361 pub clobbers: Vec<Symbol>,
2363 pub alignstack: bool,
2364 pub dialect: LlvmAsmDialect,
2367 #[derive(Debug, HashStable_Generic)]
2368 pub struct LlvmInlineAsm<'hir> {
2369 pub inner: LlvmInlineAsmInner,
2370 pub outputs_exprs: &'hir [Expr<'hir>],
2371 pub inputs_exprs: &'hir [Expr<'hir>],
2374 /// Represents a parameter in a function header.
2375 #[derive(Debug, HashStable_Generic)]
2376 pub struct Param<'hir> {
2378 pub pat: &'hir Pat<'hir>,
2383 /// Represents the header (not the body) of a function declaration.
2384 #[derive(Debug, HashStable_Generic)]
2385 pub struct FnDecl<'hir> {
2386 /// The types of the function's parameters.
2388 /// Additional argument data is stored in the function's [body](Body::params).
2389 pub inputs: &'hir [Ty<'hir>],
2390 pub output: FnRetTy<'hir>,
2391 pub c_variadic: bool,
2392 /// Does the function have an implicit self?
2393 pub implicit_self: ImplicitSelfKind,
2396 /// Represents what type of implicit self a function has, if any.
2397 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2398 pub enum ImplicitSelfKind {
2399 /// Represents a `fn x(self);`.
2401 /// Represents a `fn x(mut self);`.
2403 /// Represents a `fn x(&self);`.
2405 /// Represents a `fn x(&mut self);`.
2407 /// Represents when a function does not have a self argument or
2408 /// when a function has a `self: X` argument.
2412 impl ImplicitSelfKind {
2413 /// Does this represent an implicit self?
2414 pub fn has_implicit_self(&self) -> bool {
2415 !matches!(*self, ImplicitSelfKind::None)
2419 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable, Debug)]
2420 #[derive(HashStable_Generic)]
2426 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable, HashStable_Generic)]
2427 pub enum Defaultness {
2428 Default { has_value: bool },
2433 pub fn has_value(&self) -> bool {
2435 Defaultness::Default { has_value } => has_value,
2436 Defaultness::Final => true,
2440 pub fn is_final(&self) -> bool {
2441 *self == Defaultness::Final
2444 pub fn is_default(&self) -> bool {
2445 matches!(*self, Defaultness::Default { .. })
2449 #[derive(Debug, HashStable_Generic)]
2450 pub enum FnRetTy<'hir> {
2451 /// Return type is not specified.
2453 /// Functions default to `()` and
2454 /// closures default to inference. Span points to where return
2455 /// type would be inserted.
2456 DefaultReturn(Span),
2457 /// Everything else.
2458 Return(&'hir Ty<'hir>),
2463 pub fn span(&self) -> Span {
2465 Self::DefaultReturn(span) => span,
2466 Self::Return(ref ty) => ty.span,
2471 #[derive(Encodable, Debug)]
2472 pub struct Mod<'hir> {
2473 /// A span from the first token past `{` to the last token until `}`.
2474 /// For `mod foo;`, the inner span ranges from the first token
2475 /// to the last token in the external file.
2477 pub item_ids: &'hir [ItemId],
2480 #[derive(Debug, HashStable_Generic)]
2481 pub struct EnumDef<'hir> {
2482 pub variants: &'hir [Variant<'hir>],
2485 #[derive(Debug, HashStable_Generic)]
2486 pub struct Variant<'hir> {
2487 /// Name of the variant.
2488 #[stable_hasher(project(name))]
2490 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2492 /// Fields and constructor id of the variant.
2493 pub data: VariantData<'hir>,
2494 /// Explicit discriminant (e.g., `Foo = 1`).
2495 pub disr_expr: Option<AnonConst>,
2500 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2502 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2503 /// Also produced for each element of a list `use`, e.g.
2504 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2507 /// Glob import, e.g., `use foo::*`.
2510 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2511 /// an additional `use foo::{}` for performing checks such as
2512 /// unstable feature gating. May be removed in the future.
2516 /// References to traits in impls.
2518 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2519 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2520 /// trait being referred to but just a unique `HirId` that serves as a key
2521 /// within the resolution map.
2522 #[derive(Clone, Debug, HashStable_Generic)]
2523 pub struct TraitRef<'hir> {
2524 pub path: &'hir Path<'hir>,
2525 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2526 #[stable_hasher(ignore)]
2527 pub hir_ref_id: HirId,
2531 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2532 pub fn trait_def_id(&self) -> Option<DefId> {
2533 match self.path.res {
2534 Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
2536 _ => unreachable!(),
2541 #[derive(Clone, Debug, HashStable_Generic)]
2542 pub struct PolyTraitRef<'hir> {
2543 /// The `'a` in `for<'a> Foo<&'a T>`.
2544 pub bound_generic_params: &'hir [GenericParam<'hir>],
2546 /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
2547 pub trait_ref: TraitRef<'hir>,
2552 pub type Visibility<'hir> = Spanned<VisibilityKind<'hir>>;
2554 #[derive(Copy, Clone, Debug)]
2555 pub enum VisibilityKind<'hir> {
2558 Restricted { path: &'hir Path<'hir>, hir_id: HirId },
2562 impl VisibilityKind<'_> {
2563 pub fn is_pub(&self) -> bool {
2564 matches!(*self, VisibilityKind::Public)
2567 pub fn is_pub_restricted(&self) -> bool {
2569 VisibilityKind::Public | VisibilityKind::Inherited => false,
2570 VisibilityKind::Crate(..) | VisibilityKind::Restricted { .. } => true,
2575 #[derive(Debug, HashStable_Generic)]
2576 pub struct FieldDef<'hir> {
2578 #[stable_hasher(project(name))]
2580 pub vis: Visibility<'hir>,
2582 pub ty: &'hir Ty<'hir>,
2586 // Still necessary in couple of places
2587 pub fn is_positional(&self) -> bool {
2588 let first = self.ident.as_str().as_bytes()[0];
2589 (b'0'..=b'9').contains(&first)
2593 /// Fields and constructor IDs of enum variants and structs.
2594 #[derive(Debug, HashStable_Generic)]
2595 pub enum VariantData<'hir> {
2596 /// A struct variant.
2598 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2599 Struct(&'hir [FieldDef<'hir>], /* recovered */ bool),
2600 /// A tuple variant.
2602 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2603 Tuple(&'hir [FieldDef<'hir>], HirId),
2606 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2610 impl VariantData<'hir> {
2611 /// Return the fields of this variant.
2612 pub fn fields(&self) -> &'hir [FieldDef<'hir>] {
2614 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2619 /// Return the `HirId` of this variant's constructor, if it has one.
2620 pub fn ctor_hir_id(&self) -> Option<HirId> {
2622 VariantData::Struct(_, _) => None,
2623 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2628 // The bodies for items are stored "out of line", in a separate
2629 // hashmap in the `Crate`. Here we just record the hir-id of the item
2630 // so it can fetched later.
2631 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug, Hash)]
2633 pub def_id: LocalDefId,
2638 pub fn hir_id(&self) -> HirId {
2639 // Items are always HIR owners.
2640 HirId::make_owner(self.def_id)
2646 /// The name might be a dummy name in case of anonymous items
2648 pub struct Item<'hir> {
2650 pub def_id: LocalDefId,
2651 pub kind: ItemKind<'hir>,
2652 pub vis: Visibility<'hir>,
2658 pub fn hir_id(&self) -> HirId {
2659 // Items are always HIR owners.
2660 HirId::make_owner(self.def_id)
2663 pub fn item_id(&self) -> ItemId {
2664 ItemId { def_id: self.def_id }
2668 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2669 #[derive(Encodable, Decodable, HashStable_Generic)]
2676 pub fn prefix_str(&self) -> &'static str {
2678 Self::Unsafe => "unsafe ",
2684 impl fmt::Display for Unsafety {
2685 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2686 f.write_str(match *self {
2687 Self::Unsafe => "unsafe",
2688 Self::Normal => "normal",
2693 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2694 #[derive(Encodable, Decodable, HashStable_Generic)]
2695 pub enum Constness {
2700 impl fmt::Display for Constness {
2701 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2702 f.write_str(match *self {
2703 Self::Const => "const",
2704 Self::NotConst => "non-const",
2709 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2710 pub struct FnHeader {
2711 pub unsafety: Unsafety,
2712 pub constness: Constness,
2713 pub asyncness: IsAsync,
2718 pub fn is_const(&self) -> bool {
2719 matches!(&self.constness, Constness::Const)
2723 #[derive(Debug, HashStable_Generic)]
2724 pub enum ItemKind<'hir> {
2725 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2727 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2728 ExternCrate(Option<Symbol>),
2730 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2734 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2735 Use(&'hir Path<'hir>, UseKind),
2737 /// A `static` item.
2738 Static(&'hir Ty<'hir>, Mutability, BodyId),
2740 Const(&'hir Ty<'hir>, BodyId),
2741 /// A function declaration.
2742 Fn(FnSig<'hir>, Generics<'hir>, BodyId),
2743 /// A MBE macro definition (`macro_rules!` or `macro`).
2744 Macro(ast::MacroDef),
2747 /// An external module, e.g. `extern { .. }`.
2748 ForeignMod { abi: Abi, items: &'hir [ForeignItemRef<'hir>] },
2749 /// Module-level inline assembly (from `global_asm!`).
2750 GlobalAsm(&'hir InlineAsm<'hir>),
2751 /// A type alias, e.g., `type Foo = Bar<u8>`.
2752 TyAlias(&'hir Ty<'hir>, Generics<'hir>),
2753 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2754 OpaqueTy(OpaqueTy<'hir>),
2755 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2756 Enum(EnumDef<'hir>, Generics<'hir>),
2757 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2758 Struct(VariantData<'hir>, Generics<'hir>),
2759 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2760 Union(VariantData<'hir>, Generics<'hir>),
2761 /// A trait definition.
2762 Trait(IsAuto, Unsafety, Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
2764 TraitAlias(Generics<'hir>, GenericBounds<'hir>),
2766 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2770 #[derive(Debug, HashStable_Generic)]
2771 pub struct Impl<'hir> {
2772 pub unsafety: Unsafety,
2773 pub polarity: ImplPolarity,
2774 pub defaultness: Defaultness,
2775 // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata
2776 // decoding as `Span`s cannot be decoded when a `Session` is not available.
2777 pub defaultness_span: Option<Span>,
2778 pub constness: Constness,
2779 pub generics: Generics<'hir>,
2781 /// The trait being implemented, if any.
2782 pub of_trait: Option<TraitRef<'hir>>,
2784 pub self_ty: &'hir Ty<'hir>,
2785 pub items: &'hir [ImplItemRef<'hir>],
2789 pub fn generics(&self) -> Option<&Generics<'_>> {
2791 ItemKind::Fn(_, ref generics, _)
2792 | ItemKind::TyAlias(_, ref generics)
2793 | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
2794 | ItemKind::Enum(_, ref generics)
2795 | ItemKind::Struct(_, ref generics)
2796 | ItemKind::Union(_, ref generics)
2797 | ItemKind::Trait(_, _, ref generics, _, _)
2798 | ItemKind::Impl(Impl { ref generics, .. }) => generics,
2803 pub fn descr(&self) -> &'static str {
2805 ItemKind::ExternCrate(..) => "extern crate",
2806 ItemKind::Use(..) => "`use` import",
2807 ItemKind::Static(..) => "static item",
2808 ItemKind::Const(..) => "constant item",
2809 ItemKind::Fn(..) => "function",
2810 ItemKind::Macro(..) => "macro",
2811 ItemKind::Mod(..) => "module",
2812 ItemKind::ForeignMod { .. } => "extern block",
2813 ItemKind::GlobalAsm(..) => "global asm item",
2814 ItemKind::TyAlias(..) => "type alias",
2815 ItemKind::OpaqueTy(..) => "opaque type",
2816 ItemKind::Enum(..) => "enum",
2817 ItemKind::Struct(..) => "struct",
2818 ItemKind::Union(..) => "union",
2819 ItemKind::Trait(..) => "trait",
2820 ItemKind::TraitAlias(..) => "trait alias",
2821 ItemKind::Impl(..) => "implementation",
2826 /// A reference from an trait to one of its associated items. This
2827 /// contains the item's id, naturally, but also the item's name and
2828 /// some other high-level details (like whether it is an associated
2829 /// type or method, and whether it is public). This allows other
2830 /// passes to find the impl they want without loading the ID (which
2831 /// means fewer edges in the incremental compilation graph).
2832 #[derive(Encodable, Debug, HashStable_Generic)]
2833 pub struct TraitItemRef {
2834 pub id: TraitItemId,
2835 #[stable_hasher(project(name))]
2837 pub kind: AssocItemKind,
2839 pub defaultness: Defaultness,
2842 /// A reference from an impl to one of its associated items. This
2843 /// contains the item's ID, naturally, but also the item's name and
2844 /// some other high-level details (like whether it is an associated
2845 /// type or method, and whether it is public). This allows other
2846 /// passes to find the impl they want without loading the ID (which
2847 /// means fewer edges in the incremental compilation graph).
2848 #[derive(Debug, HashStable_Generic)]
2849 pub struct ImplItemRef<'hir> {
2851 #[stable_hasher(project(name))]
2853 pub kind: AssocItemKind,
2855 pub vis: Visibility<'hir>,
2856 pub defaultness: Defaultness,
2859 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2860 pub enum AssocItemKind {
2862 Fn { has_self: bool },
2866 // The bodies for items are stored "out of line", in a separate
2867 // hashmap in the `Crate`. Here we just record the hir-id of the item
2868 // so it can fetched later.
2869 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
2870 pub struct ForeignItemId {
2871 pub def_id: LocalDefId,
2874 impl ForeignItemId {
2876 pub fn hir_id(&self) -> HirId {
2877 // Items are always HIR owners.
2878 HirId::make_owner(self.def_id)
2882 /// A reference from a foreign block to one of its items. This
2883 /// contains the item's ID, naturally, but also the item's name and
2884 /// some other high-level details (like whether it is an associated
2885 /// type or method, and whether it is public). This allows other
2886 /// passes to find the impl they want without loading the ID (which
2887 /// means fewer edges in the incremental compilation graph).
2888 #[derive(Debug, HashStable_Generic)]
2889 pub struct ForeignItemRef<'hir> {
2890 pub id: ForeignItemId,
2891 #[stable_hasher(project(name))]
2894 pub vis: Visibility<'hir>,
2898 pub struct ForeignItem<'hir> {
2900 pub kind: ForeignItemKind<'hir>,
2901 pub def_id: LocalDefId,
2903 pub vis: Visibility<'hir>,
2906 impl ForeignItem<'_> {
2908 pub fn hir_id(&self) -> HirId {
2909 // Items are always HIR owners.
2910 HirId::make_owner(self.def_id)
2913 pub fn foreign_item_id(&self) -> ForeignItemId {
2914 ForeignItemId { def_id: self.def_id }
2918 /// An item within an `extern` block.
2919 #[derive(Debug, HashStable_Generic)]
2920 pub enum ForeignItemKind<'hir> {
2921 /// A foreign function.
2922 Fn(&'hir FnDecl<'hir>, &'hir [Ident], Generics<'hir>),
2923 /// A foreign static item (`static ext: u8`).
2924 Static(&'hir Ty<'hir>, Mutability),
2929 /// A variable captured by a closure.
2930 #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)]
2932 // First span where it is accessed (there can be multiple).
2936 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2937 // has length > 0 if the trait is found through an chain of imports, starting with the
2938 // import/use statement in the scope where the trait is used.
2939 #[derive(Encodable, Decodable, Clone, Debug)]
2940 pub struct TraitCandidate {
2942 pub import_ids: SmallVec<[LocalDefId; 1]>,
2945 #[derive(Copy, Clone, Debug, HashStable_Generic)]
2946 pub enum OwnerNode<'hir> {
2947 Item(&'hir Item<'hir>),
2948 ForeignItem(&'hir ForeignItem<'hir>),
2949 TraitItem(&'hir TraitItem<'hir>),
2950 ImplItem(&'hir ImplItem<'hir>),
2951 Crate(&'hir Mod<'hir>),
2954 impl<'hir> OwnerNode<'hir> {
2955 pub fn ident(&self) -> Option<Ident> {
2957 OwnerNode::Item(Item { ident, .. })
2958 | OwnerNode::ForeignItem(ForeignItem { ident, .. })
2959 | OwnerNode::ImplItem(ImplItem { ident, .. })
2960 | OwnerNode::TraitItem(TraitItem { ident, .. }) => Some(*ident),
2961 OwnerNode::Crate(..) => None,
2965 pub fn span(&self) -> Span {
2967 OwnerNode::Item(Item { span, .. })
2968 | OwnerNode::ForeignItem(ForeignItem { span, .. })
2969 | OwnerNode::ImplItem(ImplItem { span, .. })
2970 | OwnerNode::TraitItem(TraitItem { span, .. })
2971 | OwnerNode::Crate(Mod { inner: span, .. }) => *span,
2975 pub fn fn_decl(&self) -> Option<&FnDecl<'hir>> {
2977 OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
2978 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
2979 | OwnerNode::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
2980 OwnerNode::ForeignItem(ForeignItem {
2981 kind: ForeignItemKind::Fn(fn_decl, _, _),
2983 }) => Some(fn_decl),
2988 pub fn body_id(&self) -> Option<BodyId> {
2990 OwnerNode::TraitItem(TraitItem {
2991 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
2994 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
2995 | OwnerNode::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3000 pub fn generics(&self) -> Option<&'hir Generics<'hir>> {
3002 OwnerNode::TraitItem(TraitItem { generics, .. })
3003 | OwnerNode::ImplItem(ImplItem { generics, .. }) => Some(generics),
3004 OwnerNode::Item(item) => item.kind.generics(),
3009 pub fn def_id(self) -> LocalDefId {
3011 OwnerNode::Item(Item { def_id, .. })
3012 | OwnerNode::TraitItem(TraitItem { def_id, .. })
3013 | OwnerNode::ImplItem(ImplItem { def_id, .. })
3014 | OwnerNode::ForeignItem(ForeignItem { def_id, .. }) => *def_id,
3015 OwnerNode::Crate(..) => crate::CRATE_HIR_ID.owner,
3019 pub fn expect_item(self) -> &'hir Item<'hir> {
3021 OwnerNode::Item(n) => n,
3026 pub fn expect_foreign_item(self) -> &'hir ForeignItem<'hir> {
3028 OwnerNode::ForeignItem(n) => n,
3033 pub fn expect_impl_item(self) -> &'hir ImplItem<'hir> {
3035 OwnerNode::ImplItem(n) => n,
3040 pub fn expect_trait_item(self) -> &'hir TraitItem<'hir> {
3042 OwnerNode::TraitItem(n) => n,
3048 impl<'hir> Into<OwnerNode<'hir>> for &'hir Item<'hir> {
3049 fn into(self) -> OwnerNode<'hir> {
3050 OwnerNode::Item(self)
3054 impl<'hir> Into<OwnerNode<'hir>> for &'hir ForeignItem<'hir> {
3055 fn into(self) -> OwnerNode<'hir> {
3056 OwnerNode::ForeignItem(self)
3060 impl<'hir> Into<OwnerNode<'hir>> for &'hir ImplItem<'hir> {
3061 fn into(self) -> OwnerNode<'hir> {
3062 OwnerNode::ImplItem(self)
3066 impl<'hir> Into<OwnerNode<'hir>> for &'hir TraitItem<'hir> {
3067 fn into(self) -> OwnerNode<'hir> {
3068 OwnerNode::TraitItem(self)
3072 impl<'hir> Into<Node<'hir>> for OwnerNode<'hir> {
3073 fn into(self) -> Node<'hir> {
3075 OwnerNode::Item(n) => Node::Item(n),
3076 OwnerNode::ForeignItem(n) => Node::ForeignItem(n),
3077 OwnerNode::ImplItem(n) => Node::ImplItem(n),
3078 OwnerNode::TraitItem(n) => Node::TraitItem(n),
3079 OwnerNode::Crate(n) => Node::Crate(n),
3084 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3085 pub enum Node<'hir> {
3086 Param(&'hir Param<'hir>),
3087 Item(&'hir Item<'hir>),
3088 ForeignItem(&'hir ForeignItem<'hir>),
3089 TraitItem(&'hir TraitItem<'hir>),
3090 ImplItem(&'hir ImplItem<'hir>),
3091 Variant(&'hir Variant<'hir>),
3092 Field(&'hir FieldDef<'hir>),
3093 AnonConst(&'hir AnonConst),
3094 Expr(&'hir Expr<'hir>),
3095 Stmt(&'hir Stmt<'hir>),
3096 PathSegment(&'hir PathSegment<'hir>),
3098 TraitRef(&'hir TraitRef<'hir>),
3099 Binding(&'hir Pat<'hir>),
3100 Pat(&'hir Pat<'hir>),
3101 Arm(&'hir Arm<'hir>),
3102 Block(&'hir Block<'hir>),
3103 Local(&'hir Local<'hir>),
3105 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
3106 /// with synthesized constructors.
3107 Ctor(&'hir VariantData<'hir>),
3109 Lifetime(&'hir Lifetime),
3110 GenericParam(&'hir GenericParam<'hir>),
3111 Visibility(&'hir Visibility<'hir>),
3113 Crate(&'hir Mod<'hir>),
3115 Infer(&'hir InferArg),
3118 impl<'hir> Node<'hir> {
3119 /// Get the identifier of this `Node`, if applicable.
3123 /// Calling `.ident()` on a [`Node::Ctor`] will return `None`
3124 /// because `Ctor`s do not have identifiers themselves.
3125 /// Instead, call `.ident()` on the parent struct/variant, like so:
3127 /// ```ignore (illustrative)
3130 /// .and_then(|ctor_id| tcx.hir().find(tcx.hir().get_parent_node(ctor_id)))
3131 /// .and_then(|parent| parent.ident())
3133 pub fn ident(&self) -> Option<Ident> {
3135 Node::TraitItem(TraitItem { ident, .. })
3136 | Node::ImplItem(ImplItem { ident, .. })
3137 | Node::ForeignItem(ForeignItem { ident, .. })
3138 | Node::Field(FieldDef { ident, .. })
3139 | Node::Variant(Variant { ident, .. })
3140 | Node::Item(Item { ident, .. })
3141 | Node::PathSegment(PathSegment { ident, .. }) => Some(*ident),
3142 Node::Lifetime(lt) => Some(lt.name.ident()),
3143 Node::GenericParam(p) => Some(p.name.ident()),
3145 | Node::AnonConst(..)
3154 | Node::Visibility(..)
3157 | Node::TraitRef(..)
3158 | Node::Infer(..) => None,
3162 pub fn fn_decl(&self) -> Option<&FnDecl<'hir>> {
3164 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3165 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3166 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3167 Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
3174 pub fn body_id(&self) -> Option<BodyId> {
3176 Node::TraitItem(TraitItem {
3177 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3180 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3181 | Node::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3186 pub fn generics(&self) -> Option<&'hir Generics<'hir>> {
3188 Node::TraitItem(TraitItem { generics, .. })
3189 | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
3190 Node::Item(item) => item.kind.generics(),
3195 pub fn hir_id(&self) -> Option<HirId> {
3197 Node::Item(Item { def_id, .. })
3198 | Node::TraitItem(TraitItem { def_id, .. })
3199 | Node::ImplItem(ImplItem { def_id, .. })
3200 | Node::ForeignItem(ForeignItem { def_id, .. }) => Some(HirId::make_owner(*def_id)),
3201 Node::Field(FieldDef { hir_id, .. })
3202 | Node::AnonConst(AnonConst { hir_id, .. })
3203 | Node::Expr(Expr { hir_id, .. })
3204 | Node::Stmt(Stmt { hir_id, .. })
3205 | Node::Ty(Ty { hir_id, .. })
3206 | Node::Binding(Pat { hir_id, .. })
3207 | Node::Pat(Pat { hir_id, .. })
3208 | Node::Arm(Arm { hir_id, .. })
3209 | Node::Block(Block { hir_id, .. })
3210 | Node::Local(Local { hir_id, .. })
3211 | Node::Lifetime(Lifetime { hir_id, .. })
3212 | Node::Param(Param { hir_id, .. })
3213 | Node::Infer(InferArg { hir_id, .. })
3214 | Node::GenericParam(GenericParam { hir_id, .. }) => Some(*hir_id),
3215 Node::TraitRef(TraitRef { hir_ref_id, .. }) => Some(*hir_ref_id),
3216 Node::PathSegment(PathSegment { hir_id, .. }) => *hir_id,
3217 Node::Variant(Variant { id, .. }) => Some(*id),
3218 Node::Ctor(variant) => variant.ctor_hir_id(),
3219 Node::Crate(_) | Node::Visibility(_) => None,
3223 /// Returns `Constness::Const` when this node is a const fn/impl/item,
3225 /// HACK(fee1-dead): or an associated type in a trait. This works because
3226 /// only typeck cares about const trait predicates, so although the predicates
3227 /// query would return const predicates when it does not need to be const,
3228 /// it wouldn't have any effect.
3229 pub fn constness_for_typeck(&self) -> Constness {
3232 kind: ItemKind::Fn(FnSig { header: FnHeader { constness, .. }, .. }, ..),
3235 | Node::TraitItem(TraitItem {
3236 kind: TraitItemKind::Fn(FnSig { header: FnHeader { constness, .. }, .. }, ..),
3239 | Node::ImplItem(ImplItem {
3240 kind: ImplItemKind::Fn(FnSig { header: FnHeader { constness, .. }, .. }, ..),
3243 | Node::Item(Item { kind: ItemKind::Impl(Impl { constness, .. }), .. }) => *constness,
3245 Node::Item(Item { kind: ItemKind::Const(..), .. })
3246 | Node::TraitItem(TraitItem { kind: TraitItemKind::Const(..), .. })
3247 | Node::TraitItem(TraitItem { kind: TraitItemKind::Type(..), .. })
3248 | Node::ImplItem(ImplItem { kind: ImplItemKind::Const(..), .. }) => Constness::Const,
3250 _ => Constness::NotConst,
3254 pub fn as_owner(self) -> Option<OwnerNode<'hir>> {
3256 Node::Item(i) => Some(OwnerNode::Item(i)),
3257 Node::ForeignItem(i) => Some(OwnerNode::ForeignItem(i)),
3258 Node::TraitItem(i) => Some(OwnerNode::TraitItem(i)),
3259 Node::ImplItem(i) => Some(OwnerNode::ImplItem(i)),
3260 Node::Crate(i) => Some(OwnerNode::Crate(i)),
3266 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3267 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
3269 rustc_data_structures::static_assert_size!(super::Block<'static>, 48);
3270 rustc_data_structures::static_assert_size!(super::Expr<'static>, 64);
3271 rustc_data_structures::static_assert_size!(super::Pat<'static>, 88);
3272 rustc_data_structures::static_assert_size!(super::QPath<'static>, 24);
3273 rustc_data_structures::static_assert_size!(super::Ty<'static>, 72);
3275 rustc_data_structures::static_assert_size!(super::Item<'static>, 184);
3276 rustc_data_structures::static_assert_size!(super::TraitItem<'static>, 128);
3277 rustc_data_structures::static_assert_size!(super::ImplItem<'static>, 152);
3278 rustc_data_structures::static_assert_size!(super::ForeignItem<'static>, 136);