1 use crate::def::{CtorKind, DefKind, Res};
2 use crate::def_id::DefId;
3 pub(crate) use crate::hir_id::{HirId, ItemLocalId, OwnerId};
4 use crate::intravisit::FnKind;
8 use rustc_ast::util::parser::ExprPrecedence;
9 use rustc_ast::{Attribute, FloatTy, IntTy, Label, LitKind, TraitObjectSyntax, UintTy};
10 pub use rustc_ast::{BindingAnnotation, BorrowKind, ByRef, ImplPolarity, IsAuto};
11 pub use rustc_ast::{CaptureBy, Movability, Mutability};
12 use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
13 use rustc_data_structures::fingerprint::Fingerprint;
14 use rustc_data_structures::fx::FxHashMap;
15 use rustc_data_structures::sorted_map::SortedMap;
16 use rustc_error_messages::MultiSpan;
17 use rustc_index::vec::IndexVec;
18 use rustc_macros::HashStable_Generic;
19 use rustc_span::hygiene::MacroKind;
20 use rustc_span::source_map::Spanned;
21 use rustc_span::symbol::{kw, sym, Ident, Symbol};
22 use rustc_span::{def_id::LocalDefId, BytePos, Span, DUMMY_SP};
23 use rustc_target::asm::InlineAsmRegOrRegClass;
24 use rustc_target::spec::abi::Abi;
26 use smallvec::SmallVec;
29 #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)]
34 /// Either "`'a`", referring to a named lifetime definition,
35 /// or "``" (i.e., `kw::Empty`), for elision placeholders.
37 /// HIR lowering inserts these placeholders in type paths that
38 /// refer to type definitions needing lifetime parameters,
39 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
40 pub name: LifetimeName,
43 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
44 #[derive(HashStable_Generic)]
46 /// Some user-given name like `T` or `'x`.
49 /// Synthetic name generated when user elided a lifetime in an impl header.
51 /// E.g., the lifetimes in cases like these:
52 /// ```ignore (fragment)
54 /// impl Foo<'_> for u32
56 /// in that case, we rewrite to
57 /// ```ignore (fragment)
58 /// impl<'f> Foo for &'f u32
59 /// impl<'f> Foo<'f> for u32
61 /// where `'f` is something like `Fresh(0)`. The indices are
62 /// unique per impl, but not necessarily continuous.
65 /// Indicates an illegal name was given and an error has been
66 /// reported (so we should squelch other derived errors). Occurs
67 /// when, e.g., `'_` is used in the wrong place.
72 pub fn ident(&self) -> Ident {
74 ParamName::Plain(ident) => ident,
75 ParamName::Fresh | ParamName::Error => 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.
91 Param(LocalDefId, ParamName),
93 /// Implicit lifetime in a context like `dyn Foo`. This is
94 /// distinguished from implicit lifetimes elsewhere because the
95 /// lifetime that they default to must appear elsewhere within the
96 /// enclosing type. This means that, in an `impl Trait` context, we
97 /// don't have to create a parameter for them. That is, `impl
98 /// Trait<Item = &u32>` expands to an opaque type like `type
99 /// Foo<'a> = impl Trait<Item = &'a u32>`, but `impl Trait<item =
100 /// dyn Bar>` expands to `type Foo = impl Trait<Item = dyn Bar +
101 /// 'static>`. The latter uses `ImplicitObjectLifetimeDefault` so
102 /// that surrounding code knows not to create a lifetime
104 ImplicitObjectLifetimeDefault,
106 /// Indicates an error during lowering (usually `'_` in wrong place)
107 /// that was already reported.
110 /// User wrote an anonymous lifetime, either `'_` or nothing.
111 /// The semantics of this lifetime should be inferred by typechecking code.
114 /// User wrote `'static`.
119 pub fn ident(&self) -> Ident {
121 LifetimeName::ImplicitObjectLifetimeDefault | LifetimeName::Error => Ident::empty(),
122 LifetimeName::Infer => Ident::with_dummy_span(kw::UnderscoreLifetime),
123 LifetimeName::Static => Ident::with_dummy_span(kw::StaticLifetime),
124 LifetimeName::Param(_, param_name) => param_name.ident(),
128 pub fn is_anonymous(&self) -> bool {
130 LifetimeName::ImplicitObjectLifetimeDefault
131 | LifetimeName::Infer
132 | LifetimeName::Param(_, ParamName::Fresh)
133 | LifetimeName::Error => true,
134 LifetimeName::Static | LifetimeName::Param(..) => false,
138 pub fn is_elided(&self) -> bool {
140 LifetimeName::ImplicitObjectLifetimeDefault | LifetimeName::Infer => true,
142 // It might seem surprising that `Fresh` counts as not *elided*
143 // -- but this is because, as far as the code in the compiler is
144 // concerned -- `Fresh` variants act equivalently to "some fresh name".
145 // They correspond to early-bound regions on an impl, in other words.
146 LifetimeName::Error | LifetimeName::Param(..) | LifetimeName::Static => false,
150 fn is_static(&self) -> bool {
151 self == &LifetimeName::Static
154 pub fn normalize_to_macros_2_0(&self) -> LifetimeName {
156 LifetimeName::Param(def_id, param_name) => {
157 LifetimeName::Param(def_id, param_name.normalize_to_macros_2_0())
159 lifetime_name => lifetime_name,
164 impl fmt::Display for Lifetime {
165 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166 self.name.ident().fmt(f)
171 pub fn is_elided(&self) -> bool {
172 self.name.is_elided()
175 pub fn is_static(&self) -> bool {
176 self.name.is_static()
180 /// A `Path` is essentially Rust's notion of a name; for instance,
181 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
182 /// along with a bunch of supporting information.
183 #[derive(Debug, HashStable_Generic)]
184 pub struct Path<'hir> {
186 /// The resolution for the path.
188 /// The segments in the path: the things separated by `::`.
189 pub segments: &'hir [PathSegment<'hir>],
193 pub fn is_global(&self) -> bool {
194 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
198 /// A segment of a path: an identifier, an optional lifetime, and a set of
200 #[derive(Debug, HashStable_Generic)]
201 pub struct PathSegment<'hir> {
202 /// The identifier portion of this path segment.
207 /// Type/lifetime parameters attached to this path. They come in
208 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
209 /// this is more than just simple syntactic sugar; the use of
210 /// parens affects the region binding rules, so we preserve the
212 pub args: Option<&'hir GenericArgs<'hir>>,
214 /// Whether to infer remaining type parameters, if any.
215 /// This only applies to expression and pattern paths, and
216 /// out of those only the segments with no type parameters
217 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
218 pub infer_args: bool,
221 impl<'hir> PathSegment<'hir> {
222 /// Converts an identifier to the corresponding segment.
223 pub fn new(ident: Ident, hir_id: HirId, res: Res) -> PathSegment<'hir> {
224 PathSegment { ident, hir_id, res, infer_args: true, args: None }
227 pub fn invalid() -> Self {
228 Self::new(Ident::empty(), HirId::INVALID, Res::Err)
231 pub fn args(&self) -> &GenericArgs<'hir> {
232 if let Some(ref args) = self.args {
235 const DUMMY: &GenericArgs<'_> = &GenericArgs::none();
241 #[derive(Encodable, Debug, HashStable_Generic)]
242 pub struct ConstArg {
243 pub value: AnonConst,
247 #[derive(Encodable, Debug, HashStable_Generic)]
248 pub struct InferArg {
254 pub fn to_ty(&self) -> Ty<'_> {
255 Ty { kind: TyKind::Infer, span: self.span, hir_id: self.hir_id }
259 #[derive(Debug, HashStable_Generic)]
260 pub enum GenericArg<'hir> {
261 Lifetime(&'hir Lifetime),
262 Type(&'hir Ty<'hir>),
267 impl GenericArg<'_> {
268 pub fn span(&self) -> Span {
270 GenericArg::Lifetime(l) => l.span,
271 GenericArg::Type(t) => t.span,
272 GenericArg::Const(c) => c.span,
273 GenericArg::Infer(i) => i.span,
277 pub fn hir_id(&self) -> HirId {
279 GenericArg::Lifetime(l) => l.hir_id,
280 GenericArg::Type(t) => t.hir_id,
281 GenericArg::Const(c) => c.value.hir_id,
282 GenericArg::Infer(i) => i.hir_id,
286 pub fn is_synthetic(&self) -> bool {
287 matches!(self, GenericArg::Lifetime(lifetime) if lifetime.name.ident() == Ident::empty())
290 pub fn descr(&self) -> &'static str {
292 GenericArg::Lifetime(_) => "lifetime",
293 GenericArg::Type(_) => "type",
294 GenericArg::Const(_) => "constant",
295 GenericArg::Infer(_) => "inferred",
299 pub fn to_ord(&self) -> ast::ParamKindOrd {
301 GenericArg::Lifetime(_) => ast::ParamKindOrd::Lifetime,
302 GenericArg::Type(_) | GenericArg::Const(_) | GenericArg::Infer(_) => {
303 ast::ParamKindOrd::TypeOrConst
308 pub fn is_ty_or_const(&self) -> bool {
310 GenericArg::Lifetime(_) => false,
311 GenericArg::Type(_) | GenericArg::Const(_) | GenericArg::Infer(_) => true,
316 #[derive(Debug, HashStable_Generic)]
317 pub struct GenericArgs<'hir> {
318 /// The generic arguments for this path segment.
319 pub args: &'hir [GenericArg<'hir>],
320 /// Bindings (equality constraints) on associated types, if present.
321 /// E.g., `Foo<A = Bar>`.
322 pub bindings: &'hir [TypeBinding<'hir>],
323 /// Were arguments written in parenthesized form `Fn(T) -> U`?
324 /// This is required mostly for pretty-printing and diagnostics,
325 /// but also for changing lifetime elision rules to be "function-like".
326 pub parenthesized: bool,
327 /// The span encompassing arguments and the surrounding brackets `<>` or `()`
328 /// Foo<A, B, AssocTy = D> Fn(T, U, V) -> W
329 /// ^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^
330 /// Note that this may be:
331 /// - empty, if there are no generic brackets (but there may be hidden lifetimes)
332 /// - dummy, if this was generated while desugaring
336 impl<'hir> GenericArgs<'hir> {
337 pub const fn none() -> Self {
338 Self { args: &[], bindings: &[], parenthesized: false, span_ext: DUMMY_SP }
341 pub fn inputs(&self) -> &[Ty<'hir>] {
342 if self.parenthesized {
343 for arg in self.args {
345 GenericArg::Lifetime(_) => {}
346 GenericArg::Type(ref ty) => {
347 if let TyKind::Tup(ref tys) = ty.kind {
352 GenericArg::Const(_) => {}
353 GenericArg::Infer(_) => {}
357 panic!("GenericArgs::inputs: not a `Fn(T) -> U`");
361 pub fn has_type_params(&self) -> bool {
362 self.args.iter().any(|arg| matches!(arg, GenericArg::Type(_)))
365 pub fn has_err(&self) -> bool {
366 self.args.iter().any(|arg| match arg {
367 GenericArg::Type(ty) => matches!(ty.kind, TyKind::Err),
369 }) || self.bindings.iter().any(|arg| match arg.kind {
370 TypeBindingKind::Equality { term: Term::Ty(ty) } => matches!(ty.kind, TyKind::Err),
376 pub fn num_type_params(&self) -> usize {
377 self.args.iter().filter(|arg| matches!(arg, GenericArg::Type(_))).count()
381 pub fn num_lifetime_params(&self) -> usize {
382 self.args.iter().filter(|arg| matches!(arg, GenericArg::Lifetime(_))).count()
386 pub fn has_lifetime_params(&self) -> bool {
387 self.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)))
391 /// This function returns the number of type and const generic params.
392 /// It should only be used for diagnostics.
393 pub fn num_generic_params(&self) -> usize {
394 self.args.iter().filter(|arg| !matches!(arg, GenericArg::Lifetime(_))).count()
397 /// The span encompassing the text inside the surrounding brackets.
398 /// It will also include bindings if they aren't in the form `-> Ret`
399 /// Returns `None` if the span is empty (e.g. no brackets) or dummy
400 pub fn span(&self) -> Option<Span> {
401 let span_ext = self.span_ext()?;
402 Some(span_ext.with_lo(span_ext.lo() + BytePos(1)).with_hi(span_ext.hi() - BytePos(1)))
405 /// Returns span encompassing arguments and their surrounding `<>` or `()`
406 pub fn span_ext(&self) -> Option<Span> {
407 Some(self.span_ext).filter(|span| !span.is_empty())
410 pub fn is_empty(&self) -> bool {
415 /// A modifier on a bound, currently this is only used for `?Sized`, where the
416 /// modifier is `Maybe`. Negative bounds should also be handled here.
417 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
418 #[derive(HashStable_Generic)]
419 pub enum TraitBoundModifier {
425 /// The AST represents all type param bounds as types.
426 /// `typeck::collect::compute_bounds` matches these against
427 /// the "special" built-in traits (see `middle::lang_items`) and
428 /// detects `Copy`, `Send` and `Sync`.
429 #[derive(Clone, Debug, HashStable_Generic)]
430 pub enum GenericBound<'hir> {
431 Trait(PolyTraitRef<'hir>, TraitBoundModifier),
432 // FIXME(davidtwco): Introduce `PolyTraitRef::LangItem`
433 LangItemTrait(LangItem, Span, HirId, &'hir GenericArgs<'hir>),
434 Outlives(&'hir Lifetime),
437 impl GenericBound<'_> {
438 pub fn trait_ref(&self) -> Option<&TraitRef<'_>> {
440 GenericBound::Trait(data, _) => Some(&data.trait_ref),
445 pub fn span(&self) -> Span {
447 GenericBound::Trait(t, ..) => t.span,
448 GenericBound::LangItemTrait(_, span, ..) => *span,
449 GenericBound::Outlives(l) => l.span,
454 pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
456 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
457 pub enum LifetimeParamKind {
458 // Indicates that the lifetime definition was explicitly declared (e.g., in
459 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
462 // Indication that the lifetime was elided (e.g., in both cases in
463 // `fn foo(x: &u8) -> &'_ u8 { x }`).
466 // Indication that the lifetime name was somehow in error.
470 #[derive(Debug, HashStable_Generic)]
471 pub enum GenericParamKind<'hir> {
472 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
474 kind: LifetimeParamKind,
477 default: Option<&'hir Ty<'hir>>,
482 /// Optional default value for the const generic param
483 default: Option<AnonConst>,
487 #[derive(Debug, HashStable_Generic)]
488 pub struct GenericParam<'hir> {
490 pub def_id: LocalDefId,
493 pub pure_wrt_drop: bool,
494 pub kind: GenericParamKind<'hir>,
495 pub colon_span: Option<Span>,
498 impl<'hir> GenericParam<'hir> {
499 /// Synthetic type-parameters are inserted after normal ones.
500 /// In order for normal parameters to be able to refer to synthetic ones,
501 /// scans them first.
502 pub fn is_impl_trait(&self) -> bool {
503 matches!(self.kind, GenericParamKind::Type { synthetic: true, .. })
506 /// This can happen for `async fn`, e.g. `async fn f<'_>(&'_ self)`.
508 /// See `lifetime_to_generic_param` in `rustc_ast_lowering` for more information.
509 pub fn is_elided_lifetime(&self) -> bool {
510 matches!(self.kind, GenericParamKind::Lifetime { kind: LifetimeParamKind::Elided })
515 pub struct GenericParamCount {
516 pub lifetimes: usize,
522 /// Represents lifetimes and type parameters attached to a declaration
523 /// of a function, enum, trait, etc.
524 #[derive(Debug, HashStable_Generic)]
525 pub struct Generics<'hir> {
526 pub params: &'hir [GenericParam<'hir>],
527 pub predicates: &'hir [WherePredicate<'hir>],
528 pub has_where_clause_predicates: bool,
529 pub where_clause_span: Span,
533 impl<'hir> Generics<'hir> {
534 pub const fn empty() -> &'hir Generics<'hir> {
535 const NOPE: Generics<'_> = Generics {
538 has_where_clause_predicates: false,
539 where_clause_span: DUMMY_SP,
545 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'hir>> {
546 for param in self.params {
547 if name == param.name.ident().name {
554 pub fn spans(&self) -> MultiSpan {
555 if self.params.is_empty() {
558 self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
562 /// If there are generic parameters, return where to introduce a new one.
563 pub fn span_for_param_suggestion(&self) -> Option<Span> {
564 if self.params.iter().any(|p| self.span.contains(p.span)) {
565 // `fn foo<A>(t: impl Trait)`
566 // ^ suggest `, T: Trait` here
567 let span = self.span.with_lo(self.span.hi() - BytePos(1)).shrink_to_lo();
574 /// `Span` where further predicates would be suggested, accounting for trailing commas, like
575 /// in `fn foo<T>(t: T) where T: Foo,` so we don't suggest two trailing commas.
576 pub fn tail_span_for_predicate_suggestion(&self) -> Span {
577 let end = self.where_clause_span.shrink_to_hi();
578 if self.has_where_clause_predicates {
581 .rfind(|&p| p.in_where_clause())
582 .map_or(end, |p| p.span())
590 pub fn add_where_or_trailing_comma(&self) -> &'static str {
591 if self.has_where_clause_predicates {
593 } else if self.where_clause_span.is_empty() {
596 // No where clause predicates, but we have `where` token
601 pub fn bounds_for_param(
603 param_def_id: LocalDefId,
604 ) -> impl Iterator<Item = &WhereBoundPredicate<'hir>> {
605 self.predicates.iter().filter_map(move |pred| match pred {
606 WherePredicate::BoundPredicate(bp) if bp.is_param_bound(param_def_id.to_def_id()) => {
613 pub fn outlives_for_param(
615 param_def_id: LocalDefId,
616 ) -> impl Iterator<Item = &WhereRegionPredicate<'_>> {
617 self.predicates.iter().filter_map(move |pred| match pred {
618 WherePredicate::RegionPredicate(rp) if rp.is_param_bound(param_def_id) => Some(rp),
623 pub fn bounds_span_for_suggestions(&self, param_def_id: LocalDefId) -> Option<Span> {
624 self.bounds_for_param(param_def_id).flat_map(|bp| bp.bounds.iter().rev()).find_map(
626 // We include bounds that come from a `#[derive(_)]` but point at the user's code,
627 // as we use this method to get a span appropriate for suggestions.
628 let bs = bound.span();
629 if bs.can_be_used_for_suggestions() { Some(bs.shrink_to_hi()) } else { None }
634 pub fn span_for_predicate_removal(&self, pos: usize) -> Span {
635 let predicate = &self.predicates[pos];
636 let span = predicate.span();
638 if !predicate.in_where_clause() {
644 // We need to find out which comma to remove.
645 if pos < self.predicates.len() - 1 {
646 let next_pred = &self.predicates[pos + 1];
647 if next_pred.in_where_clause() {
648 // where T: ?Sized, Foo: Bar,
650 return span.until(next_pred.span());
655 let prev_pred = &self.predicates[pos - 1];
656 if prev_pred.in_where_clause() {
657 // where Foo: Bar, T: ?Sized,
659 return prev_pred.span().shrink_to_hi().to(span);
663 // This is the only predicate in the where clause.
666 self.where_clause_span
669 pub fn span_for_bound_removal(&self, predicate_pos: usize, bound_pos: usize) -> Span {
670 let predicate = &self.predicates[predicate_pos];
671 let bounds = predicate.bounds();
673 if bounds.len() == 1 {
674 return self.span_for_predicate_removal(predicate_pos);
677 let span = bounds[bound_pos].span();
679 // where T: ?Sized + Bar, Foo: Bar,
681 span.to(bounds[1].span().shrink_to_lo())
683 // where T: Bar + ?Sized, Foo: Bar,
685 bounds[bound_pos - 1].span().shrink_to_hi().to(span)
690 /// A single predicate in a where-clause.
691 #[derive(Debug, HashStable_Generic)]
692 pub enum WherePredicate<'hir> {
693 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
694 BoundPredicate(WhereBoundPredicate<'hir>),
695 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
696 RegionPredicate(WhereRegionPredicate<'hir>),
697 /// An equality predicate (unsupported).
698 EqPredicate(WhereEqPredicate<'hir>),
701 impl<'hir> WherePredicate<'hir> {
702 pub fn span(&self) -> Span {
704 WherePredicate::BoundPredicate(p) => p.span,
705 WherePredicate::RegionPredicate(p) => p.span,
706 WherePredicate::EqPredicate(p) => p.span,
710 pub fn in_where_clause(&self) -> bool {
712 WherePredicate::BoundPredicate(p) => p.origin == PredicateOrigin::WhereClause,
713 WherePredicate::RegionPredicate(p) => p.in_where_clause,
714 WherePredicate::EqPredicate(_) => false,
718 pub fn bounds(&self) -> GenericBounds<'hir> {
720 WherePredicate::BoundPredicate(p) => p.bounds,
721 WherePredicate::RegionPredicate(p) => p.bounds,
722 WherePredicate::EqPredicate(_) => &[],
727 #[derive(Copy, Clone, Debug, HashStable_Generic, PartialEq, Eq)]
728 pub enum PredicateOrigin {
734 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
735 #[derive(Debug, HashStable_Generic)]
736 pub struct WhereBoundPredicate<'hir> {
739 /// Origin of the predicate.
740 pub origin: PredicateOrigin,
741 /// Any generics from a `for` binding.
742 pub bound_generic_params: &'hir [GenericParam<'hir>],
743 /// The type being bounded.
744 pub bounded_ty: &'hir Ty<'hir>,
745 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
746 pub bounds: GenericBounds<'hir>,
749 impl<'hir> WhereBoundPredicate<'hir> {
750 /// Returns `true` if `param_def_id` matches the `bounded_ty` of this predicate.
751 pub fn is_param_bound(&self, param_def_id: DefId) -> bool {
752 self.bounded_ty.as_generic_param().map_or(false, |(def_id, _)| def_id == param_def_id)
756 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
757 #[derive(Debug, HashStable_Generic)]
758 pub struct WhereRegionPredicate<'hir> {
760 pub in_where_clause: bool,
761 pub lifetime: &'hir Lifetime,
762 pub bounds: GenericBounds<'hir>,
765 impl<'hir> WhereRegionPredicate<'hir> {
766 /// Returns `true` if `param_def_id` matches the `lifetime` of this predicate.
767 pub fn is_param_bound(&self, param_def_id: LocalDefId) -> bool {
768 match self.lifetime.name {
769 LifetimeName::Param(id, _) => id == param_def_id,
775 /// An equality predicate (e.g., `T = int`); currently unsupported.
776 #[derive(Debug, HashStable_Generic)]
777 pub struct WhereEqPredicate<'hir> {
779 pub lhs_ty: &'hir Ty<'hir>,
780 pub rhs_ty: &'hir Ty<'hir>,
783 /// HIR node coupled with its parent's id in the same HIR owner.
785 /// The parent is trash when the node is a HIR owner.
786 #[derive(Clone, Debug)]
787 pub struct ParentedNode<'tcx> {
788 pub parent: ItemLocalId,
789 pub node: Node<'tcx>,
792 /// Attributes owned by a HIR owner.
794 pub struct AttributeMap<'tcx> {
795 pub map: SortedMap<ItemLocalId, &'tcx [Attribute]>,
796 pub hash: Fingerprint,
799 impl<'tcx> AttributeMap<'tcx> {
800 pub const EMPTY: &'static AttributeMap<'static> =
801 &AttributeMap { map: SortedMap::new(), hash: Fingerprint::ZERO };
804 pub fn get(&self, id: ItemLocalId) -> &'tcx [Attribute] {
805 self.map.get(&id).copied().unwrap_or(&[])
809 /// Map of all HIR nodes inside the current owner.
810 /// These nodes are mapped by `ItemLocalId` alongside the index of their parent node.
811 /// The HIR tree, including bodies, is pre-hashed.
812 pub struct OwnerNodes<'tcx> {
813 /// Pre-computed hash of the full HIR.
814 pub hash_including_bodies: Fingerprint,
815 /// Pre-computed hash of the item signature, sithout recursing into the body.
816 pub hash_without_bodies: Fingerprint,
817 /// Full HIR for the current owner.
818 // The zeroth node's parent should never be accessed: the owner's parent is computed by the
819 // hir_owner_parent query. It is set to `ItemLocalId::INVALID` to force an ICE if accidentally
821 pub nodes: IndexVec<ItemLocalId, Option<ParentedNode<'tcx>>>,
822 /// Content of local bodies.
823 pub bodies: SortedMap<ItemLocalId, &'tcx Body<'tcx>>,
824 /// Non-owning definitions contained in this owner.
825 pub local_id_to_def_id: SortedMap<ItemLocalId, LocalDefId>,
828 impl<'tcx> OwnerNodes<'tcx> {
829 pub fn node(&self) -> OwnerNode<'tcx> {
830 use rustc_index::vec::Idx;
831 let node = self.nodes[ItemLocalId::new(0)].as_ref().unwrap().node;
832 let node = node.as_owner().unwrap(); // Indexing must ensure it is an OwnerNode.
837 impl fmt::Debug for OwnerNodes<'_> {
838 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
839 f.debug_struct("OwnerNodes")
840 // Do not print all the pointers to all the nodes, as it would be unreadable.
841 .field("node", &self.nodes[ItemLocalId::from_u32(0)])
847 .map(|(id, parented_node)| (id, parented_node.as_ref().map(|node| node.parent)))
848 .collect::<Vec<_>>(),
850 .field("bodies", &self.bodies)
851 .field("local_id_to_def_id", &self.local_id_to_def_id)
852 .field("hash_without_bodies", &self.hash_without_bodies)
853 .field("hash_including_bodies", &self.hash_including_bodies)
858 /// Full information resulting from lowering an AST node.
859 #[derive(Debug, HashStable_Generic)]
860 pub struct OwnerInfo<'hir> {
861 /// Contents of the HIR.
862 pub nodes: OwnerNodes<'hir>,
863 /// Map from each nested owner to its parent's local id.
864 pub parenting: FxHashMap<LocalDefId, ItemLocalId>,
865 /// Collected attributes of the HIR nodes.
866 pub attrs: AttributeMap<'hir>,
867 /// Map indicating what traits are in scope for places where this
868 /// is relevant; generated by resolve.
869 pub trait_map: FxHashMap<ItemLocalId, Box<[TraitCandidate]>>,
872 impl<'tcx> OwnerInfo<'tcx> {
874 pub fn node(&self) -> OwnerNode<'tcx> {
879 #[derive(Copy, Clone, Debug, HashStable_Generic)]
880 pub enum MaybeOwner<T> {
883 /// Used as a placeholder for unused LocalDefId.
887 impl<T> MaybeOwner<T> {
888 pub fn as_owner(self) -> Option<T> {
890 MaybeOwner::Owner(i) => Some(i),
891 MaybeOwner::NonOwner(_) | MaybeOwner::Phantom => None,
895 pub fn map<U>(self, f: impl FnOnce(T) -> U) -> MaybeOwner<U> {
897 MaybeOwner::Owner(i) => MaybeOwner::Owner(f(i)),
898 MaybeOwner::NonOwner(hir_id) => MaybeOwner::NonOwner(hir_id),
899 MaybeOwner::Phantom => MaybeOwner::Phantom,
903 pub fn unwrap(self) -> T {
905 MaybeOwner::Owner(i) => i,
906 MaybeOwner::NonOwner(_) | MaybeOwner::Phantom => panic!("Not a HIR owner"),
911 /// The top-level data structure that stores the entire contents of
912 /// the crate currently being compiled.
914 /// For more details, see the [rustc dev guide].
916 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
918 pub struct Crate<'hir> {
919 pub owners: IndexVec<LocalDefId, MaybeOwner<&'hir OwnerInfo<'hir>>>,
920 pub hir_hash: Fingerprint,
923 #[derive(Debug, HashStable_Generic)]
924 pub struct Closure<'hir> {
925 pub def_id: LocalDefId,
926 pub binder: ClosureBinder,
927 pub capture_clause: CaptureBy,
928 pub bound_generic_params: &'hir [GenericParam<'hir>],
929 pub fn_decl: &'hir FnDecl<'hir>,
931 pub fn_decl_span: Span,
932 pub movability: Option<Movability>,
935 /// A block of statements `{ .. }`, which may have a label (in this case the
936 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
937 /// the `rules` being anything but `DefaultBlock`.
938 #[derive(Debug, HashStable_Generic)]
939 pub struct Block<'hir> {
940 /// Statements in a block.
941 pub stmts: &'hir [Stmt<'hir>],
942 /// An expression at the end of the block
943 /// without a semicolon, if any.
944 pub expr: Option<&'hir Expr<'hir>>,
945 #[stable_hasher(ignore)]
947 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
948 pub rules: BlockCheckMode,
950 /// If true, then there may exist `break 'a` values that aim to
951 /// break out of this block early.
952 /// Used by `'label: {}` blocks and by `try {}` blocks.
953 pub targeted_by_break: bool,
956 impl<'hir> Block<'hir> {
957 pub fn innermost_block(&self) -> &Block<'hir> {
958 let mut block = self;
959 while let Some(Expr { kind: ExprKind::Block(inner_block, _), .. }) = block.expr {
966 #[derive(Debug, HashStable_Generic)]
967 pub struct Pat<'hir> {
968 #[stable_hasher(ignore)]
970 pub kind: PatKind<'hir>,
972 // Whether to use default binding modes.
973 // At present, this is false only for destructuring assignment.
974 pub default_binding_modes: bool,
977 impl<'hir> Pat<'hir> {
978 // FIXME(#19596) this is a workaround, but there should be a better way
979 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) -> bool {
986 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
987 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
988 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
989 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
990 Slice(before, slice, after) => {
991 before.iter().chain(slice).chain(after.iter()).all(|p| p.walk_short_(it))
996 /// Walk the pattern in left-to-right order,
997 /// short circuiting (with `.all(..)`) if `false` is returned.
999 /// Note that when visiting e.g. `Tuple(ps)`,
1000 /// if visiting `ps[0]` returns `false`,
1001 /// then `ps[1]` will not be visited.
1002 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) -> bool {
1003 self.walk_short_(&mut it)
1006 // FIXME(#19596) this is a workaround, but there should be a better way
1007 fn walk_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) {
1014 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
1015 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
1016 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
1017 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
1018 Slice(before, slice, after) => {
1019 before.iter().chain(slice).chain(after.iter()).for_each(|p| p.walk_(it))
1024 /// Walk the pattern in left-to-right order.
1026 /// If `it(pat)` returns `false`, the children are not visited.
1027 pub fn walk(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) {
1031 /// Walk the pattern in left-to-right order.
1033 /// If you always want to recurse, prefer this method over `walk`.
1034 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
1042 /// A single field in a struct pattern.
1044 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
1045 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
1046 /// except `is_shorthand` is true.
1047 #[derive(Debug, HashStable_Generic)]
1048 pub struct PatField<'hir> {
1049 #[stable_hasher(ignore)]
1051 /// The identifier for the field.
1053 /// The pattern the field is destructured to.
1054 pub pat: &'hir Pat<'hir>,
1055 pub is_shorthand: bool,
1059 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1065 impl fmt::Display for RangeEnd {
1066 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1067 f.write_str(match self {
1068 RangeEnd::Included => "..=",
1069 RangeEnd::Excluded => "..",
1074 // Equivalent to `Option<usize>`. That type takes up 16 bytes on 64-bit, but
1075 // this type only takes up 4 bytes, at the cost of being restricted to a
1076 // maximum value of `u32::MAX - 1`. In practice, this is more than enough.
1077 #[derive(Clone, Copy, PartialEq, Eq, Hash, HashStable_Generic)]
1078 pub struct DotDotPos(u32);
1081 // Panics if n >= u32::MAX.
1082 pub fn new(n: Option<usize>) -> Self {
1085 assert!(n < u32::MAX as usize);
1088 None => Self(u32::MAX),
1092 pub fn as_opt_usize(&self) -> Option<usize> {
1093 if self.0 == u32::MAX { None } else { Some(self.0 as usize) }
1097 impl fmt::Debug for DotDotPos {
1098 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1099 self.as_opt_usize().fmt(f)
1103 #[derive(Debug, HashStable_Generic)]
1104 pub enum PatKind<'hir> {
1105 /// Represents a wildcard pattern (i.e., `_`).
1108 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
1109 /// The `HirId` is the canonical ID for the variable being bound,
1110 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
1111 /// which is the pattern ID of the first `x`.
1112 Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
1114 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
1115 /// The `bool` is `true` in the presence of a `..`.
1116 Struct(QPath<'hir>, &'hir [PatField<'hir>], bool),
1118 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
1119 /// If the `..` pattern fragment is present, then `DotDotPos` denotes its position.
1120 /// `0 <= position <= subpats.len()`
1121 TupleStruct(QPath<'hir>, &'hir [Pat<'hir>], DotDotPos),
1123 /// An or-pattern `A | B | C`.
1124 /// Invariant: `pats.len() >= 2`.
1125 Or(&'hir [Pat<'hir>]),
1127 /// A path pattern for a unit struct/variant or a (maybe-associated) constant.
1130 /// A tuple pattern (e.g., `(a, b)`).
1131 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
1132 /// `0 <= position <= subpats.len()`
1133 Tuple(&'hir [Pat<'hir>], DotDotPos),
1135 /// A `box` pattern.
1136 Box(&'hir Pat<'hir>),
1138 /// A reference pattern (e.g., `&mut (a, b)`).
1139 Ref(&'hir Pat<'hir>, Mutability),
1142 Lit(&'hir Expr<'hir>),
1144 /// A range pattern (e.g., `1..=2` or `1..2`).
1145 Range(Option<&'hir Expr<'hir>>, Option<&'hir Expr<'hir>>, RangeEnd),
1147 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
1149 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
1150 /// If `slice` exists, then `after` can be non-empty.
1152 /// The representation for e.g., `[a, b, .., c, d]` is:
1153 /// ```ignore (illustrative)
1154 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
1156 Slice(&'hir [Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [Pat<'hir>]),
1159 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1160 pub enum BinOpKind {
1161 /// The `+` operator (addition).
1163 /// The `-` operator (subtraction).
1165 /// The `*` operator (multiplication).
1167 /// The `/` operator (division).
1169 /// The `%` operator (modulus).
1171 /// The `&&` operator (logical and).
1173 /// The `||` operator (logical or).
1175 /// The `^` operator (bitwise xor).
1177 /// The `&` operator (bitwise and).
1179 /// The `|` operator (bitwise or).
1181 /// The `<<` operator (shift left).
1183 /// The `>>` operator (shift right).
1185 /// The `==` operator (equality).
1187 /// The `<` operator (less than).
1189 /// The `<=` operator (less than or equal to).
1191 /// The `!=` operator (not equal to).
1193 /// The `>=` operator (greater than or equal to).
1195 /// The `>` operator (greater than).
1200 pub fn as_str(self) -> &'static str {
1202 BinOpKind::Add => "+",
1203 BinOpKind::Sub => "-",
1204 BinOpKind::Mul => "*",
1205 BinOpKind::Div => "/",
1206 BinOpKind::Rem => "%",
1207 BinOpKind::And => "&&",
1208 BinOpKind::Or => "||",
1209 BinOpKind::BitXor => "^",
1210 BinOpKind::BitAnd => "&",
1211 BinOpKind::BitOr => "|",
1212 BinOpKind::Shl => "<<",
1213 BinOpKind::Shr => ">>",
1214 BinOpKind::Eq => "==",
1215 BinOpKind::Lt => "<",
1216 BinOpKind::Le => "<=",
1217 BinOpKind::Ne => "!=",
1218 BinOpKind::Ge => ">=",
1219 BinOpKind::Gt => ">",
1223 pub fn is_lazy(self) -> bool {
1224 matches!(self, BinOpKind::And | BinOpKind::Or)
1227 pub fn is_shift(self) -> bool {
1228 matches!(self, BinOpKind::Shl | BinOpKind::Shr)
1231 pub fn is_comparison(self) -> bool {
1238 | BinOpKind::Ge => true,
1250 | BinOpKind::Shr => false,
1254 /// Returns `true` if the binary operator takes its arguments by value.
1255 pub fn is_by_value(self) -> bool {
1256 !self.is_comparison()
1260 impl Into<ast::BinOpKind> for BinOpKind {
1261 fn into(self) -> ast::BinOpKind {
1263 BinOpKind::Add => ast::BinOpKind::Add,
1264 BinOpKind::Sub => ast::BinOpKind::Sub,
1265 BinOpKind::Mul => ast::BinOpKind::Mul,
1266 BinOpKind::Div => ast::BinOpKind::Div,
1267 BinOpKind::Rem => ast::BinOpKind::Rem,
1268 BinOpKind::And => ast::BinOpKind::And,
1269 BinOpKind::Or => ast::BinOpKind::Or,
1270 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1271 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1272 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1273 BinOpKind::Shl => ast::BinOpKind::Shl,
1274 BinOpKind::Shr => ast::BinOpKind::Shr,
1275 BinOpKind::Eq => ast::BinOpKind::Eq,
1276 BinOpKind::Lt => ast::BinOpKind::Lt,
1277 BinOpKind::Le => ast::BinOpKind::Le,
1278 BinOpKind::Ne => ast::BinOpKind::Ne,
1279 BinOpKind::Ge => ast::BinOpKind::Ge,
1280 BinOpKind::Gt => ast::BinOpKind::Gt,
1285 pub type BinOp = Spanned<BinOpKind>;
1287 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1289 /// The `*` operator (dereferencing).
1291 /// The `!` operator (logical negation).
1293 /// The `-` operator (negation).
1298 pub fn as_str(self) -> &'static str {
1306 /// Returns `true` if the unary operator takes its argument by value.
1307 pub fn is_by_value(self) -> bool {
1308 matches!(self, Self::Neg | Self::Not)
1313 #[derive(Debug, HashStable_Generic)]
1314 pub struct Stmt<'hir> {
1316 pub kind: StmtKind<'hir>,
1320 /// The contents of a statement.
1321 #[derive(Debug, HashStable_Generic)]
1322 pub enum StmtKind<'hir> {
1323 /// A local (`let`) binding.
1324 Local(&'hir Local<'hir>),
1326 /// An item binding.
1329 /// An expression without a trailing semi-colon (must have unit type).
1330 Expr(&'hir Expr<'hir>),
1332 /// An expression with a trailing semi-colon (may have any type).
1333 Semi(&'hir Expr<'hir>),
1336 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <init>;`).
1337 #[derive(Debug, HashStable_Generic)]
1338 pub struct Local<'hir> {
1339 pub pat: &'hir Pat<'hir>,
1340 /// Type annotation, if any (otherwise the type will be inferred).
1341 pub ty: Option<&'hir Ty<'hir>>,
1342 /// Initializer expression to set the value, if any.
1343 pub init: Option<&'hir Expr<'hir>>,
1344 /// Else block for a `let...else` binding.
1345 pub els: Option<&'hir Block<'hir>>,
1348 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1349 /// desugaring. Otherwise will be `Normal`.
1350 pub source: LocalSource,
1353 /// Represents a single arm of a `match` expression, e.g.
1354 /// `<pat> (if <guard>) => <body>`.
1355 #[derive(Debug, HashStable_Generic)]
1356 pub struct Arm<'hir> {
1357 #[stable_hasher(ignore)]
1360 /// If this pattern and the optional guard matches, then `body` is evaluated.
1361 pub pat: &'hir Pat<'hir>,
1362 /// Optional guard clause.
1363 pub guard: Option<Guard<'hir>>,
1364 /// The expression the arm evaluates to if this arm matches.
1365 pub body: &'hir Expr<'hir>,
1368 /// Represents a `let <pat>[: <ty>] = <expr>` expression (not a Local), occurring in an `if-let` or
1369 /// `let-else`, evaluating to a boolean. Typically the pattern is refutable.
1371 /// In an if-let, imagine it as `if (let <pat> = <expr>) { ... }`; in a let-else, it is part of the
1372 /// desugaring to if-let. Only let-else supports the type annotation at present.
1373 #[derive(Debug, HashStable_Generic)]
1374 pub struct Let<'hir> {
1377 pub pat: &'hir Pat<'hir>,
1378 pub ty: Option<&'hir Ty<'hir>>,
1379 pub init: &'hir Expr<'hir>,
1382 #[derive(Debug, HashStable_Generic)]
1383 pub enum Guard<'hir> {
1384 If(&'hir Expr<'hir>),
1385 IfLet(&'hir Let<'hir>),
1388 impl<'hir> Guard<'hir> {
1389 /// Returns the body of the guard
1391 /// In other words, returns the e in either of the following:
1394 /// - `if let x = e`
1395 pub fn body(&self) -> &'hir Expr<'hir> {
1397 Guard::If(e) | Guard::IfLet(Let { init: e, .. }) => e,
1402 #[derive(Debug, HashStable_Generic)]
1403 pub struct ExprField<'hir> {
1404 #[stable_hasher(ignore)]
1407 pub expr: &'hir Expr<'hir>,
1409 pub is_shorthand: bool,
1412 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1413 pub enum BlockCheckMode {
1415 UnsafeBlock(UnsafeSource),
1418 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1419 pub enum UnsafeSource {
1424 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
1429 /// The body of a function, closure, or constant value. In the case of
1430 /// a function, the body contains not only the function body itself
1431 /// (which is an expression), but also the argument patterns, since
1432 /// those are something that the caller doesn't really care about.
1437 /// fn foo((x, y): (u32, u32)) -> u32 {
1442 /// Here, the `Body` associated with `foo()` would contain:
1444 /// - an `params` array containing the `(x, y)` pattern
1445 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1446 /// - `generator_kind` would be `None`
1448 /// All bodies have an **owner**, which can be accessed via the HIR
1449 /// map using `body_owner_def_id()`.
1450 #[derive(Debug, HashStable_Generic)]
1451 pub struct Body<'hir> {
1452 pub params: &'hir [Param<'hir>],
1453 pub value: &'hir Expr<'hir>,
1454 pub generator_kind: Option<GeneratorKind>,
1457 impl<'hir> Body<'hir> {
1458 pub fn id(&self) -> BodyId {
1459 BodyId { hir_id: self.value.hir_id }
1462 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1467 /// The type of source expression that caused this generator to be created.
1468 #[derive(Clone, PartialEq, PartialOrd, Eq, Hash, Debug, Copy)]
1469 #[derive(HashStable_Generic, Encodable, Decodable)]
1470 pub enum GeneratorKind {
1471 /// An explicit `async` block or the body of an async function.
1472 Async(AsyncGeneratorKind),
1474 /// A generator literal created via a `yield` inside a closure.
1478 impl fmt::Display for GeneratorKind {
1479 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1481 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1482 GeneratorKind::Gen => f.write_str("generator"),
1487 impl GeneratorKind {
1488 pub fn descr(&self) -> &'static str {
1490 GeneratorKind::Async(ask) => ask.descr(),
1491 GeneratorKind::Gen => "generator",
1496 /// In the case of a generator created as part of an async construct,
1497 /// which kind of async construct caused it to be created?
1499 /// This helps error messages but is also used to drive coercions in
1500 /// type-checking (see #60424).
1501 #[derive(Clone, PartialEq, PartialOrd, Eq, Hash, Debug, Copy)]
1502 #[derive(HashStable_Generic, Encodable, Decodable)]
1503 pub enum AsyncGeneratorKind {
1504 /// An explicit `async` block written by the user.
1507 /// An explicit `async` closure written by the user.
1510 /// The `async` block generated as the body of an async function.
1514 impl fmt::Display for AsyncGeneratorKind {
1515 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1516 f.write_str(match self {
1517 AsyncGeneratorKind::Block => "`async` block",
1518 AsyncGeneratorKind::Closure => "`async` closure body",
1519 AsyncGeneratorKind::Fn => "`async fn` body",
1524 impl AsyncGeneratorKind {
1525 pub fn descr(&self) -> &'static str {
1527 AsyncGeneratorKind::Block => "`async` block",
1528 AsyncGeneratorKind::Closure => "`async` closure body",
1529 AsyncGeneratorKind::Fn => "`async fn` body",
1534 #[derive(Copy, Clone, Debug)]
1535 pub enum BodyOwnerKind {
1536 /// Functions and methods.
1542 /// Constants and associated constants.
1545 /// Initializer of a `static` item.
1549 impl BodyOwnerKind {
1550 pub fn is_fn_or_closure(self) -> bool {
1552 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1553 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1558 /// The kind of an item that requires const-checking.
1559 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1560 pub enum ConstContext {
1564 /// A `static` or `static mut`.
1567 /// A `const`, associated `const`, or other const context.
1569 /// Other contexts include:
1570 /// - Array length expressions
1571 /// - Enum discriminants
1572 /// - Const generics
1574 /// For the most part, other contexts are treated just like a regular `const`, so they are
1575 /// lumped into the same category.
1580 /// A description of this const context that can appear between backticks in an error message.
1582 /// E.g. `const` or `static mut`.
1583 pub fn keyword_name(self) -> &'static str {
1585 Self::Const => "const",
1586 Self::Static(Mutability::Not) => "static",
1587 Self::Static(Mutability::Mut) => "static mut",
1588 Self::ConstFn => "const fn",
1593 /// A colloquial, trivially pluralizable description of this const context for use in error
1595 impl fmt::Display for ConstContext {
1596 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1598 Self::Const => write!(f, "constant"),
1599 Self::Static(_) => write!(f, "static"),
1600 Self::ConstFn => write!(f, "constant function"),
1605 // NOTE: `IntoDiagnosticArg` impl for `ConstContext` lives in `rustc_errors`
1606 // due to a cyclical dependency between hir that crate.
1609 pub type Lit = Spanned<LitKind>;
1611 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1618 pub fn hir_id(&self) -> HirId {
1620 &ArrayLen::Infer(hir_id, _) | &ArrayLen::Body(AnonConst { hir_id, .. }) => hir_id,
1625 /// A constant (expression) that's not an item or associated item,
1626 /// but needs its own `DefId` for type-checking, const-eval, etc.
1627 /// These are usually found nested inside types (e.g., array lengths)
1628 /// or expressions (e.g., repeat counts), and also used to define
1629 /// explicit discriminant values for enum variants.
1631 /// You can check if this anon const is a default in a const param
1632 /// `const N: usize = { ... }` with `tcx.hir().opt_const_param_default_param_def_id(..)`
1633 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1634 pub struct AnonConst {
1636 pub def_id: LocalDefId,
1641 #[derive(Debug, HashStable_Generic)]
1642 pub struct Expr<'hir> {
1644 pub kind: ExprKind<'hir>,
1649 pub fn precedence(&self) -> ExprPrecedence {
1651 ExprKind::Box(_) => ExprPrecedence::Box,
1652 ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1653 ExprKind::Array(_) => ExprPrecedence::Array,
1654 ExprKind::Call(..) => ExprPrecedence::Call,
1655 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1656 ExprKind::Tup(_) => ExprPrecedence::Tup,
1657 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1658 ExprKind::Unary(..) => ExprPrecedence::Unary,
1659 ExprKind::Lit(_) => ExprPrecedence::Lit,
1660 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1661 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1662 ExprKind::If(..) => ExprPrecedence::If,
1663 ExprKind::Let(..) => ExprPrecedence::Let,
1664 ExprKind::Loop(..) => ExprPrecedence::Loop,
1665 ExprKind::Match(..) => ExprPrecedence::Match,
1666 ExprKind::Closure { .. } => ExprPrecedence::Closure,
1667 ExprKind::Block(..) => ExprPrecedence::Block,
1668 ExprKind::Assign(..) => ExprPrecedence::Assign,
1669 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1670 ExprKind::Field(..) => ExprPrecedence::Field,
1671 ExprKind::Index(..) => ExprPrecedence::Index,
1672 ExprKind::Path(..) => ExprPrecedence::Path,
1673 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1674 ExprKind::Break(..) => ExprPrecedence::Break,
1675 ExprKind::Continue(..) => ExprPrecedence::Continue,
1676 ExprKind::Ret(..) => ExprPrecedence::Ret,
1677 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1678 ExprKind::Struct(..) => ExprPrecedence::Struct,
1679 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1680 ExprKind::Yield(..) => ExprPrecedence::Yield,
1681 ExprKind::Err => ExprPrecedence::Err,
1685 // Whether this looks like a place expr, without checking for deref
1687 // This will return `true` in some potentially surprising cases such as
1688 // `CONSTANT.field`.
1689 pub fn is_syntactic_place_expr(&self) -> bool {
1690 self.is_place_expr(|_| true)
1693 /// Whether this is a place expression.
1695 /// `allow_projections_from` should return `true` if indexing a field or index expression based
1696 /// on the given expression should be considered a place expression.
1697 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1699 ExprKind::Path(QPath::Resolved(_, ref path)) => {
1700 matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static(_), _) | Res::Err)
1703 // Type ascription inherits its place expression kind from its
1705 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1706 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1708 ExprKind::Unary(UnOp::Deref, _) => true,
1710 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1711 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1714 // Lang item paths cannot currently be local variables or statics.
1715 ExprKind::Path(QPath::LangItem(..)) => false,
1717 // Partially qualified paths in expressions can only legally
1718 // refer to associated items which are always rvalues.
1719 ExprKind::Path(QPath::TypeRelative(..))
1720 | ExprKind::Call(..)
1721 | ExprKind::MethodCall(..)
1722 | ExprKind::Struct(..)
1725 | ExprKind::Match(..)
1726 | ExprKind::Closure { .. }
1727 | ExprKind::Block(..)
1728 | ExprKind::Repeat(..)
1729 | ExprKind::Array(..)
1730 | ExprKind::Break(..)
1731 | ExprKind::Continue(..)
1734 | ExprKind::Loop(..)
1735 | ExprKind::Assign(..)
1736 | ExprKind::InlineAsm(..)
1737 | ExprKind::AssignOp(..)
1739 | ExprKind::ConstBlock(..)
1740 | ExprKind::Unary(..)
1742 | ExprKind::AddrOf(..)
1743 | ExprKind::Binary(..)
1744 | ExprKind::Yield(..)
1745 | ExprKind::Cast(..)
1746 | ExprKind::DropTemps(..)
1747 | ExprKind::Err => false,
1751 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1752 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1753 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1754 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1755 /// beyond remembering to call this function before doing analysis on it.
1756 pub fn peel_drop_temps(&self) -> &Self {
1757 let mut expr = self;
1758 while let ExprKind::DropTemps(inner) = &expr.kind {
1764 pub fn peel_blocks(&self) -> &Self {
1765 let mut expr = self;
1766 while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind {
1772 pub fn can_have_side_effects(&self) -> bool {
1773 match self.peel_drop_temps().kind {
1774 ExprKind::Path(_) | ExprKind::Lit(_) => false,
1775 ExprKind::Type(base, _)
1776 | ExprKind::Unary(_, base)
1777 | ExprKind::Field(base, _)
1778 | ExprKind::Index(base, _)
1779 | ExprKind::AddrOf(.., base)
1780 | ExprKind::Cast(base, _) => {
1781 // This isn't exactly true for `Index` and all `Unary`, but we are using this
1782 // method exclusively for diagnostics and there's a *cultural* pressure against
1783 // them being used only for its side-effects.
1784 base.can_have_side_effects()
1786 ExprKind::Struct(_, fields, init) => fields
1788 .map(|field| field.expr)
1789 .chain(init.into_iter())
1790 .all(|e| e.can_have_side_effects()),
1792 ExprKind::Array(args)
1793 | ExprKind::Tup(args)
1797 ExprKind::Path(QPath::Resolved(
1799 Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. },
1804 ) => args.iter().all(|arg| arg.can_have_side_effects()),
1806 | ExprKind::Match(..)
1807 | ExprKind::MethodCall(..)
1808 | ExprKind::Call(..)
1809 | ExprKind::Closure { .. }
1810 | ExprKind::Block(..)
1811 | ExprKind::Repeat(..)
1812 | ExprKind::Break(..)
1813 | ExprKind::Continue(..)
1816 | ExprKind::Loop(..)
1817 | ExprKind::Assign(..)
1818 | ExprKind::InlineAsm(..)
1819 | ExprKind::AssignOp(..)
1820 | ExprKind::ConstBlock(..)
1822 | ExprKind::Binary(..)
1823 | ExprKind::Yield(..)
1824 | ExprKind::DropTemps(..)
1825 | ExprKind::Err => true,
1829 // To a first-order approximation, is this a pattern
1830 pub fn is_approximately_pattern(&self) -> bool {
1833 | ExprKind::Array(_)
1834 | ExprKind::Call(..)
1838 | ExprKind::Struct(..) => true,
1843 pub fn method_ident(&self) -> Option<Ident> {
1845 ExprKind::MethodCall(receiver_method, ..) => Some(receiver_method.ident),
1846 ExprKind::Unary(_, expr) | ExprKind::AddrOf(.., expr) => expr.method_ident(),
1852 /// Checks if the specified expression is a built-in range literal.
1853 /// (See: `LoweringContext::lower_expr()`).
1854 pub fn is_range_literal(expr: &Expr<'_>) -> bool {
1856 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1857 ExprKind::Struct(ref qpath, _, _) => matches!(
1862 | LangItem::RangeFrom
1863 | LangItem::RangeFull
1864 | LangItem::RangeToInclusive,
1869 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1870 ExprKind::Call(ref func, _) => {
1871 matches!(func.kind, ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, ..)))
1878 #[derive(Debug, HashStable_Generic)]
1879 pub enum ExprKind<'hir> {
1880 /// A `box x` expression.
1881 Box(&'hir Expr<'hir>),
1882 /// Allow anonymous constants from an inline `const` block
1883 ConstBlock(AnonConst),
1884 /// An array (e.g., `[a, b, c, d]`).
1885 Array(&'hir [Expr<'hir>]),
1886 /// A function call.
1888 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1889 /// and the second field is the list of arguments.
1890 /// This also represents calling the constructor of
1891 /// tuple-like ADTs such as tuple structs and enum variants.
1892 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1893 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1895 /// The `PathSegment` represents the method name and its generic arguments
1896 /// (within the angle brackets).
1897 /// The `&Expr` is the expression that evaluates
1898 /// to the object on which the method is being called on (the receiver),
1899 /// and the `&[Expr]` is the rest of the arguments.
1900 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1901 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, x, [a, b, c, d], span)`.
1902 /// The final `Span` represents the span of the function and arguments
1903 /// (e.g. `foo::<Bar, Baz>(a, b, c, d)` in `x.foo::<Bar, Baz>(a, b, c, d)`
1905 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1906 /// the `hir_id` of the `MethodCall` node itself.
1908 /// [`type_dependent_def_id`]: ../../rustc_middle/ty/struct.TypeckResults.html#method.type_dependent_def_id
1909 MethodCall(&'hir PathSegment<'hir>, &'hir Expr<'hir>, &'hir [Expr<'hir>], Span),
1910 /// A tuple (e.g., `(a, b, c, d)`).
1911 Tup(&'hir [Expr<'hir>]),
1912 /// A binary operation (e.g., `a + b`, `a * b`).
1913 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1914 /// A unary operation (e.g., `!x`, `*x`).
1915 Unary(UnOp, &'hir Expr<'hir>),
1916 /// A literal (e.g., `1`, `"foo"`).
1918 /// A cast (e.g., `foo as f64`).
1919 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1920 /// A type reference (e.g., `Foo`).
1921 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1922 /// Wraps the expression in a terminating scope.
1923 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1925 /// This construct only exists to tweak the drop order in HIR lowering.
1926 /// An example of that is the desugaring of `for` loops.
1927 DropTemps(&'hir Expr<'hir>),
1928 /// A `let $pat = $expr` expression.
1930 /// These are not `Local` and only occur as expressions.
1931 /// The `let Some(x) = foo()` in `if let Some(x) = foo()` is an example of `Let(..)`.
1932 Let(&'hir Let<'hir>),
1933 /// An `if` block, with an optional else block.
1935 /// I.e., `if <expr> { <expr> } else { <expr> }`.
1936 If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
1937 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1939 /// I.e., `'label: loop { <block> }`.
1941 /// The `Span` is the loop header (`for x in y`/`while let pat = expr`).
1942 Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span),
1943 /// A `match` block, with a source that indicates whether or not it is
1944 /// the result of a desugaring, and if so, which kind.
1945 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1946 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1948 /// The `Span` is the argument block `|...|`.
1950 /// This may also be a generator literal or an `async block` as indicated by the
1951 /// `Option<Movability>`.
1952 Closure(&'hir Closure<'hir>),
1953 /// A block (e.g., `'label: { ... }`).
1954 Block(&'hir Block<'hir>, Option<Label>),
1956 /// An assignment (e.g., `a = foo()`).
1957 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1958 /// An assignment with an operator.
1961 AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1962 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1963 Field(&'hir Expr<'hir>, Ident),
1964 /// An indexing operation (`foo[2]`).
1965 Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1967 /// Path to a definition, possibly containing lifetime or type parameters.
1970 /// A referencing operation (i.e., `&a` or `&mut a`).
1971 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1972 /// A `break`, with an optional label to break.
1973 Break(Destination, Option<&'hir Expr<'hir>>),
1974 /// A `continue`, with an optional label.
1975 Continue(Destination),
1976 /// A `return`, with an optional value to be returned.
1977 Ret(Option<&'hir Expr<'hir>>),
1979 /// Inline assembly (from `asm!`), with its outputs and inputs.
1980 InlineAsm(&'hir InlineAsm<'hir>),
1982 /// A struct or struct-like variant literal expression.
1984 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1985 /// where `base` is the `Option<Expr>`.
1986 Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], Option<&'hir Expr<'hir>>),
1988 /// An array literal constructed from one repeated element.
1990 /// E.g., `[1; 5]`. The first expression is the element
1991 /// to be repeated; the second is the number of times to repeat it.
1992 Repeat(&'hir Expr<'hir>, ArrayLen),
1994 /// A suspension point for generators (i.e., `yield <expr>`).
1995 Yield(&'hir Expr<'hir>, YieldSource),
1997 /// A placeholder for an expression that wasn't syntactically well formed in some way.
2001 /// Represents an optionally `Self`-qualified value/type path or associated extension.
2003 /// To resolve the path to a `DefId`, call [`qpath_res`].
2005 /// [`qpath_res`]: ../../rustc_middle/ty/struct.TypeckResults.html#method.qpath_res
2006 #[derive(Debug, HashStable_Generic)]
2007 pub enum QPath<'hir> {
2008 /// Path to a definition, optionally "fully-qualified" with a `Self`
2009 /// type, if the path points to an associated item in a trait.
2011 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
2012 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
2013 /// even though they both have the same two-segment `Clone::clone` `Path`.
2014 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
2016 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
2017 /// Will be resolved by type-checking to an associated item.
2019 /// UFCS source paths can desugar into this, with `Vec::new` turning into
2020 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
2021 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
2022 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
2024 /// Reference to a `#[lang = "foo"]` item. `HirId` of the inner expr.
2025 LangItem(LangItem, Span, Option<HirId>),
2028 impl<'hir> QPath<'hir> {
2029 /// Returns the span of this `QPath`.
2030 pub fn span(&self) -> Span {
2032 QPath::Resolved(_, path) => path.span,
2033 QPath::TypeRelative(qself, ps) => qself.span.to(ps.ident.span),
2034 QPath::LangItem(_, span, _) => span,
2038 /// Returns the span of the qself of this `QPath`. For example, `()` in
2039 /// `<() as Trait>::method`.
2040 pub fn qself_span(&self) -> Span {
2042 QPath::Resolved(_, path) => path.span,
2043 QPath::TypeRelative(qself, _) => qself.span,
2044 QPath::LangItem(_, span, _) => span,
2048 /// Returns the span of the last segment of this `QPath`. For example, `method` in
2049 /// `<() as Trait>::method`.
2050 pub fn last_segment_span(&self) -> Span {
2052 QPath::Resolved(_, path) => path.segments.last().unwrap().ident.span,
2053 QPath::TypeRelative(_, segment) => segment.ident.span,
2054 QPath::LangItem(_, span, _) => span,
2059 /// Hints at the original code for a let statement.
2060 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2061 pub enum LocalSource {
2062 /// A `match _ { .. }`.
2064 /// When lowering async functions, we create locals within the `async move` so that
2065 /// all parameters are dropped after the future is polled.
2067 /// ```ignore (pseudo-Rust)
2068 /// async fn foo(<pattern> @ x: Type) {
2070 /// let <pattern> = x;
2075 /// A desugared `<expr>.await`.
2077 /// A desugared `expr = expr`, where the LHS is a tuple, struct or array.
2078 /// The span is that of the `=` sign.
2079 AssignDesugar(Span),
2082 /// Hints at the original code for a `match _ { .. }`.
2083 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
2084 #[derive(HashStable_Generic)]
2085 pub enum MatchSource {
2086 /// A `match _ { .. }`.
2088 /// A desugared `for _ in _ { .. }` loop.
2090 /// A desugared `?` operator.
2092 /// A desugared `<expr>.await`.
2098 pub const fn name(self) -> &'static str {
2102 ForLoopDesugar => "for",
2104 AwaitDesugar => ".await",
2109 /// The loop type that yielded an `ExprKind::Loop`.
2110 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2111 pub enum LoopSource {
2112 /// A `loop { .. }` loop.
2114 /// A `while _ { .. }` loop.
2116 /// A `for _ in _ { .. }` loop.
2121 pub fn name(self) -> &'static str {
2123 LoopSource::Loop => "loop",
2124 LoopSource::While => "while",
2125 LoopSource::ForLoop => "for",
2130 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2131 pub enum LoopIdError {
2133 UnlabeledCfInWhileCondition,
2137 impl fmt::Display for LoopIdError {
2138 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2139 f.write_str(match self {
2140 LoopIdError::OutsideLoopScope => "not inside loop scope",
2141 LoopIdError::UnlabeledCfInWhileCondition => {
2142 "unlabeled control flow (break or continue) in while condition"
2144 LoopIdError::UnresolvedLabel => "label not found",
2149 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2150 pub struct Destination {
2151 // This is `Some(_)` iff there is an explicit user-specified `label
2152 pub label: Option<Label>,
2154 // These errors are caught and then reported during the diagnostics pass in
2155 // librustc_passes/loops.rs
2156 pub target_id: Result<HirId, LoopIdError>,
2159 /// The yield kind that caused an `ExprKind::Yield`.
2160 #[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
2161 pub enum YieldSource {
2162 /// An `<expr>.await`.
2163 Await { expr: Option<HirId> },
2164 /// A plain `yield`.
2169 pub fn is_await(&self) -> bool {
2170 matches!(self, YieldSource::Await { .. })
2174 impl fmt::Display for YieldSource {
2175 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2176 f.write_str(match self {
2177 YieldSource::Await { .. } => "`await`",
2178 YieldSource::Yield => "`yield`",
2183 impl From<GeneratorKind> for YieldSource {
2184 fn from(kind: GeneratorKind) -> Self {
2186 // Guess based on the kind of the current generator.
2187 GeneratorKind::Gen => Self::Yield,
2188 GeneratorKind::Async(_) => Self::Await { expr: None },
2193 // N.B., if you change this, you'll probably want to change the corresponding
2194 // type structure in middle/ty.rs as well.
2195 #[derive(Debug, HashStable_Generic)]
2196 pub struct MutTy<'hir> {
2197 pub ty: &'hir Ty<'hir>,
2198 pub mutbl: Mutability,
2201 /// Represents a function's signature in a trait declaration,
2202 /// trait implementation, or a free function.
2203 #[derive(Debug, HashStable_Generic)]
2204 pub struct FnSig<'hir> {
2205 pub header: FnHeader,
2206 pub decl: &'hir FnDecl<'hir>,
2210 // The bodies for items are stored "out of line", in a separate
2211 // hashmap in the `Crate`. Here we just record the hir-id of the item
2212 // so it can fetched later.
2213 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2214 pub struct TraitItemId {
2215 pub owner_id: OwnerId,
2220 pub fn hir_id(&self) -> HirId {
2221 // Items are always HIR owners.
2222 HirId::make_owner(self.owner_id.def_id)
2226 /// Represents an item declaration within a trait declaration,
2227 /// possibly including a default implementation. A trait item is
2228 /// either required (meaning it doesn't have an implementation, just a
2229 /// signature) or provided (meaning it has a default implementation).
2230 #[derive(Debug, HashStable_Generic)]
2231 pub struct TraitItem<'hir> {
2233 pub owner_id: OwnerId,
2234 pub generics: &'hir Generics<'hir>,
2235 pub kind: TraitItemKind<'hir>,
2237 pub defaultness: Defaultness,
2240 impl TraitItem<'_> {
2242 pub fn hir_id(&self) -> HirId {
2243 // Items are always HIR owners.
2244 HirId::make_owner(self.owner_id.def_id)
2247 pub fn trait_item_id(&self) -> TraitItemId {
2248 TraitItemId { owner_id: self.owner_id }
2252 /// Represents a trait method's body (or just argument names).
2253 #[derive(Encodable, Debug, HashStable_Generic)]
2254 pub enum TraitFn<'hir> {
2255 /// No default body in the trait, just a signature.
2256 Required(&'hir [Ident]),
2258 /// Both signature and body are provided in the trait.
2262 /// Represents a trait method or associated constant or type
2263 #[derive(Debug, HashStable_Generic)]
2264 pub enum TraitItemKind<'hir> {
2265 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
2266 Const(&'hir Ty<'hir>, Option<BodyId>),
2267 /// An associated function with an optional body.
2268 Fn(FnSig<'hir>, TraitFn<'hir>),
2269 /// An associated type with (possibly empty) bounds and optional concrete
2271 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
2274 // The bodies for items are stored "out of line", in a separate
2275 // hashmap in the `Crate`. Here we just record the hir-id of the item
2276 // so it can fetched later.
2277 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2278 pub struct ImplItemId {
2279 pub owner_id: OwnerId,
2284 pub fn hir_id(&self) -> HirId {
2285 // Items are always HIR owners.
2286 HirId::make_owner(self.owner_id.def_id)
2290 /// Represents anything within an `impl` block.
2291 #[derive(Debug, HashStable_Generic)]
2292 pub struct ImplItem<'hir> {
2294 pub owner_id: OwnerId,
2295 pub generics: &'hir Generics<'hir>,
2296 pub kind: ImplItemKind<'hir>,
2297 pub defaultness: Defaultness,
2304 pub fn hir_id(&self) -> HirId {
2305 // Items are always HIR owners.
2306 HirId::make_owner(self.owner_id.def_id)
2309 pub fn impl_item_id(&self) -> ImplItemId {
2310 ImplItemId { owner_id: self.owner_id }
2314 /// Represents various kinds of content within an `impl`.
2315 #[derive(Debug, HashStable_Generic)]
2316 pub enum ImplItemKind<'hir> {
2317 /// An associated constant of the given type, set to the constant result
2318 /// of the expression.
2319 Const(&'hir Ty<'hir>, BodyId),
2320 /// An associated function implementation with the given signature and body.
2321 Fn(FnSig<'hir>, BodyId),
2322 /// An associated type.
2323 Type(&'hir Ty<'hir>),
2326 // The name of the associated type for `Fn` return types.
2327 pub const FN_OUTPUT_NAME: Symbol = sym::Output;
2329 /// Bind a type to an associated type (i.e., `A = Foo`).
2331 /// Bindings like `A: Debug` are represented as a special type `A =
2332 /// $::Debug` that is understood by the astconv code.
2334 /// FIXME(alexreg): why have a separate type for the binding case,
2335 /// wouldn't it be better to make the `ty` field an enum like the
2338 /// ```ignore (pseudo-rust)
2339 /// enum TypeBindingKind {
2344 #[derive(Debug, HashStable_Generic)]
2345 pub struct TypeBinding<'hir> {
2348 pub gen_args: &'hir GenericArgs<'hir>,
2349 pub kind: TypeBindingKind<'hir>,
2353 #[derive(Debug, HashStable_Generic)]
2354 pub enum Term<'hir> {
2359 impl<'hir> From<&'hir Ty<'hir>> for Term<'hir> {
2360 fn from(ty: &'hir Ty<'hir>) -> Self {
2365 impl<'hir> From<AnonConst> for Term<'hir> {
2366 fn from(c: AnonConst) -> Self {
2371 // Represents the two kinds of type bindings.
2372 #[derive(Debug, HashStable_Generic)]
2373 pub enum TypeBindingKind<'hir> {
2374 /// E.g., `Foo<Bar: Send>`.
2375 Constraint { bounds: &'hir [GenericBound<'hir>] },
2376 /// E.g., `Foo<Bar = ()>`, `Foo<Bar = ()>`
2377 Equality { term: Term<'hir> },
2380 impl TypeBinding<'_> {
2381 pub fn ty(&self) -> &Ty<'_> {
2383 TypeBindingKind::Equality { term: Term::Ty(ref ty) } => ty,
2384 _ => panic!("expected equality type binding for parenthesized generic args"),
2387 pub fn opt_const(&self) -> Option<&'_ AnonConst> {
2389 TypeBindingKind::Equality { term: Term::Const(ref c) } => Some(c),
2395 #[derive(Debug, HashStable_Generic)]
2396 pub struct Ty<'hir> {
2398 pub kind: TyKind<'hir>,
2402 impl<'hir> Ty<'hir> {
2403 /// Returns `true` if `param_def_id` matches the `bounded_ty` of this predicate.
2404 pub fn as_generic_param(&self) -> Option<(DefId, Ident)> {
2405 let TyKind::Path(QPath::Resolved(None, path)) = self.kind else {
2408 let [segment] = &path.segments else {
2412 Res::Def(DefKind::TyParam, def_id) | Res::SelfTyParam { trait_: def_id } => {
2413 Some((def_id, segment.ident))
2419 pub fn peel_refs(&self) -> &Self {
2420 let mut final_ty = self;
2421 while let TyKind::Rptr(_, MutTy { ty, .. }) = &final_ty.kind {
2427 pub fn find_self_aliases(&self) -> Vec<Span> {
2428 use crate::intravisit::Visitor;
2429 struct MyVisitor(Vec<Span>);
2430 impl<'v> Visitor<'v> for MyVisitor {
2431 fn visit_ty(&mut self, t: &'v Ty<'v>) {
2434 TyKind::Path(QPath::Resolved(
2436 Path { res: crate::def::Res::SelfTyAlias { .. }, .. },
2439 self.0.push(t.span);
2442 crate::intravisit::walk_ty(self, t);
2446 let mut my_visitor = MyVisitor(vec![]);
2447 my_visitor.visit_ty(self);
2452 /// Not represented directly in the AST; referred to by name through a `ty_path`.
2453 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
2454 #[derive(HashStable_Generic)]
2465 /// All of the primitive types
2466 pub const ALL: [Self; 17] = [
2467 // any changes here should also be reflected in `PrimTy::from_name`
2468 Self::Int(IntTy::I8),
2469 Self::Int(IntTy::I16),
2470 Self::Int(IntTy::I32),
2471 Self::Int(IntTy::I64),
2472 Self::Int(IntTy::I128),
2473 Self::Int(IntTy::Isize),
2474 Self::Uint(UintTy::U8),
2475 Self::Uint(UintTy::U16),
2476 Self::Uint(UintTy::U32),
2477 Self::Uint(UintTy::U64),
2478 Self::Uint(UintTy::U128),
2479 Self::Uint(UintTy::Usize),
2480 Self::Float(FloatTy::F32),
2481 Self::Float(FloatTy::F64),
2487 /// Like [`PrimTy::name`], but returns a &str instead of a symbol.
2490 pub fn name_str(self) -> &'static str {
2492 PrimTy::Int(i) => i.name_str(),
2493 PrimTy::Uint(u) => u.name_str(),
2494 PrimTy::Float(f) => f.name_str(),
2495 PrimTy::Str => "str",
2496 PrimTy::Bool => "bool",
2497 PrimTy::Char => "char",
2501 pub fn name(self) -> Symbol {
2503 PrimTy::Int(i) => i.name(),
2504 PrimTy::Uint(u) => u.name(),
2505 PrimTy::Float(f) => f.name(),
2506 PrimTy::Str => sym::str,
2507 PrimTy::Bool => sym::bool,
2508 PrimTy::Char => sym::char,
2512 /// Returns the matching `PrimTy` for a `Symbol` such as "str" or "i32".
2513 /// Returns `None` if no matching type is found.
2514 pub fn from_name(name: Symbol) -> Option<Self> {
2515 let ty = match name {
2516 // any changes here should also be reflected in `PrimTy::ALL`
2517 sym::i8 => Self::Int(IntTy::I8),
2518 sym::i16 => Self::Int(IntTy::I16),
2519 sym::i32 => Self::Int(IntTy::I32),
2520 sym::i64 => Self::Int(IntTy::I64),
2521 sym::i128 => Self::Int(IntTy::I128),
2522 sym::isize => Self::Int(IntTy::Isize),
2523 sym::u8 => Self::Uint(UintTy::U8),
2524 sym::u16 => Self::Uint(UintTy::U16),
2525 sym::u32 => Self::Uint(UintTy::U32),
2526 sym::u64 => Self::Uint(UintTy::U64),
2527 sym::u128 => Self::Uint(UintTy::U128),
2528 sym::usize => Self::Uint(UintTy::Usize),
2529 sym::f32 => Self::Float(FloatTy::F32),
2530 sym::f64 => Self::Float(FloatTy::F64),
2531 sym::bool => Self::Bool,
2532 sym::char => Self::Char,
2533 sym::str => Self::Str,
2540 #[derive(Debug, HashStable_Generic)]
2541 pub struct BareFnTy<'hir> {
2542 pub unsafety: Unsafety,
2544 pub generic_params: &'hir [GenericParam<'hir>],
2545 pub decl: &'hir FnDecl<'hir>,
2546 pub param_names: &'hir [Ident],
2549 #[derive(Debug, HashStable_Generic)]
2550 pub struct OpaqueTy<'hir> {
2551 pub generics: &'hir Generics<'hir>,
2552 pub bounds: GenericBounds<'hir>,
2553 pub origin: OpaqueTyOrigin,
2557 /// From whence the opaque type came.
2558 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2559 pub enum OpaqueTyOrigin {
2561 FnReturn(LocalDefId),
2563 AsyncFn(LocalDefId),
2564 /// type aliases: `type Foo = impl Trait;`
2568 /// The various kinds of types recognized by the compiler.
2569 #[derive(Debug, HashStable_Generic)]
2570 pub enum TyKind<'hir> {
2571 /// A variable length slice (i.e., `[T]`).
2572 Slice(&'hir Ty<'hir>),
2573 /// A fixed length array (i.e., `[T; n]`).
2574 Array(&'hir Ty<'hir>, ArrayLen),
2575 /// A raw pointer (i.e., `*const T` or `*mut T`).
2577 /// A reference (i.e., `&'a T` or `&'a mut T`).
2578 Rptr(&'hir Lifetime, MutTy<'hir>),
2579 /// A bare function (e.g., `fn(usize) -> bool`).
2580 BareFn(&'hir BareFnTy<'hir>),
2581 /// The never type (`!`).
2583 /// A tuple (`(A, B, C, D, ...)`).
2584 Tup(&'hir [Ty<'hir>]),
2585 /// A path to a type definition (`module::module::...::Type`), or an
2586 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2588 /// Type parameters may be stored in each `PathSegment`.
2590 /// An opaque type definition itself. This is only used for `impl Trait`.
2592 /// The generic argument list contains the lifetimes (and in the future
2593 /// possibly parameters) that are actually bound on the `impl Trait`.
2595 /// The last parameter specifies whether this opaque appears in a trait definition.
2596 OpaqueDef(ItemId, &'hir [GenericArg<'hir>], bool),
2597 /// A trait object type `Bound1 + Bound2 + Bound3`
2598 /// where `Bound` is a trait or a lifetime.
2599 TraitObject(&'hir [PolyTraitRef<'hir>], &'hir Lifetime, TraitObjectSyntax),
2602 /// `TyKind::Infer` means the type should be inferred instead of it having been
2603 /// specified. This can appear anywhere in a type.
2605 /// Placeholder for a type that has failed to be defined.
2609 #[derive(Debug, HashStable_Generic)]
2610 pub enum InlineAsmOperand<'hir> {
2612 reg: InlineAsmRegOrRegClass,
2613 expr: &'hir Expr<'hir>,
2616 reg: InlineAsmRegOrRegClass,
2618 expr: Option<&'hir Expr<'hir>>,
2621 reg: InlineAsmRegOrRegClass,
2623 expr: &'hir Expr<'hir>,
2626 reg: InlineAsmRegOrRegClass,
2628 in_expr: &'hir Expr<'hir>,
2629 out_expr: Option<&'hir Expr<'hir>>,
2632 anon_const: AnonConst,
2635 anon_const: AnonConst,
2643 impl<'hir> InlineAsmOperand<'hir> {
2644 pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
2646 Self::In { reg, .. }
2647 | Self::Out { reg, .. }
2648 | Self::InOut { reg, .. }
2649 | Self::SplitInOut { reg, .. } => Some(reg),
2650 Self::Const { .. } | Self::SymFn { .. } | Self::SymStatic { .. } => None,
2654 pub fn is_clobber(&self) -> bool {
2657 InlineAsmOperand::Out { reg: InlineAsmRegOrRegClass::Reg(_), late: _, expr: None }
2662 #[derive(Debug, HashStable_Generic)]
2663 pub struct InlineAsm<'hir> {
2664 pub template: &'hir [InlineAsmTemplatePiece],
2665 pub template_strs: &'hir [(Symbol, Option<Symbol>, Span)],
2666 pub operands: &'hir [(InlineAsmOperand<'hir>, Span)],
2667 pub options: InlineAsmOptions,
2668 pub line_spans: &'hir [Span],
2671 /// Represents a parameter in a function header.
2672 #[derive(Debug, HashStable_Generic)]
2673 pub struct Param<'hir> {
2675 pub pat: &'hir Pat<'hir>,
2680 /// Represents the header (not the body) of a function declaration.
2681 #[derive(Debug, HashStable_Generic)]
2682 pub struct FnDecl<'hir> {
2683 /// The types of the function's parameters.
2685 /// Additional argument data is stored in the function's [body](Body::params).
2686 pub inputs: &'hir [Ty<'hir>],
2687 pub output: FnRetTy<'hir>,
2688 pub c_variadic: bool,
2689 /// Does the function have an implicit self?
2690 pub implicit_self: ImplicitSelfKind,
2693 /// Represents what type of implicit self a function has, if any.
2694 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2695 pub enum ImplicitSelfKind {
2696 /// Represents a `fn x(self);`.
2698 /// Represents a `fn x(mut self);`.
2700 /// Represents a `fn x(&self);`.
2702 /// Represents a `fn x(&mut self);`.
2704 /// Represents when a function does not have a self argument or
2705 /// when a function has a `self: X` argument.
2709 impl ImplicitSelfKind {
2710 /// Does this represent an implicit self?
2711 pub fn has_implicit_self(&self) -> bool {
2712 !matches!(*self, ImplicitSelfKind::None)
2716 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable, Debug)]
2717 #[derive(HashStable_Generic)]
2724 pub fn is_async(self) -> bool {
2725 self == IsAsync::Async
2729 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable, HashStable_Generic)]
2730 pub enum Defaultness {
2731 Default { has_value: bool },
2736 pub fn has_value(&self) -> bool {
2738 Defaultness::Default { has_value } => has_value,
2739 Defaultness::Final => true,
2743 pub fn is_final(&self) -> bool {
2744 *self == Defaultness::Final
2747 pub fn is_default(&self) -> bool {
2748 matches!(*self, Defaultness::Default { .. })
2752 #[derive(Debug, HashStable_Generic)]
2753 pub enum FnRetTy<'hir> {
2754 /// Return type is not specified.
2756 /// Functions default to `()` and
2757 /// closures default to inference. Span points to where return
2758 /// type would be inserted.
2759 DefaultReturn(Span),
2760 /// Everything else.
2761 Return(&'hir Ty<'hir>),
2766 pub fn span(&self) -> Span {
2768 Self::DefaultReturn(span) => span,
2769 Self::Return(ref ty) => ty.span,
2774 /// Represents `for<...>` binder before a closure
2775 #[derive(Copy, Clone, Debug, HashStable_Generic)]
2776 pub enum ClosureBinder {
2777 /// Binder is not specified.
2779 /// Binder is specified.
2781 /// Span points to the whole `for<...>`.
2785 #[derive(Encodable, Debug, HashStable_Generic)]
2786 pub struct Mod<'hir> {
2787 pub spans: ModSpans,
2788 pub item_ids: &'hir [ItemId],
2791 #[derive(Copy, Clone, Debug, HashStable_Generic, Encodable)]
2792 pub struct ModSpans {
2793 /// A span from the first token past `{` to the last token until `}`.
2794 /// For `mod foo;`, the inner span ranges from the first token
2795 /// to the last token in the external file.
2796 pub inner_span: Span,
2797 pub inject_use_span: Span,
2800 #[derive(Debug, HashStable_Generic)]
2801 pub struct EnumDef<'hir> {
2802 pub variants: &'hir [Variant<'hir>],
2805 #[derive(Debug, HashStable_Generic)]
2806 pub struct Variant<'hir> {
2807 /// Name of the variant.
2809 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2811 pub def_id: LocalDefId,
2812 /// Fields and constructor id of the variant.
2813 pub data: VariantData<'hir>,
2814 /// Explicit discriminant (e.g., `Foo = 1`).
2815 pub disr_expr: Option<AnonConst>,
2820 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2822 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2823 /// Also produced for each element of a list `use`, e.g.
2824 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2827 /// Glob import, e.g., `use foo::*`.
2830 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2831 /// an additional `use foo::{}` for performing checks such as
2832 /// unstable feature gating. May be removed in the future.
2836 /// References to traits in impls.
2838 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2839 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2840 /// trait being referred to but just a unique `HirId` that serves as a key
2841 /// within the resolution map.
2842 #[derive(Clone, Debug, HashStable_Generic)]
2843 pub struct TraitRef<'hir> {
2844 pub path: &'hir Path<'hir>,
2845 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2846 #[stable_hasher(ignore)]
2847 pub hir_ref_id: HirId,
2851 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2852 pub fn trait_def_id(&self) -> Option<DefId> {
2853 match self.path.res {
2854 Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
2856 _ => unreachable!(),
2861 #[derive(Clone, Debug, HashStable_Generic)]
2862 pub struct PolyTraitRef<'hir> {
2863 /// The `'a` in `for<'a> Foo<&'a T>`.
2864 pub bound_generic_params: &'hir [GenericParam<'hir>],
2866 /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
2867 pub trait_ref: TraitRef<'hir>,
2872 #[derive(Debug, HashStable_Generic)]
2873 pub struct FieldDef<'hir> {
2878 pub def_id: LocalDefId,
2879 pub ty: &'hir Ty<'hir>,
2883 // Still necessary in couple of places
2884 pub fn is_positional(&self) -> bool {
2885 let first = self.ident.as_str().as_bytes()[0];
2886 (b'0'..=b'9').contains(&first)
2890 /// Fields and constructor IDs of enum variants and structs.
2891 #[derive(Debug, HashStable_Generic)]
2892 pub enum VariantData<'hir> {
2893 /// A struct variant.
2895 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2896 Struct(&'hir [FieldDef<'hir>], /* recovered */ bool),
2897 /// A tuple variant.
2899 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2900 Tuple(&'hir [FieldDef<'hir>], HirId, LocalDefId),
2903 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2904 Unit(HirId, LocalDefId),
2907 impl<'hir> VariantData<'hir> {
2908 /// Return the fields of this variant.
2909 pub fn fields(&self) -> &'hir [FieldDef<'hir>] {
2911 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2916 pub fn ctor(&self) -> Option<(CtorKind, HirId, LocalDefId)> {
2918 VariantData::Tuple(_, hir_id, def_id) => Some((CtorKind::Fn, hir_id, def_id)),
2919 VariantData::Unit(hir_id, def_id) => Some((CtorKind::Const, hir_id, def_id)),
2920 VariantData::Struct(..) => None,
2925 pub fn ctor_kind(&self) -> Option<CtorKind> {
2926 self.ctor().map(|(kind, ..)| kind)
2929 /// Return the `HirId` of this variant's constructor, if it has one.
2931 pub fn ctor_hir_id(&self) -> Option<HirId> {
2932 self.ctor().map(|(_, hir_id, _)| hir_id)
2935 /// Return the `LocalDefId` of this variant's constructor, if it has one.
2937 pub fn ctor_def_id(&self) -> Option<LocalDefId> {
2938 self.ctor().map(|(.., def_id)| def_id)
2942 // The bodies for items are stored "out of line", in a separate
2943 // hashmap in the `Crate`. Here we just record the hir-id of the item
2944 // so it can fetched later.
2945 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
2947 pub owner_id: OwnerId,
2952 pub fn hir_id(&self) -> HirId {
2953 // Items are always HIR owners.
2954 HirId::make_owner(self.owner_id.def_id)
2960 /// The name might be a dummy name in case of anonymous items
2961 #[derive(Debug, HashStable_Generic)]
2962 pub struct Item<'hir> {
2964 pub owner_id: OwnerId,
2965 pub kind: ItemKind<'hir>,
2972 pub fn hir_id(&self) -> HirId {
2973 // Items are always HIR owners.
2974 HirId::make_owner(self.owner_id.def_id)
2977 pub fn item_id(&self) -> ItemId {
2978 ItemId { owner_id: self.owner_id }
2982 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2983 #[derive(Encodable, Decodable, HashStable_Generic)]
2990 pub fn prefix_str(&self) -> &'static str {
2992 Self::Unsafe => "unsafe ",
2998 impl fmt::Display for Unsafety {
2999 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3000 f.write_str(match *self {
3001 Self::Unsafe => "unsafe",
3002 Self::Normal => "normal",
3007 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
3008 #[derive(Encodable, Decodable, HashStable_Generic)]
3009 pub enum Constness {
3014 impl fmt::Display for Constness {
3015 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3016 f.write_str(match *self {
3017 Self::Const => "const",
3018 Self::NotConst => "non-const",
3023 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
3024 pub struct FnHeader {
3025 pub unsafety: Unsafety,
3026 pub constness: Constness,
3027 pub asyncness: IsAsync,
3032 pub fn is_async(&self) -> bool {
3033 matches!(&self.asyncness, IsAsync::Async)
3036 pub fn is_const(&self) -> bool {
3037 matches!(&self.constness, Constness::Const)
3040 pub fn is_unsafe(&self) -> bool {
3041 matches!(&self.unsafety, Unsafety::Unsafe)
3045 #[derive(Debug, HashStable_Generic)]
3046 pub enum ItemKind<'hir> {
3047 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
3049 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
3050 ExternCrate(Option<Symbol>),
3052 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
3056 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
3057 Use(&'hir Path<'hir>, UseKind),
3059 /// A `static` item.
3060 Static(&'hir Ty<'hir>, Mutability, BodyId),
3062 Const(&'hir Ty<'hir>, BodyId),
3063 /// A function declaration.
3064 Fn(FnSig<'hir>, &'hir Generics<'hir>, BodyId),
3065 /// A MBE macro definition (`macro_rules!` or `macro`).
3066 Macro(ast::MacroDef, MacroKind),
3068 Mod(&'hir Mod<'hir>),
3069 /// An external module, e.g. `extern { .. }`.
3070 ForeignMod { abi: Abi, items: &'hir [ForeignItemRef] },
3071 /// Module-level inline assembly (from `global_asm!`).
3072 GlobalAsm(&'hir InlineAsm<'hir>),
3073 /// A type alias, e.g., `type Foo = Bar<u8>`.
3074 TyAlias(&'hir Ty<'hir>, &'hir Generics<'hir>),
3075 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
3076 OpaqueTy(OpaqueTy<'hir>),
3077 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
3078 Enum(EnumDef<'hir>, &'hir Generics<'hir>),
3079 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
3080 Struct(VariantData<'hir>, &'hir Generics<'hir>),
3081 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
3082 Union(VariantData<'hir>, &'hir Generics<'hir>),
3083 /// A trait definition.
3084 Trait(IsAuto, Unsafety, &'hir Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
3086 TraitAlias(&'hir Generics<'hir>, GenericBounds<'hir>),
3088 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
3089 Impl(&'hir Impl<'hir>),
3092 #[derive(Debug, HashStable_Generic)]
3093 pub struct Impl<'hir> {
3094 pub unsafety: Unsafety,
3095 pub polarity: ImplPolarity,
3096 pub defaultness: Defaultness,
3097 // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata
3098 // decoding as `Span`s cannot be decoded when a `Session` is not available.
3099 pub defaultness_span: Option<Span>,
3100 pub constness: Constness,
3101 pub generics: &'hir Generics<'hir>,
3103 /// The trait being implemented, if any.
3104 pub of_trait: Option<TraitRef<'hir>>,
3106 pub self_ty: &'hir Ty<'hir>,
3107 pub items: &'hir [ImplItemRef],
3111 pub fn generics(&self) -> Option<&Generics<'_>> {
3113 ItemKind::Fn(_, ref generics, _)
3114 | ItemKind::TyAlias(_, ref generics)
3115 | ItemKind::OpaqueTy(OpaqueTy { ref generics, .. })
3116 | ItemKind::Enum(_, ref generics)
3117 | ItemKind::Struct(_, ref generics)
3118 | ItemKind::Union(_, ref generics)
3119 | ItemKind::Trait(_, _, ref generics, _, _)
3120 | ItemKind::TraitAlias(ref generics, _)
3121 | ItemKind::Impl(Impl { ref generics, .. }) => generics,
3126 pub fn descr(&self) -> &'static str {
3128 ItemKind::ExternCrate(..) => "extern crate",
3129 ItemKind::Use(..) => "`use` import",
3130 ItemKind::Static(..) => "static item",
3131 ItemKind::Const(..) => "constant item",
3132 ItemKind::Fn(..) => "function",
3133 ItemKind::Macro(..) => "macro",
3134 ItemKind::Mod(..) => "module",
3135 ItemKind::ForeignMod { .. } => "extern block",
3136 ItemKind::GlobalAsm(..) => "global asm item",
3137 ItemKind::TyAlias(..) => "type alias",
3138 ItemKind::OpaqueTy(..) => "opaque type",
3139 ItemKind::Enum(..) => "enum",
3140 ItemKind::Struct(..) => "struct",
3141 ItemKind::Union(..) => "union",
3142 ItemKind::Trait(..) => "trait",
3143 ItemKind::TraitAlias(..) => "trait alias",
3144 ItemKind::Impl(..) => "implementation",
3149 /// A reference from an trait to one of its associated items. This
3150 /// contains the item's id, naturally, but also the item's name and
3151 /// some other high-level details (like whether it is an associated
3152 /// type or method, and whether it is public). This allows other
3153 /// passes to find the impl they want without loading the ID (which
3154 /// means fewer edges in the incremental compilation graph).
3155 #[derive(Encodable, Debug, HashStable_Generic)]
3156 pub struct TraitItemRef {
3157 pub id: TraitItemId,
3159 pub kind: AssocItemKind,
3163 /// A reference from an impl to one of its associated items. This
3164 /// contains the item's ID, naturally, but also the item's name and
3165 /// some other high-level details (like whether it is an associated
3166 /// type or method, and whether it is public). This allows other
3167 /// passes to find the impl they want without loading the ID (which
3168 /// means fewer edges in the incremental compilation graph).
3169 #[derive(Debug, HashStable_Generic)]
3170 pub struct ImplItemRef {
3173 pub kind: AssocItemKind,
3175 /// When we are in a trait impl, link to the trait-item's id.
3176 pub trait_item_def_id: Option<DefId>,
3179 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
3180 pub enum AssocItemKind {
3182 Fn { has_self: bool },
3186 // The bodies for items are stored "out of line", in a separate
3187 // hashmap in the `Crate`. Here we just record the hir-id of the item
3188 // so it can fetched later.
3189 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3190 pub struct ForeignItemId {
3191 pub owner_id: OwnerId,
3194 impl ForeignItemId {
3196 pub fn hir_id(&self) -> HirId {
3197 // Items are always HIR owners.
3198 HirId::make_owner(self.owner_id.def_id)
3202 /// A reference from a foreign block to one of its items. This
3203 /// contains the item's ID, naturally, but also the item's name and
3204 /// some other high-level details (like whether it is an associated
3205 /// type or method, and whether it is public). This allows other
3206 /// passes to find the impl they want without loading the ID (which
3207 /// means fewer edges in the incremental compilation graph).
3208 #[derive(Debug, HashStable_Generic)]
3209 pub struct ForeignItemRef {
3210 pub id: ForeignItemId,
3215 #[derive(Debug, HashStable_Generic)]
3216 pub struct ForeignItem<'hir> {
3218 pub kind: ForeignItemKind<'hir>,
3219 pub owner_id: OwnerId,
3224 impl ForeignItem<'_> {
3226 pub fn hir_id(&self) -> HirId {
3227 // Items are always HIR owners.
3228 HirId::make_owner(self.owner_id.def_id)
3231 pub fn foreign_item_id(&self) -> ForeignItemId {
3232 ForeignItemId { owner_id: self.owner_id }
3236 /// An item within an `extern` block.
3237 #[derive(Debug, HashStable_Generic)]
3238 pub enum ForeignItemKind<'hir> {
3239 /// A foreign function.
3240 Fn(&'hir FnDecl<'hir>, &'hir [Ident], &'hir Generics<'hir>),
3241 /// A foreign static item (`static ext: u8`).
3242 Static(&'hir Ty<'hir>, Mutability),
3247 /// A variable captured by a closure.
3248 #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)]
3250 // First span where it is accessed (there can be multiple).
3254 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
3255 // has length > 0 if the trait is found through an chain of imports, starting with the
3256 // import/use statement in the scope where the trait is used.
3257 #[derive(Encodable, Decodable, Clone, Debug, HashStable_Generic)]
3258 pub struct TraitCandidate {
3260 pub import_ids: SmallVec<[LocalDefId; 1]>,
3263 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3264 pub enum OwnerNode<'hir> {
3265 Item(&'hir Item<'hir>),
3266 ForeignItem(&'hir ForeignItem<'hir>),
3267 TraitItem(&'hir TraitItem<'hir>),
3268 ImplItem(&'hir ImplItem<'hir>),
3269 Crate(&'hir Mod<'hir>),
3272 impl<'hir> OwnerNode<'hir> {
3273 pub fn ident(&self) -> Option<Ident> {
3275 OwnerNode::Item(Item { ident, .. })
3276 | OwnerNode::ForeignItem(ForeignItem { ident, .. })
3277 | OwnerNode::ImplItem(ImplItem { ident, .. })
3278 | OwnerNode::TraitItem(TraitItem { ident, .. }) => Some(*ident),
3279 OwnerNode::Crate(..) => None,
3283 pub fn span(&self) -> Span {
3285 OwnerNode::Item(Item { span, .. })
3286 | OwnerNode::ForeignItem(ForeignItem { span, .. })
3287 | OwnerNode::ImplItem(ImplItem { span, .. })
3288 | OwnerNode::TraitItem(TraitItem { span, .. }) => *span,
3289 OwnerNode::Crate(Mod { spans: ModSpans { inner_span, .. }, .. }) => *inner_span,
3293 pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
3295 OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3296 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3297 | OwnerNode::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3298 OwnerNode::ForeignItem(ForeignItem {
3299 kind: ForeignItemKind::Fn(fn_decl, _, _),
3301 }) => Some(fn_decl),
3306 pub fn body_id(&self) -> Option<BodyId> {
3308 OwnerNode::TraitItem(TraitItem {
3309 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3312 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3313 | OwnerNode::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3318 pub fn generics(self) -> Option<&'hir Generics<'hir>> {
3319 Node::generics(self.into())
3322 pub fn def_id(self) -> OwnerId {
3324 OwnerNode::Item(Item { owner_id, .. })
3325 | OwnerNode::TraitItem(TraitItem { owner_id, .. })
3326 | OwnerNode::ImplItem(ImplItem { owner_id, .. })
3327 | OwnerNode::ForeignItem(ForeignItem { owner_id, .. }) => *owner_id,
3328 OwnerNode::Crate(..) => crate::CRATE_HIR_ID.owner,
3332 pub fn expect_item(self) -> &'hir Item<'hir> {
3334 OwnerNode::Item(n) => n,
3339 pub fn expect_foreign_item(self) -> &'hir ForeignItem<'hir> {
3341 OwnerNode::ForeignItem(n) => n,
3346 pub fn expect_impl_item(self) -> &'hir ImplItem<'hir> {
3348 OwnerNode::ImplItem(n) => n,
3353 pub fn expect_trait_item(self) -> &'hir TraitItem<'hir> {
3355 OwnerNode::TraitItem(n) => n,
3361 impl<'hir> Into<OwnerNode<'hir>> for &'hir Item<'hir> {
3362 fn into(self) -> OwnerNode<'hir> {
3363 OwnerNode::Item(self)
3367 impl<'hir> Into<OwnerNode<'hir>> for &'hir ForeignItem<'hir> {
3368 fn into(self) -> OwnerNode<'hir> {
3369 OwnerNode::ForeignItem(self)
3373 impl<'hir> Into<OwnerNode<'hir>> for &'hir ImplItem<'hir> {
3374 fn into(self) -> OwnerNode<'hir> {
3375 OwnerNode::ImplItem(self)
3379 impl<'hir> Into<OwnerNode<'hir>> for &'hir TraitItem<'hir> {
3380 fn into(self) -> OwnerNode<'hir> {
3381 OwnerNode::TraitItem(self)
3385 impl<'hir> Into<Node<'hir>> for OwnerNode<'hir> {
3386 fn into(self) -> Node<'hir> {
3388 OwnerNode::Item(n) => Node::Item(n),
3389 OwnerNode::ForeignItem(n) => Node::ForeignItem(n),
3390 OwnerNode::ImplItem(n) => Node::ImplItem(n),
3391 OwnerNode::TraitItem(n) => Node::TraitItem(n),
3392 OwnerNode::Crate(n) => Node::Crate(n),
3397 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3398 pub enum Node<'hir> {
3399 Param(&'hir Param<'hir>),
3400 Item(&'hir Item<'hir>),
3401 ForeignItem(&'hir ForeignItem<'hir>),
3402 TraitItem(&'hir TraitItem<'hir>),
3403 ImplItem(&'hir ImplItem<'hir>),
3404 Variant(&'hir Variant<'hir>),
3405 Field(&'hir FieldDef<'hir>),
3406 AnonConst(&'hir AnonConst),
3407 Expr(&'hir Expr<'hir>),
3408 ExprField(&'hir ExprField<'hir>),
3409 Stmt(&'hir Stmt<'hir>),
3410 PathSegment(&'hir PathSegment<'hir>),
3412 TypeBinding(&'hir TypeBinding<'hir>),
3413 TraitRef(&'hir TraitRef<'hir>),
3414 Pat(&'hir Pat<'hir>),
3415 PatField(&'hir PatField<'hir>),
3416 Arm(&'hir Arm<'hir>),
3417 Block(&'hir Block<'hir>),
3418 Local(&'hir Local<'hir>),
3420 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
3421 /// with synthesized constructors.
3422 Ctor(&'hir VariantData<'hir>),
3424 Lifetime(&'hir Lifetime),
3425 GenericParam(&'hir GenericParam<'hir>),
3427 Crate(&'hir Mod<'hir>),
3429 Infer(&'hir InferArg),
3432 impl<'hir> Node<'hir> {
3433 /// Get the identifier of this `Node`, if applicable.
3437 /// Calling `.ident()` on a [`Node::Ctor`] will return `None`
3438 /// because `Ctor`s do not have identifiers themselves.
3439 /// Instead, call `.ident()` on the parent struct/variant, like so:
3441 /// ```ignore (illustrative)
3444 /// .and_then(|ctor_id| tcx.hir().find(tcx.hir().get_parent_node(ctor_id)))
3445 /// .and_then(|parent| parent.ident())
3447 pub fn ident(&self) -> Option<Ident> {
3449 Node::TraitItem(TraitItem { ident, .. })
3450 | Node::ImplItem(ImplItem { ident, .. })
3451 | Node::ForeignItem(ForeignItem { ident, .. })
3452 | Node::Field(FieldDef { ident, .. })
3453 | Node::Variant(Variant { ident, .. })
3454 | Node::Item(Item { ident, .. })
3455 | Node::PathSegment(PathSegment { ident, .. }) => Some(*ident),
3456 Node::Lifetime(lt) => Some(lt.name.ident()),
3457 Node::GenericParam(p) => Some(p.name.ident()),
3458 Node::TypeBinding(b) => Some(b.ident),
3460 | Node::AnonConst(..)
3466 | Node::PatField(..)
3467 | Node::ExprField(..)
3472 | Node::TraitRef(..)
3473 | Node::Infer(..) => None,
3477 pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
3479 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3480 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3481 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3482 Node::Expr(Expr { kind: ExprKind::Closure(Closure { fn_decl, .. }), .. })
3483 | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
3490 pub fn fn_sig(self) -> Option<&'hir FnSig<'hir>> {
3492 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3493 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3494 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig),
3499 pub fn body_id(&self) -> Option<BodyId> {
3501 Node::TraitItem(TraitItem {
3502 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3505 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3506 | Node::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3511 pub fn generics(self) -> Option<&'hir Generics<'hir>> {
3513 Node::ForeignItem(ForeignItem {
3514 kind: ForeignItemKind::Fn(_, _, generics), ..
3516 | Node::TraitItem(TraitItem { generics, .. })
3517 | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
3518 Node::Item(item) => item.kind.generics(),
3523 pub fn as_owner(self) -> Option<OwnerNode<'hir>> {
3525 Node::Item(i) => Some(OwnerNode::Item(i)),
3526 Node::ForeignItem(i) => Some(OwnerNode::ForeignItem(i)),
3527 Node::TraitItem(i) => Some(OwnerNode::TraitItem(i)),
3528 Node::ImplItem(i) => Some(OwnerNode::ImplItem(i)),
3529 Node::Crate(i) => Some(OwnerNode::Crate(i)),
3534 pub fn fn_kind(self) -> Option<FnKind<'hir>> {
3536 Node::Item(i) => match i.kind {
3537 ItemKind::Fn(ref sig, ref generics, _) => {
3538 Some(FnKind::ItemFn(i.ident, generics, sig.header))
3542 Node::TraitItem(ti) => match ti.kind {
3543 TraitItemKind::Fn(ref sig, TraitFn::Provided(_)) => {
3544 Some(FnKind::Method(ti.ident, sig))
3548 Node::ImplItem(ii) => match ii.kind {
3549 ImplItemKind::Fn(ref sig, _) => Some(FnKind::Method(ii.ident, sig)),
3552 Node::Expr(e) => match e.kind {
3553 ExprKind::Closure { .. } => Some(FnKind::Closure),
3560 /// Get the fields for the tuple-constructor,
3561 /// if this node is a tuple constructor, otherwise None
3562 pub fn tuple_fields(&self) -> Option<&'hir [FieldDef<'hir>]> {
3563 if let Node::Ctor(&VariantData::Tuple(fields, _, _)) = self { Some(fields) } else { None }
3567 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3568 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
3571 // tidy-alphabetical-start
3572 static_assert_size!(Block<'_>, 48);
3573 static_assert_size!(Body<'_>, 32);
3574 static_assert_size!(Expr<'_>, 64);
3575 static_assert_size!(ExprKind<'_>, 48);
3576 static_assert_size!(FnDecl<'_>, 40);
3577 static_assert_size!(ForeignItem<'_>, 72);
3578 static_assert_size!(ForeignItemKind<'_>, 40);
3579 static_assert_size!(GenericArg<'_>, 32);
3580 static_assert_size!(GenericBound<'_>, 48);
3581 static_assert_size!(Generics<'_>, 56);
3582 static_assert_size!(Impl<'_>, 80);
3583 static_assert_size!(ImplItem<'_>, 80);
3584 static_assert_size!(ImplItemKind<'_>, 32);
3585 static_assert_size!(Item<'_>, 80);
3586 static_assert_size!(ItemKind<'_>, 48);
3587 static_assert_size!(Local<'_>, 64);
3588 static_assert_size!(Param<'_>, 32);
3589 static_assert_size!(Pat<'_>, 72);
3590 static_assert_size!(Path<'_>, 40);
3591 static_assert_size!(PathSegment<'_>, 48);
3592 static_assert_size!(PatKind<'_>, 48);
3593 static_assert_size!(QPath<'_>, 24);
3594 static_assert_size!(Res, 12);
3595 static_assert_size!(Stmt<'_>, 32);
3596 static_assert_size!(StmtKind<'_>, 16);
3597 // tidy-alphabetical-end
3598 // FIXME: move the tidy directive to the end after the next bootstrap bump
3600 static_assert_size!(TraitItem<'_>, 88);
3601 #[cfg(not(bootstrap))]
3602 static_assert_size!(TraitItem<'_>, 80);
3604 static_assert_size!(TraitItemKind<'_>, 48);
3605 #[cfg(not(bootstrap))]
3606 static_assert_size!(TraitItemKind<'_>, 40);
3607 static_assert_size!(Ty<'_>, 48);
3608 static_assert_size!(TyKind<'_>, 32);