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)]
33 /// Either "`'a`", referring to a named lifetime definition,
34 /// `'_` referring to an anonymous lifetime (either explicitly `'_` or `&type`),
35 /// or "``" (i.e., `kw::Empty`) when appearing in path.
37 /// See `Lifetime::suggestion_position` for practical use.
40 /// Semantics of this lifetime.
41 pub res: LifetimeName,
44 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
45 #[derive(HashStable_Generic)]
47 /// Some user-given name like `T` or `'x`.
50 /// Synthetic name generated when user elided a lifetime in an impl header.
52 /// E.g., the lifetimes in cases like these:
53 /// ```ignore (fragment)
55 /// impl Foo<'_> for u32
57 /// in that case, we rewrite to
58 /// ```ignore (fragment)
59 /// impl<'f> Foo for &'f u32
60 /// impl<'f> Foo<'f> for u32
62 /// where `'f` is something like `Fresh(0)`. The indices are
63 /// unique per impl, but not necessarily continuous.
66 /// Indicates an illegal name was given and an error has been
67 /// reported (so we should squelch other derived errors). Occurs
68 /// when, e.g., `'_` is used in the wrong place.
73 pub fn ident(&self) -> Ident {
75 ParamName::Plain(ident) => ident,
76 ParamName::Fresh | ParamName::Error => Ident::with_dummy_span(kw::UnderscoreLifetime),
80 pub fn normalize_to_macros_2_0(&self) -> ParamName {
82 ParamName::Plain(ident) => ParamName::Plain(ident.normalize_to_macros_2_0()),
83 param_name => param_name,
88 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
89 #[derive(HashStable_Generic)]
90 pub enum LifetimeName {
91 /// User-given names or fresh (synthetic) names.
94 /// Implicit lifetime in a context like `dyn Foo`. This is
95 /// distinguished from implicit lifetimes elsewhere because the
96 /// lifetime that they default to must appear elsewhere within the
97 /// enclosing type. This means that, in an `impl Trait` context, we
98 /// don't have to create a parameter for them. That is, `impl
99 /// Trait<Item = &u32>` expands to an opaque type like `type
100 /// Foo<'a> = impl Trait<Item = &'a u32>`, but `impl Trait<item =
101 /// dyn Bar>` expands to `type Foo = impl Trait<Item = dyn Bar +
102 /// 'static>`. The latter uses `ImplicitObjectLifetimeDefault` so
103 /// that surrounding code knows not to create a lifetime
105 ImplicitObjectLifetimeDefault,
107 /// Indicates an error during lowering (usually `'_` in wrong place)
108 /// that was already reported.
111 /// User wrote an anonymous lifetime, either `'_` or nothing.
112 /// The semantics of this lifetime should be inferred by typechecking code.
115 /// User wrote `'static`.
120 pub fn is_elided(&self) -> bool {
122 LifetimeName::ImplicitObjectLifetimeDefault | LifetimeName::Infer => true,
124 // It might seem surprising that `Fresh` counts as not *elided*
125 // -- but this is because, as far as the code in the compiler is
126 // concerned -- `Fresh` variants act equivalently to "some fresh name".
127 // They correspond to early-bound regions on an impl, in other words.
128 LifetimeName::Error | LifetimeName::Param(..) | LifetimeName::Static => false,
133 impl fmt::Display for Lifetime {
134 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
135 if self.ident.name != kw::Empty { self.ident.name.fmt(f) } else { "'_".fmt(f) }
139 pub enum LifetimeSuggestionPosition {
140 /// The user wrote `'a` or `'_`.
142 /// The user wrote `&type` or `&mut type`.
144 /// The user wrote `Path` and omitted the `<'_>`.
146 /// The user wrote `Path<T>`, and omitted the `'_,`.
148 /// The user wrote `dyn Trait` and omitted the `+ '_`.
153 pub fn is_elided(&self) -> bool {
157 pub fn is_anonymous(&self) -> bool {
158 self.ident.name == kw::Empty || self.ident.name == kw::UnderscoreLifetime
161 pub fn suggestion_position(&self) -> (LifetimeSuggestionPosition, Span) {
162 if self.ident.name == kw::Empty {
163 if self.ident.span.is_empty() {
164 (LifetimeSuggestionPosition::ElidedPathArgument, self.ident.span)
166 (LifetimeSuggestionPosition::ElidedPath, self.ident.span.shrink_to_hi())
168 } else if self.res == LifetimeName::ImplicitObjectLifetimeDefault {
169 (LifetimeSuggestionPosition::ObjectDefault, self.ident.span)
170 } else if self.ident.span.is_empty() {
171 (LifetimeSuggestionPosition::Ampersand, self.ident.span)
173 (LifetimeSuggestionPosition::Normal, self.ident.span)
177 pub fn is_static(&self) -> bool {
178 self.res == LifetimeName::Static
182 /// A `Path` is essentially Rust's notion of a name; for instance,
183 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
184 /// along with a bunch of supporting information.
185 #[derive(Debug, HashStable_Generic)]
186 pub struct Path<'hir, R = Res> {
188 /// The resolution for the path.
190 /// The segments in the path: the things separated by `::`.
191 pub segments: &'hir [PathSegment<'hir>],
194 /// Up to three resolutions for type, value and macro namespaces.
195 pub type UsePath<'hir> = Path<'hir, SmallVec<[Res; 3]>>;
198 pub fn is_global(&self) -> bool {
199 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
203 /// A segment of a path: an identifier, an optional lifetime, and a set of
205 #[derive(Debug, HashStable_Generic)]
206 pub struct PathSegment<'hir> {
207 /// The identifier portion of this path segment.
212 /// Type/lifetime parameters attached to this path. They come in
213 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
214 /// this is more than just simple syntactic sugar; the use of
215 /// parens affects the region binding rules, so we preserve the
217 pub args: Option<&'hir GenericArgs<'hir>>,
219 /// Whether to infer remaining type parameters, if any.
220 /// This only applies to expression and pattern paths, and
221 /// out of those only the segments with no type parameters
222 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
223 pub infer_args: bool,
226 impl<'hir> PathSegment<'hir> {
227 /// Converts an identifier to the corresponding segment.
228 pub fn new(ident: Ident, hir_id: HirId, res: Res) -> PathSegment<'hir> {
229 PathSegment { ident, hir_id, res, infer_args: true, args: None }
232 pub fn invalid() -> Self {
233 Self::new(Ident::empty(), HirId::INVALID, Res::Err)
236 pub fn args(&self) -> &GenericArgs<'hir> {
237 if let Some(ref args) = self.args {
240 const DUMMY: &GenericArgs<'_> = &GenericArgs::none();
246 #[derive(Encodable, Debug, HashStable_Generic)]
247 pub struct ConstArg {
248 pub value: AnonConst,
252 #[derive(Encodable, Debug, HashStable_Generic)]
253 pub struct InferArg {
259 pub fn to_ty(&self) -> Ty<'_> {
260 Ty { kind: TyKind::Infer, span: self.span, hir_id: self.hir_id }
264 #[derive(Debug, HashStable_Generic)]
265 pub enum GenericArg<'hir> {
266 Lifetime(&'hir Lifetime),
267 Type(&'hir Ty<'hir>),
272 impl GenericArg<'_> {
273 pub fn span(&self) -> Span {
275 GenericArg::Lifetime(l) => l.ident.span,
276 GenericArg::Type(t) => t.span,
277 GenericArg::Const(c) => c.span,
278 GenericArg::Infer(i) => i.span,
282 pub fn hir_id(&self) -> HirId {
284 GenericArg::Lifetime(l) => l.hir_id,
285 GenericArg::Type(t) => t.hir_id,
286 GenericArg::Const(c) => c.value.hir_id,
287 GenericArg::Infer(i) => i.hir_id,
291 pub fn is_synthetic(&self) -> bool {
292 matches!(self, GenericArg::Lifetime(lifetime) if lifetime.ident == Ident::empty())
295 pub fn descr(&self) -> &'static str {
297 GenericArg::Lifetime(_) => "lifetime",
298 GenericArg::Type(_) => "type",
299 GenericArg::Const(_) => "constant",
300 GenericArg::Infer(_) => "inferred",
304 pub fn to_ord(&self) -> ast::ParamKindOrd {
306 GenericArg::Lifetime(_) => ast::ParamKindOrd::Lifetime,
307 GenericArg::Type(_) | GenericArg::Const(_) | GenericArg::Infer(_) => {
308 ast::ParamKindOrd::TypeOrConst
313 pub fn is_ty_or_const(&self) -> bool {
315 GenericArg::Lifetime(_) => false,
316 GenericArg::Type(_) | GenericArg::Const(_) | GenericArg::Infer(_) => true,
321 #[derive(Debug, HashStable_Generic)]
322 pub struct GenericArgs<'hir> {
323 /// The generic arguments for this path segment.
324 pub args: &'hir [GenericArg<'hir>],
325 /// Bindings (equality constraints) on associated types, if present.
326 /// E.g., `Foo<A = Bar>`.
327 pub bindings: &'hir [TypeBinding<'hir>],
328 /// Were arguments written in parenthesized form `Fn(T) -> U`?
329 /// This is required mostly for pretty-printing and diagnostics,
330 /// but also for changing lifetime elision rules to be "function-like".
331 pub parenthesized: bool,
332 /// The span encompassing arguments and the surrounding brackets `<>` or `()`
333 /// Foo<A, B, AssocTy = D> Fn(T, U, V) -> W
334 /// ^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^
335 /// Note that this may be:
336 /// - empty, if there are no generic brackets (but there may be hidden lifetimes)
337 /// - dummy, if this was generated while desugaring
341 impl<'hir> GenericArgs<'hir> {
342 pub const fn none() -> Self {
343 Self { args: &[], bindings: &[], parenthesized: false, span_ext: DUMMY_SP }
346 pub fn inputs(&self) -> &[Ty<'hir>] {
347 if self.parenthesized {
348 for arg in self.args {
350 GenericArg::Lifetime(_) => {}
351 GenericArg::Type(ref ty) => {
352 if let TyKind::Tup(ref tys) = ty.kind {
357 GenericArg::Const(_) => {}
358 GenericArg::Infer(_) => {}
362 panic!("GenericArgs::inputs: not a `Fn(T) -> U`");
366 pub fn has_type_params(&self) -> bool {
367 self.args.iter().any(|arg| matches!(arg, GenericArg::Type(_)))
370 pub fn has_err(&self) -> bool {
371 self.args.iter().any(|arg| match arg {
372 GenericArg::Type(ty) => matches!(ty.kind, TyKind::Err),
374 }) || self.bindings.iter().any(|arg| match arg.kind {
375 TypeBindingKind::Equality { term: Term::Ty(ty) } => matches!(ty.kind, TyKind::Err),
381 pub fn num_type_params(&self) -> usize {
382 self.args.iter().filter(|arg| matches!(arg, GenericArg::Type(_))).count()
386 pub fn num_lifetime_params(&self) -> usize {
387 self.args.iter().filter(|arg| matches!(arg, GenericArg::Lifetime(_))).count()
391 pub fn has_lifetime_params(&self) -> bool {
392 self.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)))
396 /// This function returns the number of type and const generic params.
397 /// It should only be used for diagnostics.
398 pub fn num_generic_params(&self) -> usize {
399 self.args.iter().filter(|arg| !matches!(arg, GenericArg::Lifetime(_))).count()
402 /// The span encompassing the text inside the surrounding brackets.
403 /// It will also include bindings if they aren't in the form `-> Ret`
404 /// Returns `None` if the span is empty (e.g. no brackets) or dummy
405 pub fn span(&self) -> Option<Span> {
406 let span_ext = self.span_ext()?;
407 Some(span_ext.with_lo(span_ext.lo() + BytePos(1)).with_hi(span_ext.hi() - BytePos(1)))
410 /// Returns span encompassing arguments and their surrounding `<>` or `()`
411 pub fn span_ext(&self) -> Option<Span> {
412 Some(self.span_ext).filter(|span| !span.is_empty())
415 pub fn is_empty(&self) -> bool {
420 /// A modifier on a bound, currently this is only used for `?Sized`, where the
421 /// modifier is `Maybe`. Negative bounds should also be handled here.
422 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
423 #[derive(HashStable_Generic)]
424 pub enum TraitBoundModifier {
430 /// The AST represents all type param bounds as types.
431 /// `typeck::collect::compute_bounds` matches these against
432 /// the "special" built-in traits (see `middle::lang_items`) and
433 /// detects `Copy`, `Send` and `Sync`.
434 #[derive(Clone, Debug, HashStable_Generic)]
435 pub enum GenericBound<'hir> {
436 Trait(PolyTraitRef<'hir>, TraitBoundModifier),
437 // FIXME(davidtwco): Introduce `PolyTraitRef::LangItem`
438 LangItemTrait(LangItem, Span, HirId, &'hir GenericArgs<'hir>),
439 Outlives(&'hir Lifetime),
442 impl GenericBound<'_> {
443 pub fn trait_ref(&self) -> Option<&TraitRef<'_>> {
445 GenericBound::Trait(data, _) => Some(&data.trait_ref),
450 pub fn span(&self) -> Span {
452 GenericBound::Trait(t, ..) => t.span,
453 GenericBound::LangItemTrait(_, span, ..) => *span,
454 GenericBound::Outlives(l) => l.ident.span,
459 pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
461 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
462 pub enum LifetimeParamKind {
463 // Indicates that the lifetime definition was explicitly declared (e.g., in
464 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
467 // Indication that the lifetime was elided (e.g., in both cases in
468 // `fn foo(x: &u8) -> &'_ u8 { x }`).
471 // Indication that the lifetime name was somehow in error.
475 #[derive(Debug, HashStable_Generic)]
476 pub enum GenericParamKind<'hir> {
477 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
479 kind: LifetimeParamKind,
482 default: Option<&'hir Ty<'hir>>,
487 /// Optional default value for the const generic param
488 default: Option<AnonConst>,
492 #[derive(Debug, HashStable_Generic)]
493 pub struct GenericParam<'hir> {
495 pub def_id: LocalDefId,
498 pub pure_wrt_drop: bool,
499 pub kind: GenericParamKind<'hir>,
500 pub colon_span: Option<Span>,
503 impl<'hir> GenericParam<'hir> {
504 /// Synthetic type-parameters are inserted after normal ones.
505 /// In order for normal parameters to be able to refer to synthetic ones,
506 /// scans them first.
507 pub fn is_impl_trait(&self) -> bool {
508 matches!(self.kind, GenericParamKind::Type { synthetic: true, .. })
511 /// This can happen for `async fn`, e.g. `async fn f<'_>(&'_ self)`.
513 /// See `lifetime_to_generic_param` in `rustc_ast_lowering` for more information.
514 pub fn is_elided_lifetime(&self) -> bool {
515 matches!(self.kind, GenericParamKind::Lifetime { kind: LifetimeParamKind::Elided })
520 pub struct GenericParamCount {
521 pub lifetimes: usize,
527 /// Represents lifetimes and type parameters attached to a declaration
528 /// of a function, enum, trait, etc.
529 #[derive(Debug, HashStable_Generic)]
530 pub struct Generics<'hir> {
531 pub params: &'hir [GenericParam<'hir>],
532 pub predicates: &'hir [WherePredicate<'hir>],
533 pub has_where_clause_predicates: bool,
534 pub where_clause_span: Span,
538 impl<'hir> Generics<'hir> {
539 pub const fn empty() -> &'hir Generics<'hir> {
540 const NOPE: Generics<'_> = Generics {
543 has_where_clause_predicates: false,
544 where_clause_span: DUMMY_SP,
550 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'hir>> {
551 self.params.iter().find(|¶m| 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_lifetime_suggestion(&self) -> Option<Span> {
564 if let Some(first) = self.params.first()
565 && self.span.contains(first.span)
567 // `fn foo<A>(t: impl Trait)`
568 // ^ suggest `'a, ` here
569 Some(first.span.shrink_to_lo())
575 /// If there are generic parameters, return where to introduce a new one.
576 pub fn span_for_param_suggestion(&self) -> Option<Span> {
577 if self.params.iter().any(|p| self.span.contains(p.span)) {
578 // `fn foo<A>(t: impl Trait)`
579 // ^ suggest `, T: Trait` here
580 let span = self.span.with_lo(self.span.hi() - BytePos(1)).shrink_to_lo();
587 /// `Span` where further predicates would be suggested, accounting for trailing commas, like
588 /// in `fn foo<T>(t: T) where T: Foo,` so we don't suggest two trailing commas.
589 pub fn tail_span_for_predicate_suggestion(&self) -> Span {
590 let end = self.where_clause_span.shrink_to_hi();
591 if self.has_where_clause_predicates {
594 .rfind(|&p| p.in_where_clause())
595 .map_or(end, |p| p.span())
603 pub fn add_where_or_trailing_comma(&self) -> &'static str {
604 if self.has_where_clause_predicates {
606 } else if self.where_clause_span.is_empty() {
609 // No where clause predicates, but we have `where` token
614 pub fn bounds_for_param(
616 param_def_id: LocalDefId,
617 ) -> impl Iterator<Item = &WhereBoundPredicate<'hir>> {
618 self.predicates.iter().filter_map(move |pred| match pred {
619 WherePredicate::BoundPredicate(bp) if bp.is_param_bound(param_def_id.to_def_id()) => {
626 pub fn outlives_for_param(
628 param_def_id: LocalDefId,
629 ) -> impl Iterator<Item = &WhereRegionPredicate<'_>> {
630 self.predicates.iter().filter_map(move |pred| match pred {
631 WherePredicate::RegionPredicate(rp) if rp.is_param_bound(param_def_id) => Some(rp),
636 pub fn bounds_span_for_suggestions(&self, param_def_id: LocalDefId) -> Option<Span> {
637 self.bounds_for_param(param_def_id).flat_map(|bp| bp.bounds.iter().rev()).find_map(
639 // We include bounds that come from a `#[derive(_)]` but point at the user's code,
640 // as we use this method to get a span appropriate for suggestions.
641 let bs = bound.span();
642 if bs.can_be_used_for_suggestions() { Some(bs.shrink_to_hi()) } else { None }
647 pub fn span_for_predicate_removal(&self, pos: usize) -> Span {
648 let predicate = &self.predicates[pos];
649 let span = predicate.span();
651 if !predicate.in_where_clause() {
657 // We need to find out which comma to remove.
658 if pos < self.predicates.len() - 1 {
659 let next_pred = &self.predicates[pos + 1];
660 if next_pred.in_where_clause() {
661 // where T: ?Sized, Foo: Bar,
663 return span.until(next_pred.span());
668 let prev_pred = &self.predicates[pos - 1];
669 if prev_pred.in_where_clause() {
670 // where Foo: Bar, T: ?Sized,
672 return prev_pred.span().shrink_to_hi().to(span);
676 // This is the only predicate in the where clause.
679 self.where_clause_span
682 pub fn span_for_bound_removal(&self, predicate_pos: usize, bound_pos: usize) -> Span {
683 let predicate = &self.predicates[predicate_pos];
684 let bounds = predicate.bounds();
686 if bounds.len() == 1 {
687 return self.span_for_predicate_removal(predicate_pos);
690 let span = bounds[bound_pos].span();
692 // where T: ?Sized + Bar, Foo: Bar,
694 span.to(bounds[1].span().shrink_to_lo())
696 // where T: Bar + ?Sized, Foo: Bar,
698 bounds[bound_pos - 1].span().shrink_to_hi().to(span)
703 /// A single predicate in a where-clause.
704 #[derive(Debug, HashStable_Generic)]
705 pub enum WherePredicate<'hir> {
706 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
707 BoundPredicate(WhereBoundPredicate<'hir>),
708 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
709 RegionPredicate(WhereRegionPredicate<'hir>),
710 /// An equality predicate (unsupported).
711 EqPredicate(WhereEqPredicate<'hir>),
714 impl<'hir> WherePredicate<'hir> {
715 pub fn span(&self) -> Span {
717 WherePredicate::BoundPredicate(p) => p.span,
718 WherePredicate::RegionPredicate(p) => p.span,
719 WherePredicate::EqPredicate(p) => p.span,
723 pub fn in_where_clause(&self) -> bool {
725 WherePredicate::BoundPredicate(p) => p.origin == PredicateOrigin::WhereClause,
726 WherePredicate::RegionPredicate(p) => p.in_where_clause,
727 WherePredicate::EqPredicate(_) => false,
731 pub fn bounds(&self) -> GenericBounds<'hir> {
733 WherePredicate::BoundPredicate(p) => p.bounds,
734 WherePredicate::RegionPredicate(p) => p.bounds,
735 WherePredicate::EqPredicate(_) => &[],
740 #[derive(Copy, Clone, Debug, HashStable_Generic, PartialEq, Eq)]
741 pub enum PredicateOrigin {
747 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
748 #[derive(Debug, HashStable_Generic)]
749 pub struct WhereBoundPredicate<'hir> {
752 /// Origin of the predicate.
753 pub origin: PredicateOrigin,
754 /// Any generics from a `for` binding.
755 pub bound_generic_params: &'hir [GenericParam<'hir>],
756 /// The type being bounded.
757 pub bounded_ty: &'hir Ty<'hir>,
758 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
759 pub bounds: GenericBounds<'hir>,
762 impl<'hir> WhereBoundPredicate<'hir> {
763 /// Returns `true` if `param_def_id` matches the `bounded_ty` of this predicate.
764 pub fn is_param_bound(&self, param_def_id: DefId) -> bool {
765 self.bounded_ty.as_generic_param().map_or(false, |(def_id, _)| def_id == param_def_id)
769 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
770 #[derive(Debug, HashStable_Generic)]
771 pub struct WhereRegionPredicate<'hir> {
773 pub in_where_clause: bool,
774 pub lifetime: &'hir Lifetime,
775 pub bounds: GenericBounds<'hir>,
778 impl<'hir> WhereRegionPredicate<'hir> {
779 /// Returns `true` if `param_def_id` matches the `lifetime` of this predicate.
780 pub fn is_param_bound(&self, param_def_id: LocalDefId) -> bool {
781 self.lifetime.res == LifetimeName::Param(param_def_id)
785 /// An equality predicate (e.g., `T = int`); currently unsupported.
786 #[derive(Debug, HashStable_Generic)]
787 pub struct WhereEqPredicate<'hir> {
789 pub lhs_ty: &'hir Ty<'hir>,
790 pub rhs_ty: &'hir Ty<'hir>,
793 /// HIR node coupled with its parent's id in the same HIR owner.
795 /// The parent is trash when the node is a HIR owner.
796 #[derive(Clone, Debug)]
797 pub struct ParentedNode<'tcx> {
798 pub parent: ItemLocalId,
799 pub node: Node<'tcx>,
802 /// Attributes owned by a HIR owner.
804 pub struct AttributeMap<'tcx> {
805 pub map: SortedMap<ItemLocalId, &'tcx [Attribute]>,
806 pub hash: Fingerprint,
809 impl<'tcx> AttributeMap<'tcx> {
810 pub const EMPTY: &'static AttributeMap<'static> =
811 &AttributeMap { map: SortedMap::new(), hash: Fingerprint::ZERO };
814 pub fn get(&self, id: ItemLocalId) -> &'tcx [Attribute] {
815 self.map.get(&id).copied().unwrap_or(&[])
819 /// Map of all HIR nodes inside the current owner.
820 /// These nodes are mapped by `ItemLocalId` alongside the index of their parent node.
821 /// The HIR tree, including bodies, is pre-hashed.
822 pub struct OwnerNodes<'tcx> {
823 /// Pre-computed hash of the full HIR.
824 pub hash_including_bodies: Fingerprint,
825 /// Pre-computed hash of the item signature, without recursing into the body.
826 pub hash_without_bodies: Fingerprint,
827 /// Full HIR for the current owner.
828 // The zeroth node's parent should never be accessed: the owner's parent is computed by the
829 // hir_owner_parent query. It is set to `ItemLocalId::INVALID` to force an ICE if accidentally
831 pub nodes: IndexVec<ItemLocalId, Option<ParentedNode<'tcx>>>,
832 /// Content of local bodies.
833 pub bodies: SortedMap<ItemLocalId, &'tcx Body<'tcx>>,
834 /// Non-owning definitions contained in this owner.
835 pub local_id_to_def_id: SortedMap<ItemLocalId, LocalDefId>,
838 impl<'tcx> OwnerNodes<'tcx> {
839 pub fn node(&self) -> OwnerNode<'tcx> {
840 use rustc_index::vec::Idx;
841 let node = self.nodes[ItemLocalId::new(0)].as_ref().unwrap().node;
842 let node = node.as_owner().unwrap(); // Indexing must ensure it is an OwnerNode.
847 impl fmt::Debug for OwnerNodes<'_> {
848 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
849 f.debug_struct("OwnerNodes")
850 // Do not print all the pointers to all the nodes, as it would be unreadable.
851 .field("node", &self.nodes[ItemLocalId::from_u32(0)])
857 .map(|(id, parented_node)| (id, parented_node.as_ref().map(|node| node.parent)))
858 .collect::<Vec<_>>(),
860 .field("bodies", &self.bodies)
861 .field("local_id_to_def_id", &self.local_id_to_def_id)
862 .field("hash_without_bodies", &self.hash_without_bodies)
863 .field("hash_including_bodies", &self.hash_including_bodies)
868 /// Full information resulting from lowering an AST node.
869 #[derive(Debug, HashStable_Generic)]
870 pub struct OwnerInfo<'hir> {
871 /// Contents of the HIR.
872 pub nodes: OwnerNodes<'hir>,
873 /// Map from each nested owner to its parent's local id.
874 pub parenting: FxHashMap<LocalDefId, ItemLocalId>,
875 /// Collected attributes of the HIR nodes.
876 pub attrs: AttributeMap<'hir>,
877 /// Map indicating what traits are in scope for places where this
878 /// is relevant; generated by resolve.
879 pub trait_map: FxHashMap<ItemLocalId, Box<[TraitCandidate]>>,
882 impl<'tcx> OwnerInfo<'tcx> {
884 pub fn node(&self) -> OwnerNode<'tcx> {
889 #[derive(Copy, Clone, Debug, HashStable_Generic)]
890 pub enum MaybeOwner<T> {
893 /// Used as a placeholder for unused LocalDefId.
897 impl<T> MaybeOwner<T> {
898 pub fn as_owner(self) -> Option<T> {
900 MaybeOwner::Owner(i) => Some(i),
901 MaybeOwner::NonOwner(_) | MaybeOwner::Phantom => None,
905 pub fn map<U>(self, f: impl FnOnce(T) -> U) -> MaybeOwner<U> {
907 MaybeOwner::Owner(i) => MaybeOwner::Owner(f(i)),
908 MaybeOwner::NonOwner(hir_id) => MaybeOwner::NonOwner(hir_id),
909 MaybeOwner::Phantom => MaybeOwner::Phantom,
913 pub fn unwrap(self) -> T {
915 MaybeOwner::Owner(i) => i,
916 MaybeOwner::NonOwner(_) | MaybeOwner::Phantom => panic!("Not a HIR owner"),
921 /// The top-level data structure that stores the entire contents of
922 /// the crate currently being compiled.
924 /// For more details, see the [rustc dev guide].
926 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
928 pub struct Crate<'hir> {
929 pub owners: IndexVec<LocalDefId, MaybeOwner<&'hir OwnerInfo<'hir>>>,
930 pub hir_hash: Fingerprint,
933 #[derive(Debug, HashStable_Generic)]
934 pub struct Closure<'hir> {
935 pub def_id: LocalDefId,
936 pub binder: ClosureBinder,
937 pub capture_clause: CaptureBy,
938 pub bound_generic_params: &'hir [GenericParam<'hir>],
939 pub fn_decl: &'hir FnDecl<'hir>,
941 /// The span of the declaration block: 'move |...| -> ...'
942 pub fn_decl_span: Span,
943 /// The span of the argument block `|...|`
944 pub fn_arg_span: Option<Span>,
945 pub movability: Option<Movability>,
948 /// A block of statements `{ .. }`, which may have a label (in this case the
949 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
950 /// the `rules` being anything but `DefaultBlock`.
951 #[derive(Debug, HashStable_Generic)]
952 pub struct Block<'hir> {
953 /// Statements in a block.
954 pub stmts: &'hir [Stmt<'hir>],
955 /// An expression at the end of the block
956 /// without a semicolon, if any.
957 pub expr: Option<&'hir Expr<'hir>>,
958 #[stable_hasher(ignore)]
960 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
961 pub rules: BlockCheckMode,
963 /// If true, then there may exist `break 'a` values that aim to
964 /// break out of this block early.
965 /// Used by `'label: {}` blocks and by `try {}` blocks.
966 pub targeted_by_break: bool,
969 impl<'hir> Block<'hir> {
970 pub fn innermost_block(&self) -> &Block<'hir> {
971 let mut block = self;
972 while let Some(Expr { kind: ExprKind::Block(inner_block, _), .. }) = block.expr {
979 #[derive(Debug, HashStable_Generic)]
980 pub struct Pat<'hir> {
981 #[stable_hasher(ignore)]
983 pub kind: PatKind<'hir>,
985 /// Whether to use default binding modes.
986 /// At present, this is false only for destructuring assignment.
987 pub default_binding_modes: bool,
990 impl<'hir> Pat<'hir> {
991 // FIXME(#19596) this is a workaround, but there should be a better way
992 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) -> bool {
999 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
1000 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
1001 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
1002 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
1003 Slice(before, slice, after) => {
1004 before.iter().chain(slice).chain(after.iter()).all(|p| p.walk_short_(it))
1009 /// Walk the pattern in left-to-right order,
1010 /// short circuiting (with `.all(..)`) if `false` is returned.
1012 /// Note that when visiting e.g. `Tuple(ps)`,
1013 /// if visiting `ps[0]` returns `false`,
1014 /// then `ps[1]` will not be visited.
1015 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) -> bool {
1016 self.walk_short_(&mut it)
1019 // FIXME(#19596) this is a workaround, but there should be a better way
1020 fn walk_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) {
1027 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
1028 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
1029 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
1030 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
1031 Slice(before, slice, after) => {
1032 before.iter().chain(slice).chain(after.iter()).for_each(|p| p.walk_(it))
1037 /// Walk the pattern in left-to-right order.
1039 /// If `it(pat)` returns `false`, the children are not visited.
1040 pub fn walk(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) {
1044 /// Walk the pattern in left-to-right order.
1046 /// If you always want to recurse, prefer this method over `walk`.
1047 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
1055 /// A single field in a struct pattern.
1057 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
1058 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
1059 /// except `is_shorthand` is true.
1060 #[derive(Debug, HashStable_Generic)]
1061 pub struct PatField<'hir> {
1062 #[stable_hasher(ignore)]
1064 /// The identifier for the field.
1066 /// The pattern the field is destructured to.
1067 pub pat: &'hir Pat<'hir>,
1068 pub is_shorthand: bool,
1072 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1078 impl fmt::Display for RangeEnd {
1079 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1080 f.write_str(match self {
1081 RangeEnd::Included => "..=",
1082 RangeEnd::Excluded => "..",
1087 // Equivalent to `Option<usize>`. That type takes up 16 bytes on 64-bit, but
1088 // this type only takes up 4 bytes, at the cost of being restricted to a
1089 // maximum value of `u32::MAX - 1`. In practice, this is more than enough.
1090 #[derive(Clone, Copy, PartialEq, Eq, Hash, HashStable_Generic)]
1091 pub struct DotDotPos(u32);
1094 /// Panics if n >= u32::MAX.
1095 pub fn new(n: Option<usize>) -> Self {
1098 assert!(n < u32::MAX as usize);
1101 None => Self(u32::MAX),
1105 pub fn as_opt_usize(&self) -> Option<usize> {
1106 if self.0 == u32::MAX { None } else { Some(self.0 as usize) }
1110 impl fmt::Debug for DotDotPos {
1111 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1112 self.as_opt_usize().fmt(f)
1116 #[derive(Debug, HashStable_Generic)]
1117 pub enum PatKind<'hir> {
1118 /// Represents a wildcard pattern (i.e., `_`).
1121 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
1122 /// The `HirId` is the canonical ID for the variable being bound,
1123 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
1124 /// which is the pattern ID of the first `x`.
1125 Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
1127 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
1128 /// The `bool` is `true` in the presence of a `..`.
1129 Struct(QPath<'hir>, &'hir [PatField<'hir>], bool),
1131 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
1132 /// If the `..` pattern fragment is present, then `DotDotPos` denotes its position.
1133 /// `0 <= position <= subpats.len()`
1134 TupleStruct(QPath<'hir>, &'hir [Pat<'hir>], DotDotPos),
1136 /// An or-pattern `A | B | C`.
1137 /// Invariant: `pats.len() >= 2`.
1138 Or(&'hir [Pat<'hir>]),
1140 /// A path pattern for a unit struct/variant or a (maybe-associated) constant.
1143 /// A tuple pattern (e.g., `(a, b)`).
1144 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
1145 /// `0 <= position <= subpats.len()`
1146 Tuple(&'hir [Pat<'hir>], DotDotPos),
1148 /// A `box` pattern.
1149 Box(&'hir Pat<'hir>),
1151 /// A reference pattern (e.g., `&mut (a, b)`).
1152 Ref(&'hir Pat<'hir>, Mutability),
1155 Lit(&'hir Expr<'hir>),
1157 /// A range pattern (e.g., `1..=2` or `1..2`).
1158 Range(Option<&'hir Expr<'hir>>, Option<&'hir Expr<'hir>>, RangeEnd),
1160 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
1162 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
1163 /// If `slice` exists, then `after` can be non-empty.
1165 /// The representation for e.g., `[a, b, .., c, d]` is:
1166 /// ```ignore (illustrative)
1167 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
1169 Slice(&'hir [Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [Pat<'hir>]),
1172 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1173 pub enum BinOpKind {
1174 /// The `+` operator (addition).
1176 /// The `-` operator (subtraction).
1178 /// The `*` operator (multiplication).
1180 /// The `/` operator (division).
1182 /// The `%` operator (modulus).
1184 /// The `&&` operator (logical and).
1186 /// The `||` operator (logical or).
1188 /// The `^` operator (bitwise xor).
1190 /// The `&` operator (bitwise and).
1192 /// The `|` operator (bitwise or).
1194 /// The `<<` operator (shift left).
1196 /// The `>>` operator (shift right).
1198 /// The `==` operator (equality).
1200 /// The `<` operator (less than).
1202 /// The `<=` operator (less than or equal to).
1204 /// The `!=` operator (not equal to).
1206 /// The `>=` operator (greater than or equal to).
1208 /// The `>` operator (greater than).
1213 pub fn as_str(self) -> &'static str {
1215 BinOpKind::Add => "+",
1216 BinOpKind::Sub => "-",
1217 BinOpKind::Mul => "*",
1218 BinOpKind::Div => "/",
1219 BinOpKind::Rem => "%",
1220 BinOpKind::And => "&&",
1221 BinOpKind::Or => "||",
1222 BinOpKind::BitXor => "^",
1223 BinOpKind::BitAnd => "&",
1224 BinOpKind::BitOr => "|",
1225 BinOpKind::Shl => "<<",
1226 BinOpKind::Shr => ">>",
1227 BinOpKind::Eq => "==",
1228 BinOpKind::Lt => "<",
1229 BinOpKind::Le => "<=",
1230 BinOpKind::Ne => "!=",
1231 BinOpKind::Ge => ">=",
1232 BinOpKind::Gt => ">",
1236 pub fn is_lazy(self) -> bool {
1237 matches!(self, BinOpKind::And | BinOpKind::Or)
1240 pub fn is_shift(self) -> bool {
1241 matches!(self, BinOpKind::Shl | BinOpKind::Shr)
1244 pub fn is_comparison(self) -> bool {
1251 | BinOpKind::Ge => true,
1263 | BinOpKind::Shr => false,
1267 /// Returns `true` if the binary operator takes its arguments by value.
1268 pub fn is_by_value(self) -> bool {
1269 !self.is_comparison()
1273 impl Into<ast::BinOpKind> for BinOpKind {
1274 fn into(self) -> ast::BinOpKind {
1276 BinOpKind::Add => ast::BinOpKind::Add,
1277 BinOpKind::Sub => ast::BinOpKind::Sub,
1278 BinOpKind::Mul => ast::BinOpKind::Mul,
1279 BinOpKind::Div => ast::BinOpKind::Div,
1280 BinOpKind::Rem => ast::BinOpKind::Rem,
1281 BinOpKind::And => ast::BinOpKind::And,
1282 BinOpKind::Or => ast::BinOpKind::Or,
1283 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1284 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1285 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1286 BinOpKind::Shl => ast::BinOpKind::Shl,
1287 BinOpKind::Shr => ast::BinOpKind::Shr,
1288 BinOpKind::Eq => ast::BinOpKind::Eq,
1289 BinOpKind::Lt => ast::BinOpKind::Lt,
1290 BinOpKind::Le => ast::BinOpKind::Le,
1291 BinOpKind::Ne => ast::BinOpKind::Ne,
1292 BinOpKind::Ge => ast::BinOpKind::Ge,
1293 BinOpKind::Gt => ast::BinOpKind::Gt,
1298 pub type BinOp = Spanned<BinOpKind>;
1300 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1302 /// The `*` operator (dereferencing).
1304 /// The `!` operator (logical negation).
1306 /// The `-` operator (negation).
1311 pub fn as_str(self) -> &'static str {
1319 /// Returns `true` if the unary operator takes its argument by value.
1320 pub fn is_by_value(self) -> bool {
1321 matches!(self, Self::Neg | Self::Not)
1326 #[derive(Debug, HashStable_Generic)]
1327 pub struct Stmt<'hir> {
1329 pub kind: StmtKind<'hir>,
1333 /// The contents of a statement.
1334 #[derive(Debug, HashStable_Generic)]
1335 pub enum StmtKind<'hir> {
1336 /// A local (`let`) binding.
1337 Local(&'hir Local<'hir>),
1339 /// An item binding.
1342 /// An expression without a trailing semi-colon (must have unit type).
1343 Expr(&'hir Expr<'hir>),
1345 /// An expression with a trailing semi-colon (may have any type).
1346 Semi(&'hir Expr<'hir>),
1349 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <init>;`).
1350 #[derive(Debug, HashStable_Generic)]
1351 pub struct Local<'hir> {
1352 pub pat: &'hir Pat<'hir>,
1353 /// Type annotation, if any (otherwise the type will be inferred).
1354 pub ty: Option<&'hir Ty<'hir>>,
1355 /// Initializer expression to set the value, if any.
1356 pub init: Option<&'hir Expr<'hir>>,
1357 /// Else block for a `let...else` binding.
1358 pub els: Option<&'hir Block<'hir>>,
1361 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1362 /// desugaring. Otherwise will be `Normal`.
1363 pub source: LocalSource,
1366 /// Represents a single arm of a `match` expression, e.g.
1367 /// `<pat> (if <guard>) => <body>`.
1368 #[derive(Debug, HashStable_Generic)]
1369 pub struct Arm<'hir> {
1370 #[stable_hasher(ignore)]
1373 /// If this pattern and the optional guard matches, then `body` is evaluated.
1374 pub pat: &'hir Pat<'hir>,
1375 /// Optional guard clause.
1376 pub guard: Option<Guard<'hir>>,
1377 /// The expression the arm evaluates to if this arm matches.
1378 pub body: &'hir Expr<'hir>,
1381 /// Represents a `let <pat>[: <ty>] = <expr>` expression (not a Local), occurring in an `if-let` or
1382 /// `let-else`, evaluating to a boolean. Typically the pattern is refutable.
1384 /// In an if-let, imagine it as `if (let <pat> = <expr>) { ... }`; in a let-else, it is part of the
1385 /// desugaring to if-let. Only let-else supports the type annotation at present.
1386 #[derive(Debug, HashStable_Generic)]
1387 pub struct Let<'hir> {
1390 pub pat: &'hir Pat<'hir>,
1391 pub ty: Option<&'hir Ty<'hir>>,
1392 pub init: &'hir Expr<'hir>,
1395 #[derive(Debug, HashStable_Generic)]
1396 pub enum Guard<'hir> {
1397 If(&'hir Expr<'hir>),
1398 IfLet(&'hir Let<'hir>),
1401 impl<'hir> Guard<'hir> {
1402 /// Returns the body of the guard
1404 /// In other words, returns the e in either of the following:
1407 /// - `if let x = e`
1408 pub fn body(&self) -> &'hir Expr<'hir> {
1410 Guard::If(e) | Guard::IfLet(Let { init: e, .. }) => e,
1415 #[derive(Debug, HashStable_Generic)]
1416 pub struct ExprField<'hir> {
1417 #[stable_hasher(ignore)]
1420 pub expr: &'hir Expr<'hir>,
1422 pub is_shorthand: bool,
1425 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1426 pub enum BlockCheckMode {
1428 UnsafeBlock(UnsafeSource),
1431 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1432 pub enum UnsafeSource {
1437 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
1442 /// The body of a function, closure, or constant value. In the case of
1443 /// a function, the body contains not only the function body itself
1444 /// (which is an expression), but also the argument patterns, since
1445 /// those are something that the caller doesn't really care about.
1450 /// fn foo((x, y): (u32, u32)) -> u32 {
1455 /// Here, the `Body` associated with `foo()` would contain:
1457 /// - an `params` array containing the `(x, y)` pattern
1458 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1459 /// - `generator_kind` would be `None`
1461 /// All bodies have an **owner**, which can be accessed via the HIR
1462 /// map using `body_owner_def_id()`.
1463 #[derive(Debug, HashStable_Generic)]
1464 pub struct Body<'hir> {
1465 pub params: &'hir [Param<'hir>],
1466 pub value: &'hir Expr<'hir>,
1467 pub generator_kind: Option<GeneratorKind>,
1470 impl<'hir> Body<'hir> {
1471 pub fn id(&self) -> BodyId {
1472 BodyId { hir_id: self.value.hir_id }
1475 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1480 /// The type of source expression that caused this generator to be created.
1481 #[derive(Clone, PartialEq, PartialOrd, Eq, Hash, Debug, Copy)]
1482 #[derive(HashStable_Generic, Encodable, Decodable)]
1483 pub enum GeneratorKind {
1484 /// An explicit `async` block or the body of an async function.
1485 Async(AsyncGeneratorKind),
1487 /// A generator literal created via a `yield` inside a closure.
1491 impl fmt::Display for GeneratorKind {
1492 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1494 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1495 GeneratorKind::Gen => f.write_str("generator"),
1500 impl GeneratorKind {
1501 pub fn descr(&self) -> &'static str {
1503 GeneratorKind::Async(ask) => ask.descr(),
1504 GeneratorKind::Gen => "generator",
1509 /// In the case of a generator created as part of an async construct,
1510 /// which kind of async construct caused it to be created?
1512 /// This helps error messages but is also used to drive coercions in
1513 /// type-checking (see #60424).
1514 #[derive(Clone, PartialEq, PartialOrd, Eq, Hash, Debug, Copy)]
1515 #[derive(HashStable_Generic, Encodable, Decodable)]
1516 pub enum AsyncGeneratorKind {
1517 /// An explicit `async` block written by the user.
1520 /// An explicit `async` closure written by the user.
1523 /// The `async` block generated as the body of an async function.
1527 impl fmt::Display for AsyncGeneratorKind {
1528 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1529 f.write_str(match self {
1530 AsyncGeneratorKind::Block => "async block",
1531 AsyncGeneratorKind::Closure => "async closure body",
1532 AsyncGeneratorKind::Fn => "async fn body",
1537 impl AsyncGeneratorKind {
1538 pub fn descr(&self) -> &'static str {
1540 AsyncGeneratorKind::Block => "`async` block",
1541 AsyncGeneratorKind::Closure => "`async` closure body",
1542 AsyncGeneratorKind::Fn => "`async fn` body",
1547 #[derive(Copy, Clone, Debug)]
1548 pub enum BodyOwnerKind {
1549 /// Functions and methods.
1555 /// Constants and associated constants.
1558 /// Initializer of a `static` item.
1562 impl BodyOwnerKind {
1563 pub fn is_fn_or_closure(self) -> bool {
1565 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1566 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1571 /// The kind of an item that requires const-checking.
1572 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1573 pub enum ConstContext {
1577 /// A `static` or `static mut`.
1580 /// A `const`, associated `const`, or other const context.
1582 /// Other contexts include:
1583 /// - Array length expressions
1584 /// - Enum discriminants
1585 /// - Const generics
1587 /// For the most part, other contexts are treated just like a regular `const`, so they are
1588 /// lumped into the same category.
1593 /// A description of this const context that can appear between backticks in an error message.
1595 /// E.g. `const` or `static mut`.
1596 pub fn keyword_name(self) -> &'static str {
1598 Self::Const => "const",
1599 Self::Static(Mutability::Not) => "static",
1600 Self::Static(Mutability::Mut) => "static mut",
1601 Self::ConstFn => "const fn",
1606 /// A colloquial, trivially pluralizable description of this const context for use in error
1608 impl fmt::Display for ConstContext {
1609 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1611 Self::Const => write!(f, "constant"),
1612 Self::Static(_) => write!(f, "static"),
1613 Self::ConstFn => write!(f, "constant function"),
1618 // NOTE: `IntoDiagnosticArg` impl for `ConstContext` lives in `rustc_errors`
1619 // due to a cyclical dependency between hir that crate.
1622 pub type Lit = Spanned<LitKind>;
1624 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1631 pub fn hir_id(&self) -> HirId {
1633 &ArrayLen::Infer(hir_id, _) | &ArrayLen::Body(AnonConst { hir_id, .. }) => hir_id,
1638 /// A constant (expression) that's not an item or associated item,
1639 /// but needs its own `DefId` for type-checking, const-eval, etc.
1640 /// These are usually found nested inside types (e.g., array lengths)
1641 /// or expressions (e.g., repeat counts), and also used to define
1642 /// explicit discriminant values for enum variants.
1644 /// You can check if this anon const is a default in a const param
1645 /// `const N: usize = { ... }` with `tcx.hir().opt_const_param_default_param_def_id(..)`
1646 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1647 pub struct AnonConst {
1649 pub def_id: LocalDefId,
1654 #[derive(Debug, HashStable_Generic)]
1655 pub struct Expr<'hir> {
1657 pub kind: ExprKind<'hir>,
1662 pub fn precedence(&self) -> ExprPrecedence {
1664 ExprKind::Box(_) => ExprPrecedence::Box,
1665 ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1666 ExprKind::Array(_) => ExprPrecedence::Array,
1667 ExprKind::Call(..) => ExprPrecedence::Call,
1668 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1669 ExprKind::Tup(_) => ExprPrecedence::Tup,
1670 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1671 ExprKind::Unary(..) => ExprPrecedence::Unary,
1672 ExprKind::Lit(_) => ExprPrecedence::Lit,
1673 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1674 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1675 ExprKind::If(..) => ExprPrecedence::If,
1676 ExprKind::Let(..) => ExprPrecedence::Let,
1677 ExprKind::Loop(..) => ExprPrecedence::Loop,
1678 ExprKind::Match(..) => ExprPrecedence::Match,
1679 ExprKind::Closure { .. } => ExprPrecedence::Closure,
1680 ExprKind::Block(..) => ExprPrecedence::Block,
1681 ExprKind::Assign(..) => ExprPrecedence::Assign,
1682 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1683 ExprKind::Field(..) => ExprPrecedence::Field,
1684 ExprKind::Index(..) => ExprPrecedence::Index,
1685 ExprKind::Path(..) => ExprPrecedence::Path,
1686 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1687 ExprKind::Break(..) => ExprPrecedence::Break,
1688 ExprKind::Continue(..) => ExprPrecedence::Continue,
1689 ExprKind::Ret(..) => ExprPrecedence::Ret,
1690 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1691 ExprKind::Struct(..) => ExprPrecedence::Struct,
1692 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1693 ExprKind::Yield(..) => ExprPrecedence::Yield,
1694 ExprKind::Err => ExprPrecedence::Err,
1698 /// Whether this looks like a place expr, without checking for deref
1700 /// This will return `true` in some potentially surprising cases such as
1701 /// `CONSTANT.field`.
1702 pub fn is_syntactic_place_expr(&self) -> bool {
1703 self.is_place_expr(|_| true)
1706 /// Whether this is a place expression.
1708 /// `allow_projections_from` should return `true` if indexing a field or index expression based
1709 /// on the given expression should be considered a place expression.
1710 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1712 ExprKind::Path(QPath::Resolved(_, ref path)) => {
1713 matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static(_), _) | Res::Err)
1716 // Type ascription inherits its place expression kind from its
1718 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1719 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1721 ExprKind::Unary(UnOp::Deref, _) => true,
1723 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1724 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1727 // Lang item paths cannot currently be local variables or statics.
1728 ExprKind::Path(QPath::LangItem(..)) => false,
1730 // Partially qualified paths in expressions can only legally
1731 // refer to associated items which are always rvalues.
1732 ExprKind::Path(QPath::TypeRelative(..))
1733 | ExprKind::Call(..)
1734 | ExprKind::MethodCall(..)
1735 | ExprKind::Struct(..)
1738 | ExprKind::Match(..)
1739 | ExprKind::Closure { .. }
1740 | ExprKind::Block(..)
1741 | ExprKind::Repeat(..)
1742 | ExprKind::Array(..)
1743 | ExprKind::Break(..)
1744 | ExprKind::Continue(..)
1747 | ExprKind::Loop(..)
1748 | ExprKind::Assign(..)
1749 | ExprKind::InlineAsm(..)
1750 | ExprKind::AssignOp(..)
1752 | ExprKind::ConstBlock(..)
1753 | ExprKind::Unary(..)
1755 | ExprKind::AddrOf(..)
1756 | ExprKind::Binary(..)
1757 | ExprKind::Yield(..)
1758 | ExprKind::Cast(..)
1759 | ExprKind::DropTemps(..)
1760 | ExprKind::Err => false,
1764 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1765 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1766 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1767 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1768 /// beyond remembering to call this function before doing analysis on it.
1769 pub fn peel_drop_temps(&self) -> &Self {
1770 let mut expr = self;
1771 while let ExprKind::DropTemps(inner) = &expr.kind {
1777 pub fn peel_blocks(&self) -> &Self {
1778 let mut expr = self;
1779 while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind {
1785 pub fn can_have_side_effects(&self) -> bool {
1786 match self.peel_drop_temps().kind {
1787 ExprKind::Path(_) | ExprKind::Lit(_) => false,
1788 ExprKind::Type(base, _)
1789 | ExprKind::Unary(_, base)
1790 | ExprKind::Field(base, _)
1791 | ExprKind::Index(base, _)
1792 | ExprKind::AddrOf(.., base)
1793 | ExprKind::Cast(base, _) => {
1794 // This isn't exactly true for `Index` and all `Unary`, but we are using this
1795 // method exclusively for diagnostics and there's a *cultural* pressure against
1796 // them being used only for its side-effects.
1797 base.can_have_side_effects()
1799 ExprKind::Struct(_, fields, init) => fields
1801 .map(|field| field.expr)
1802 .chain(init.into_iter())
1803 .all(|e| e.can_have_side_effects()),
1805 ExprKind::Array(args)
1806 | ExprKind::Tup(args)
1810 ExprKind::Path(QPath::Resolved(
1812 Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. },
1817 ) => args.iter().all(|arg| arg.can_have_side_effects()),
1819 | ExprKind::Match(..)
1820 | ExprKind::MethodCall(..)
1821 | ExprKind::Call(..)
1822 | ExprKind::Closure { .. }
1823 | ExprKind::Block(..)
1824 | ExprKind::Repeat(..)
1825 | ExprKind::Break(..)
1826 | ExprKind::Continue(..)
1829 | ExprKind::Loop(..)
1830 | ExprKind::Assign(..)
1831 | ExprKind::InlineAsm(..)
1832 | ExprKind::AssignOp(..)
1833 | ExprKind::ConstBlock(..)
1835 | ExprKind::Binary(..)
1836 | ExprKind::Yield(..)
1837 | ExprKind::DropTemps(..)
1838 | ExprKind::Err => true,
1842 /// To a first-order approximation, is this a pattern?
1843 pub fn is_approximately_pattern(&self) -> bool {
1846 | ExprKind::Array(_)
1847 | ExprKind::Call(..)
1851 | ExprKind::Struct(..) => true,
1856 pub fn method_ident(&self) -> Option<Ident> {
1858 ExprKind::MethodCall(receiver_method, ..) => Some(receiver_method.ident),
1859 ExprKind::Unary(_, expr) | ExprKind::AddrOf(.., expr) => expr.method_ident(),
1865 /// Checks if the specified expression is a built-in range literal.
1866 /// (See: `LoweringContext::lower_expr()`).
1867 pub fn is_range_literal(expr: &Expr<'_>) -> bool {
1869 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1870 ExprKind::Struct(ref qpath, _, _) => matches!(
1875 | LangItem::RangeFrom
1876 | LangItem::RangeFull
1877 | LangItem::RangeToInclusive,
1882 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1883 ExprKind::Call(ref func, _) => {
1884 matches!(func.kind, ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, ..)))
1891 #[derive(Debug, HashStable_Generic)]
1892 pub enum ExprKind<'hir> {
1893 /// A `box x` expression.
1894 Box(&'hir Expr<'hir>),
1895 /// Allow anonymous constants from an inline `const` block
1896 ConstBlock(AnonConst),
1897 /// An array (e.g., `[a, b, c, d]`).
1898 Array(&'hir [Expr<'hir>]),
1899 /// A function call.
1901 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1902 /// and the second field is the list of arguments.
1903 /// This also represents calling the constructor of
1904 /// tuple-like ADTs such as tuple structs and enum variants.
1905 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1906 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1908 /// The `PathSegment` represents the method name and its generic arguments
1909 /// (within the angle brackets).
1910 /// The `&Expr` is the expression that evaluates
1911 /// to the object on which the method is being called on (the receiver),
1912 /// and the `&[Expr]` is the rest of the arguments.
1913 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1914 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, x, [a, b, c, d], span)`.
1915 /// The final `Span` represents the span of the function and arguments
1916 /// (e.g. `foo::<Bar, Baz>(a, b, c, d)` in `x.foo::<Bar, Baz>(a, b, c, d)`
1918 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1919 /// the `hir_id` of the `MethodCall` node itself.
1921 /// [`type_dependent_def_id`]: ../../rustc_middle/ty/struct.TypeckResults.html#method.type_dependent_def_id
1922 MethodCall(&'hir PathSegment<'hir>, &'hir Expr<'hir>, &'hir [Expr<'hir>], Span),
1923 /// A tuple (e.g., `(a, b, c, d)`).
1924 Tup(&'hir [Expr<'hir>]),
1925 /// A binary operation (e.g., `a + b`, `a * b`).
1926 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1927 /// A unary operation (e.g., `!x`, `*x`).
1928 Unary(UnOp, &'hir Expr<'hir>),
1929 /// A literal (e.g., `1`, `"foo"`).
1931 /// A cast (e.g., `foo as f64`).
1932 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1933 /// A type reference (e.g., `Foo`).
1934 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1935 /// Wraps the expression in a terminating scope.
1936 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1938 /// This construct only exists to tweak the drop order in HIR lowering.
1939 /// An example of that is the desugaring of `for` loops.
1940 DropTemps(&'hir Expr<'hir>),
1941 /// A `let $pat = $expr` expression.
1943 /// These are not `Local` and only occur as expressions.
1944 /// The `let Some(x) = foo()` in `if let Some(x) = foo()` is an example of `Let(..)`.
1945 Let(&'hir Let<'hir>),
1946 /// An `if` block, with an optional else block.
1948 /// I.e., `if <expr> { <expr> } else { <expr> }`.
1949 If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
1950 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1952 /// I.e., `'label: loop { <block> }`.
1954 /// The `Span` is the loop header (`for x in y`/`while let pat = expr`).
1955 Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span),
1956 /// A `match` block, with a source that indicates whether or not it is
1957 /// the result of a desugaring, and if so, which kind.
1958 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1959 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1961 /// The `Span` is the argument block `|...|`.
1963 /// This may also be a generator literal or an `async block` as indicated by the
1964 /// `Option<Movability>`.
1965 Closure(&'hir Closure<'hir>),
1966 /// A block (e.g., `'label: { ... }`).
1967 Block(&'hir Block<'hir>, Option<Label>),
1969 /// An assignment (e.g., `a = foo()`).
1970 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1971 /// An assignment with an operator.
1974 AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1975 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1976 Field(&'hir Expr<'hir>, Ident),
1977 /// An indexing operation (`foo[2]`).
1978 Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1980 /// Path to a definition, possibly containing lifetime or type parameters.
1983 /// A referencing operation (i.e., `&a` or `&mut a`).
1984 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1985 /// A `break`, with an optional label to break.
1986 Break(Destination, Option<&'hir Expr<'hir>>),
1987 /// A `continue`, with an optional label.
1988 Continue(Destination),
1989 /// A `return`, with an optional value to be returned.
1990 Ret(Option<&'hir Expr<'hir>>),
1992 /// Inline assembly (from `asm!`), with its outputs and inputs.
1993 InlineAsm(&'hir InlineAsm<'hir>),
1995 /// A struct or struct-like variant literal expression.
1997 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1998 /// where `base` is the `Option<Expr>`.
1999 Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], Option<&'hir Expr<'hir>>),
2001 /// An array literal constructed from one repeated element.
2003 /// E.g., `[1; 5]`. The first expression is the element
2004 /// to be repeated; the second is the number of times to repeat it.
2005 Repeat(&'hir Expr<'hir>, ArrayLen),
2007 /// A suspension point for generators (i.e., `yield <expr>`).
2008 Yield(&'hir Expr<'hir>, YieldSource),
2010 /// A placeholder for an expression that wasn't syntactically well formed in some way.
2014 /// Represents an optionally `Self`-qualified value/type path or associated extension.
2016 /// To resolve the path to a `DefId`, call [`qpath_res`].
2018 /// [`qpath_res`]: ../../rustc_middle/ty/struct.TypeckResults.html#method.qpath_res
2019 #[derive(Debug, HashStable_Generic)]
2020 pub enum QPath<'hir> {
2021 /// Path to a definition, optionally "fully-qualified" with a `Self`
2022 /// type, if the path points to an associated item in a trait.
2024 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
2025 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
2026 /// even though they both have the same two-segment `Clone::clone` `Path`.
2027 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
2029 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
2030 /// Will be resolved by type-checking to an associated item.
2032 /// UFCS source paths can desugar into this, with `Vec::new` turning into
2033 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
2034 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
2035 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
2037 /// Reference to a `#[lang = "foo"]` item. `HirId` of the inner expr.
2038 LangItem(LangItem, Span, Option<HirId>),
2041 impl<'hir> QPath<'hir> {
2042 /// Returns the span of this `QPath`.
2043 pub fn span(&self) -> Span {
2045 QPath::Resolved(_, path) => path.span,
2046 QPath::TypeRelative(qself, ps) => qself.span.to(ps.ident.span),
2047 QPath::LangItem(_, span, _) => span,
2051 /// Returns the span of the qself of this `QPath`. For example, `()` in
2052 /// `<() as Trait>::method`.
2053 pub fn qself_span(&self) -> Span {
2055 QPath::Resolved(_, path) => path.span,
2056 QPath::TypeRelative(qself, _) => qself.span,
2057 QPath::LangItem(_, span, _) => span,
2061 /// Returns the span of the last segment of this `QPath`. For example, `method` in
2062 /// `<() as Trait>::method`.
2063 pub fn last_segment_span(&self) -> Span {
2065 QPath::Resolved(_, path) => path.segments.last().unwrap().ident.span,
2066 QPath::TypeRelative(_, segment) => segment.ident.span,
2067 QPath::LangItem(_, span, _) => span,
2072 /// Hints at the original code for a let statement.
2073 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2074 pub enum LocalSource {
2075 /// A `match _ { .. }`.
2077 /// When lowering async functions, we create locals within the `async move` so that
2078 /// all parameters are dropped after the future is polled.
2080 /// ```ignore (pseudo-Rust)
2081 /// async fn foo(<pattern> @ x: Type) {
2083 /// let <pattern> = x;
2088 /// A desugared `<expr>.await`.
2090 /// A desugared `expr = expr`, where the LHS is a tuple, struct or array.
2091 /// The span is that of the `=` sign.
2092 AssignDesugar(Span),
2095 /// Hints at the original code for a `match _ { .. }`.
2096 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
2097 #[derive(HashStable_Generic)]
2098 pub enum MatchSource {
2099 /// A `match _ { .. }`.
2101 /// A desugared `for _ in _ { .. }` loop.
2103 /// A desugared `?` operator.
2105 /// A desugared `<expr>.await`.
2111 pub const fn name(self) -> &'static str {
2115 ForLoopDesugar => "for",
2117 AwaitDesugar => ".await",
2122 /// The loop type that yielded an `ExprKind::Loop`.
2123 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2124 pub enum LoopSource {
2125 /// A `loop { .. }` loop.
2127 /// A `while _ { .. }` loop.
2129 /// A `for _ in _ { .. }` loop.
2134 pub fn name(self) -> &'static str {
2136 LoopSource::Loop => "loop",
2137 LoopSource::While => "while",
2138 LoopSource::ForLoop => "for",
2143 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2144 pub enum LoopIdError {
2146 UnlabeledCfInWhileCondition,
2150 impl fmt::Display for LoopIdError {
2151 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2152 f.write_str(match self {
2153 LoopIdError::OutsideLoopScope => "not inside loop scope",
2154 LoopIdError::UnlabeledCfInWhileCondition => {
2155 "unlabeled control flow (break or continue) in while condition"
2157 LoopIdError::UnresolvedLabel => "label not found",
2162 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2163 pub struct Destination {
2164 /// This is `Some(_)` iff there is an explicit user-specified 'label
2165 pub label: Option<Label>,
2167 /// These errors are caught and then reported during the diagnostics pass in
2168 /// `librustc_passes/loops.rs`
2169 pub target_id: Result<HirId, LoopIdError>,
2172 /// The yield kind that caused an `ExprKind::Yield`.
2173 #[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
2174 pub enum YieldSource {
2175 /// An `<expr>.await`.
2176 Await { expr: Option<HirId> },
2177 /// A plain `yield`.
2182 pub fn is_await(&self) -> bool {
2183 matches!(self, YieldSource::Await { .. })
2187 impl fmt::Display for YieldSource {
2188 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2189 f.write_str(match self {
2190 YieldSource::Await { .. } => "`await`",
2191 YieldSource::Yield => "`yield`",
2196 impl From<GeneratorKind> for YieldSource {
2197 fn from(kind: GeneratorKind) -> Self {
2199 // Guess based on the kind of the current generator.
2200 GeneratorKind::Gen => Self::Yield,
2201 GeneratorKind::Async(_) => Self::Await { expr: None },
2206 // N.B., if you change this, you'll probably want to change the corresponding
2207 // type structure in middle/ty.rs as well.
2208 #[derive(Debug, HashStable_Generic)]
2209 pub struct MutTy<'hir> {
2210 pub ty: &'hir Ty<'hir>,
2211 pub mutbl: Mutability,
2214 /// Represents a function's signature in a trait declaration,
2215 /// trait implementation, or a free function.
2216 #[derive(Debug, HashStable_Generic)]
2217 pub struct FnSig<'hir> {
2218 pub header: FnHeader,
2219 pub decl: &'hir FnDecl<'hir>,
2223 // The bodies for items are stored "out of line", in a separate
2224 // hashmap in the `Crate`. Here we just record the hir-id of the item
2225 // so it can fetched later.
2226 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2227 pub struct TraitItemId {
2228 pub owner_id: OwnerId,
2233 pub fn hir_id(&self) -> HirId {
2234 // Items are always HIR owners.
2235 HirId::make_owner(self.owner_id.def_id)
2239 /// Represents an item declaration within a trait declaration,
2240 /// possibly including a default implementation. A trait item is
2241 /// either required (meaning it doesn't have an implementation, just a
2242 /// signature) or provided (meaning it has a default implementation).
2243 #[derive(Debug, HashStable_Generic)]
2244 pub struct TraitItem<'hir> {
2246 pub owner_id: OwnerId,
2247 pub generics: &'hir Generics<'hir>,
2248 pub kind: TraitItemKind<'hir>,
2250 pub defaultness: Defaultness,
2253 impl TraitItem<'_> {
2255 pub fn hir_id(&self) -> HirId {
2256 // Items are always HIR owners.
2257 HirId::make_owner(self.owner_id.def_id)
2260 pub fn trait_item_id(&self) -> TraitItemId {
2261 TraitItemId { owner_id: self.owner_id }
2265 /// Represents a trait method's body (or just argument names).
2266 #[derive(Encodable, Debug, HashStable_Generic)]
2267 pub enum TraitFn<'hir> {
2268 /// No default body in the trait, just a signature.
2269 Required(&'hir [Ident]),
2271 /// Both signature and body are provided in the trait.
2275 /// Represents a trait method or associated constant or type
2276 #[derive(Debug, HashStable_Generic)]
2277 pub enum TraitItemKind<'hir> {
2278 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
2279 Const(&'hir Ty<'hir>, Option<BodyId>),
2280 /// An associated function with an optional body.
2281 Fn(FnSig<'hir>, TraitFn<'hir>),
2282 /// An associated type with (possibly empty) bounds and optional concrete
2284 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
2287 // The bodies for items are stored "out of line", in a separate
2288 // hashmap in the `Crate`. Here we just record the hir-id of the item
2289 // so it can fetched later.
2290 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2291 pub struct ImplItemId {
2292 pub owner_id: OwnerId,
2297 pub fn hir_id(&self) -> HirId {
2298 // Items are always HIR owners.
2299 HirId::make_owner(self.owner_id.def_id)
2303 /// Represents anything within an `impl` block.
2304 #[derive(Debug, HashStable_Generic)]
2305 pub struct ImplItem<'hir> {
2307 pub owner_id: OwnerId,
2308 pub generics: &'hir Generics<'hir>,
2309 pub kind: ImplItemKind<'hir>,
2310 pub defaultness: Defaultness,
2317 pub fn hir_id(&self) -> HirId {
2318 // Items are always HIR owners.
2319 HirId::make_owner(self.owner_id.def_id)
2322 pub fn impl_item_id(&self) -> ImplItemId {
2323 ImplItemId { owner_id: self.owner_id }
2327 /// Represents various kinds of content within an `impl`.
2328 #[derive(Debug, HashStable_Generic)]
2329 pub enum ImplItemKind<'hir> {
2330 /// An associated constant of the given type, set to the constant result
2331 /// of the expression.
2332 Const(&'hir Ty<'hir>, BodyId),
2333 /// An associated function implementation with the given signature and body.
2334 Fn(FnSig<'hir>, BodyId),
2335 /// An associated type.
2336 Type(&'hir Ty<'hir>),
2339 /// The name of the associated type for `Fn` return types.
2340 pub const FN_OUTPUT_NAME: Symbol = sym::Output;
2342 /// Bind a type to an associated type (i.e., `A = Foo`).
2344 /// Bindings like `A: Debug` are represented as a special type `A =
2345 /// $::Debug` that is understood by the astconv code.
2347 /// FIXME(alexreg): why have a separate type for the binding case,
2348 /// wouldn't it be better to make the `ty` field an enum like the
2351 /// ```ignore (pseudo-rust)
2352 /// enum TypeBindingKind {
2357 #[derive(Debug, HashStable_Generic)]
2358 pub struct TypeBinding<'hir> {
2361 pub gen_args: &'hir GenericArgs<'hir>,
2362 pub kind: TypeBindingKind<'hir>,
2366 #[derive(Debug, HashStable_Generic)]
2367 pub enum Term<'hir> {
2372 impl<'hir> From<&'hir Ty<'hir>> for Term<'hir> {
2373 fn from(ty: &'hir Ty<'hir>) -> Self {
2378 impl<'hir> From<AnonConst> for Term<'hir> {
2379 fn from(c: AnonConst) -> Self {
2384 // Represents the two kinds of type bindings.
2385 #[derive(Debug, HashStable_Generic)]
2386 pub enum TypeBindingKind<'hir> {
2387 /// E.g., `Foo<Bar: Send>`.
2388 Constraint { bounds: &'hir [GenericBound<'hir>] },
2389 /// E.g., `Foo<Bar = ()>`, `Foo<Bar = ()>`
2390 Equality { term: Term<'hir> },
2393 impl TypeBinding<'_> {
2394 pub fn ty(&self) -> &Ty<'_> {
2396 TypeBindingKind::Equality { term: Term::Ty(ref ty) } => ty,
2397 _ => panic!("expected equality type binding for parenthesized generic args"),
2400 pub fn opt_const(&self) -> Option<&'_ AnonConst> {
2402 TypeBindingKind::Equality { term: Term::Const(ref c) } => Some(c),
2408 #[derive(Debug, HashStable_Generic)]
2409 pub struct Ty<'hir> {
2411 pub kind: TyKind<'hir>,
2415 impl<'hir> Ty<'hir> {
2416 /// Returns `true` if `param_def_id` matches the `bounded_ty` of this predicate.
2417 pub fn as_generic_param(&self) -> Option<(DefId, Ident)> {
2418 let TyKind::Path(QPath::Resolved(None, path)) = self.kind else {
2421 let [segment] = &path.segments else {
2425 Res::Def(DefKind::TyParam, def_id) | Res::SelfTyParam { trait_: def_id } => {
2426 Some((def_id, segment.ident))
2432 pub fn peel_refs(&self) -> &Self {
2433 let mut final_ty = self;
2434 while let TyKind::Ref(_, MutTy { ty, .. }) = &final_ty.kind {
2440 pub fn find_self_aliases(&self) -> Vec<Span> {
2441 use crate::intravisit::Visitor;
2442 struct MyVisitor(Vec<Span>);
2443 impl<'v> Visitor<'v> for MyVisitor {
2444 fn visit_ty(&mut self, t: &'v Ty<'v>) {
2447 TyKind::Path(QPath::Resolved(
2449 Path { res: crate::def::Res::SelfTyAlias { .. }, .. },
2452 self.0.push(t.span);
2455 crate::intravisit::walk_ty(self, t);
2459 let mut my_visitor = MyVisitor(vec![]);
2460 my_visitor.visit_ty(self);
2465 /// Not represented directly in the AST; referred to by name through a `ty_path`.
2466 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
2467 #[derive(HashStable_Generic)]
2478 /// All of the primitive types
2479 pub const ALL: [Self; 17] = [
2480 // any changes here should also be reflected in `PrimTy::from_name`
2481 Self::Int(IntTy::I8),
2482 Self::Int(IntTy::I16),
2483 Self::Int(IntTy::I32),
2484 Self::Int(IntTy::I64),
2485 Self::Int(IntTy::I128),
2486 Self::Int(IntTy::Isize),
2487 Self::Uint(UintTy::U8),
2488 Self::Uint(UintTy::U16),
2489 Self::Uint(UintTy::U32),
2490 Self::Uint(UintTy::U64),
2491 Self::Uint(UintTy::U128),
2492 Self::Uint(UintTy::Usize),
2493 Self::Float(FloatTy::F32),
2494 Self::Float(FloatTy::F64),
2500 /// Like [`PrimTy::name`], but returns a &str instead of a symbol.
2503 pub fn name_str(self) -> &'static str {
2505 PrimTy::Int(i) => i.name_str(),
2506 PrimTy::Uint(u) => u.name_str(),
2507 PrimTy::Float(f) => f.name_str(),
2508 PrimTy::Str => "str",
2509 PrimTy::Bool => "bool",
2510 PrimTy::Char => "char",
2514 pub fn name(self) -> Symbol {
2516 PrimTy::Int(i) => i.name(),
2517 PrimTy::Uint(u) => u.name(),
2518 PrimTy::Float(f) => f.name(),
2519 PrimTy::Str => sym::str,
2520 PrimTy::Bool => sym::bool,
2521 PrimTy::Char => sym::char,
2525 /// Returns the matching `PrimTy` for a `Symbol` such as "str" or "i32".
2526 /// Returns `None` if no matching type is found.
2527 pub fn from_name(name: Symbol) -> Option<Self> {
2528 let ty = match name {
2529 // any changes here should also be reflected in `PrimTy::ALL`
2530 sym::i8 => Self::Int(IntTy::I8),
2531 sym::i16 => Self::Int(IntTy::I16),
2532 sym::i32 => Self::Int(IntTy::I32),
2533 sym::i64 => Self::Int(IntTy::I64),
2534 sym::i128 => Self::Int(IntTy::I128),
2535 sym::isize => Self::Int(IntTy::Isize),
2536 sym::u8 => Self::Uint(UintTy::U8),
2537 sym::u16 => Self::Uint(UintTy::U16),
2538 sym::u32 => Self::Uint(UintTy::U32),
2539 sym::u64 => Self::Uint(UintTy::U64),
2540 sym::u128 => Self::Uint(UintTy::U128),
2541 sym::usize => Self::Uint(UintTy::Usize),
2542 sym::f32 => Self::Float(FloatTy::F32),
2543 sym::f64 => Self::Float(FloatTy::F64),
2544 sym::bool => Self::Bool,
2545 sym::char => Self::Char,
2546 sym::str => Self::Str,
2553 #[derive(Debug, HashStable_Generic)]
2554 pub struct BareFnTy<'hir> {
2555 pub unsafety: Unsafety,
2557 pub generic_params: &'hir [GenericParam<'hir>],
2558 pub decl: &'hir FnDecl<'hir>,
2559 pub param_names: &'hir [Ident],
2562 #[derive(Debug, HashStable_Generic)]
2563 pub struct OpaqueTy<'hir> {
2564 pub generics: &'hir Generics<'hir>,
2565 pub bounds: GenericBounds<'hir>,
2566 pub origin: OpaqueTyOrigin,
2570 /// From whence the opaque type came.
2571 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2572 pub enum OpaqueTyOrigin {
2574 FnReturn(LocalDefId),
2576 AsyncFn(LocalDefId),
2577 /// type aliases: `type Foo = impl Trait;`
2581 /// The various kinds of types recognized by the compiler.
2582 #[derive(Debug, HashStable_Generic)]
2583 pub enum TyKind<'hir> {
2584 /// A variable length slice (i.e., `[T]`).
2585 Slice(&'hir Ty<'hir>),
2586 /// A fixed length array (i.e., `[T; n]`).
2587 Array(&'hir Ty<'hir>, ArrayLen),
2588 /// A raw pointer (i.e., `*const T` or `*mut T`).
2590 /// A reference (i.e., `&'a T` or `&'a mut T`).
2591 Ref(&'hir Lifetime, MutTy<'hir>),
2592 /// A bare function (e.g., `fn(usize) -> bool`).
2593 BareFn(&'hir BareFnTy<'hir>),
2594 /// The never type (`!`).
2596 /// A tuple (`(A, B, C, D, ...)`).
2597 Tup(&'hir [Ty<'hir>]),
2598 /// A path to a type definition (`module::module::...::Type`), or an
2599 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2601 /// Type parameters may be stored in each `PathSegment`.
2603 /// An opaque type definition itself. This is only used for `impl Trait`.
2605 /// The generic argument list contains the lifetimes (and in the future
2606 /// possibly parameters) that are actually bound on the `impl Trait`.
2608 /// The last parameter specifies whether this opaque appears in a trait definition.
2609 OpaqueDef(ItemId, &'hir [GenericArg<'hir>], bool),
2610 /// A trait object type `Bound1 + Bound2 + Bound3`
2611 /// where `Bound` is a trait or a lifetime.
2612 TraitObject(&'hir [PolyTraitRef<'hir>], &'hir Lifetime, TraitObjectSyntax),
2615 /// `TyKind::Infer` means the type should be inferred instead of it having been
2616 /// specified. This can appear anywhere in a type.
2618 /// Placeholder for a type that has failed to be defined.
2622 #[derive(Debug, HashStable_Generic)]
2623 pub enum InlineAsmOperand<'hir> {
2625 reg: InlineAsmRegOrRegClass,
2626 expr: &'hir Expr<'hir>,
2629 reg: InlineAsmRegOrRegClass,
2631 expr: Option<&'hir Expr<'hir>>,
2634 reg: InlineAsmRegOrRegClass,
2636 expr: &'hir Expr<'hir>,
2639 reg: InlineAsmRegOrRegClass,
2641 in_expr: &'hir Expr<'hir>,
2642 out_expr: Option<&'hir Expr<'hir>>,
2645 anon_const: AnonConst,
2648 anon_const: AnonConst,
2656 impl<'hir> InlineAsmOperand<'hir> {
2657 pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
2659 Self::In { reg, .. }
2660 | Self::Out { reg, .. }
2661 | Self::InOut { reg, .. }
2662 | Self::SplitInOut { reg, .. } => Some(reg),
2663 Self::Const { .. } | Self::SymFn { .. } | Self::SymStatic { .. } => None,
2667 pub fn is_clobber(&self) -> bool {
2670 InlineAsmOperand::Out { reg: InlineAsmRegOrRegClass::Reg(_), late: _, expr: None }
2675 #[derive(Debug, HashStable_Generic)]
2676 pub struct InlineAsm<'hir> {
2677 pub template: &'hir [InlineAsmTemplatePiece],
2678 pub template_strs: &'hir [(Symbol, Option<Symbol>, Span)],
2679 pub operands: &'hir [(InlineAsmOperand<'hir>, Span)],
2680 pub options: InlineAsmOptions,
2681 pub line_spans: &'hir [Span],
2684 /// Represents a parameter in a function header.
2685 #[derive(Debug, HashStable_Generic)]
2686 pub struct Param<'hir> {
2688 pub pat: &'hir Pat<'hir>,
2693 /// Represents the header (not the body) of a function declaration.
2694 #[derive(Debug, HashStable_Generic)]
2695 pub struct FnDecl<'hir> {
2696 /// The types of the function's parameters.
2698 /// Additional argument data is stored in the function's [body](Body::params).
2699 pub inputs: &'hir [Ty<'hir>],
2700 pub output: FnRetTy<'hir>,
2701 pub c_variadic: bool,
2702 /// Does the function have an implicit self?
2703 pub implicit_self: ImplicitSelfKind,
2704 /// Is lifetime elision allowed.
2705 pub lifetime_elision_allowed: bool,
2708 /// Represents what type of implicit self a function has, if any.
2709 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2710 pub enum ImplicitSelfKind {
2711 /// Represents a `fn x(self);`.
2713 /// Represents a `fn x(mut self);`.
2715 /// Represents a `fn x(&self);`.
2717 /// Represents a `fn x(&mut self);`.
2719 /// Represents when a function does not have a self argument or
2720 /// when a function has a `self: X` argument.
2724 impl ImplicitSelfKind {
2725 /// Does this represent an implicit self?
2726 pub fn has_implicit_self(&self) -> bool {
2727 !matches!(*self, ImplicitSelfKind::None)
2731 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable, Debug)]
2732 #[derive(HashStable_Generic)]
2739 pub fn is_async(self) -> bool {
2740 self == IsAsync::Async
2744 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable, HashStable_Generic)]
2745 pub enum Defaultness {
2746 Default { has_value: bool },
2751 pub fn has_value(&self) -> bool {
2753 Defaultness::Default { has_value } => has_value,
2754 Defaultness::Final => true,
2758 pub fn is_final(&self) -> bool {
2759 *self == Defaultness::Final
2762 pub fn is_default(&self) -> bool {
2763 matches!(*self, Defaultness::Default { .. })
2767 #[derive(Debug, HashStable_Generic)]
2768 pub enum FnRetTy<'hir> {
2769 /// Return type is not specified.
2771 /// Functions default to `()` and
2772 /// closures default to inference. Span points to where return
2773 /// type would be inserted.
2774 DefaultReturn(Span),
2775 /// Everything else.
2776 Return(&'hir Ty<'hir>),
2781 pub fn span(&self) -> Span {
2783 Self::DefaultReturn(span) => span,
2784 Self::Return(ref ty) => ty.span,
2789 /// Represents `for<...>` binder before a closure
2790 #[derive(Copy, Clone, Debug, HashStable_Generic)]
2791 pub enum ClosureBinder {
2792 /// Binder is not specified.
2794 /// Binder is specified.
2796 /// Span points to the whole `for<...>`.
2800 #[derive(Encodable, Debug, HashStable_Generic)]
2801 pub struct Mod<'hir> {
2802 pub spans: ModSpans,
2803 pub item_ids: &'hir [ItemId],
2806 #[derive(Copy, Clone, Debug, HashStable_Generic, Encodable)]
2807 pub struct ModSpans {
2808 /// A span from the first token past `{` to the last token until `}`.
2809 /// For `mod foo;`, the inner span ranges from the first token
2810 /// to the last token in the external file.
2811 pub inner_span: Span,
2812 pub inject_use_span: Span,
2815 #[derive(Debug, HashStable_Generic)]
2816 pub struct EnumDef<'hir> {
2817 pub variants: &'hir [Variant<'hir>],
2820 #[derive(Debug, HashStable_Generic)]
2821 pub struct Variant<'hir> {
2822 /// Name of the variant.
2824 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2826 pub def_id: LocalDefId,
2827 /// Fields and constructor id of the variant.
2828 pub data: VariantData<'hir>,
2829 /// Explicit discriminant (e.g., `Foo = 1`).
2830 pub disr_expr: Option<AnonConst>,
2835 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2837 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2838 /// Also produced for each element of a list `use`, e.g.
2839 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2842 /// Glob import, e.g., `use foo::*`.
2845 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2846 /// an additional `use foo::{}` for performing checks such as
2847 /// unstable feature gating. May be removed in the future.
2851 /// References to traits in impls.
2853 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2854 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2855 /// trait being referred to but just a unique `HirId` that serves as a key
2856 /// within the resolution map.
2857 #[derive(Clone, Debug, HashStable_Generic)]
2858 pub struct TraitRef<'hir> {
2859 pub path: &'hir Path<'hir>,
2860 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2861 #[stable_hasher(ignore)]
2862 pub hir_ref_id: HirId,
2866 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2867 pub fn trait_def_id(&self) -> Option<DefId> {
2868 match self.path.res {
2869 Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
2871 _ => unreachable!(),
2876 #[derive(Clone, Debug, HashStable_Generic)]
2877 pub struct PolyTraitRef<'hir> {
2878 /// The `'a` in `for<'a> Foo<&'a T>`.
2879 pub bound_generic_params: &'hir [GenericParam<'hir>],
2881 /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
2882 pub trait_ref: TraitRef<'hir>,
2887 #[derive(Debug, HashStable_Generic)]
2888 pub struct FieldDef<'hir> {
2893 pub def_id: LocalDefId,
2894 pub ty: &'hir Ty<'hir>,
2898 // Still necessary in couple of places
2899 pub fn is_positional(&self) -> bool {
2900 let first = self.ident.as_str().as_bytes()[0];
2901 (b'0'..=b'9').contains(&first)
2905 /// Fields and constructor IDs of enum variants and structs.
2906 #[derive(Debug, HashStable_Generic)]
2907 pub enum VariantData<'hir> {
2908 /// A struct variant.
2910 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2911 Struct(&'hir [FieldDef<'hir>], /* recovered */ bool),
2912 /// A tuple variant.
2914 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2915 Tuple(&'hir [FieldDef<'hir>], HirId, LocalDefId),
2918 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2919 Unit(HirId, LocalDefId),
2922 impl<'hir> VariantData<'hir> {
2923 /// Return the fields of this variant.
2924 pub fn fields(&self) -> &'hir [FieldDef<'hir>] {
2926 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2931 pub fn ctor(&self) -> Option<(CtorKind, HirId, LocalDefId)> {
2933 VariantData::Tuple(_, hir_id, def_id) => Some((CtorKind::Fn, hir_id, def_id)),
2934 VariantData::Unit(hir_id, def_id) => Some((CtorKind::Const, hir_id, def_id)),
2935 VariantData::Struct(..) => None,
2940 pub fn ctor_kind(&self) -> Option<CtorKind> {
2941 self.ctor().map(|(kind, ..)| kind)
2944 /// Return the `HirId` of this variant's constructor, if it has one.
2946 pub fn ctor_hir_id(&self) -> Option<HirId> {
2947 self.ctor().map(|(_, hir_id, _)| hir_id)
2950 /// Return the `LocalDefId` of this variant's constructor, if it has one.
2952 pub fn ctor_def_id(&self) -> Option<LocalDefId> {
2953 self.ctor().map(|(.., def_id)| def_id)
2957 // The bodies for items are stored "out of line", in a separate
2958 // hashmap in the `Crate`. Here we just record the hir-id of the item
2959 // so it can fetched later.
2960 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
2962 pub owner_id: OwnerId,
2967 pub fn hir_id(&self) -> HirId {
2968 // Items are always HIR owners.
2969 HirId::make_owner(self.owner_id.def_id)
2975 /// The name might be a dummy name in case of anonymous items
2976 #[derive(Debug, HashStable_Generic)]
2977 pub struct Item<'hir> {
2979 pub owner_id: OwnerId,
2980 pub kind: ItemKind<'hir>,
2987 pub fn hir_id(&self) -> HirId {
2988 // Items are always HIR owners.
2989 HirId::make_owner(self.owner_id.def_id)
2992 pub fn item_id(&self) -> ItemId {
2993 ItemId { owner_id: self.owner_id }
2997 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2998 #[derive(Encodable, Decodable, HashStable_Generic)]
3005 pub fn prefix_str(&self) -> &'static str {
3007 Self::Unsafe => "unsafe ",
3013 impl fmt::Display for Unsafety {
3014 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3015 f.write_str(match *self {
3016 Self::Unsafe => "unsafe",
3017 Self::Normal => "normal",
3022 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
3023 #[derive(Encodable, Decodable, HashStable_Generic)]
3024 pub enum Constness {
3029 impl fmt::Display for Constness {
3030 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3031 f.write_str(match *self {
3032 Self::Const => "const",
3033 Self::NotConst => "non-const",
3038 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
3039 pub struct FnHeader {
3040 pub unsafety: Unsafety,
3041 pub constness: Constness,
3042 pub asyncness: IsAsync,
3047 pub fn is_async(&self) -> bool {
3048 matches!(&self.asyncness, IsAsync::Async)
3051 pub fn is_const(&self) -> bool {
3052 matches!(&self.constness, Constness::Const)
3055 pub fn is_unsafe(&self) -> bool {
3056 matches!(&self.unsafety, Unsafety::Unsafe)
3060 #[derive(Debug, HashStable_Generic)]
3061 pub enum ItemKind<'hir> {
3062 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
3064 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
3065 ExternCrate(Option<Symbol>),
3067 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
3071 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
3072 Use(&'hir UsePath<'hir>, UseKind),
3074 /// A `static` item.
3075 Static(&'hir Ty<'hir>, Mutability, BodyId),
3077 Const(&'hir Ty<'hir>, BodyId),
3078 /// A function declaration.
3079 Fn(FnSig<'hir>, &'hir Generics<'hir>, BodyId),
3080 /// A MBE macro definition (`macro_rules!` or `macro`).
3081 Macro(ast::MacroDef, MacroKind),
3083 Mod(&'hir Mod<'hir>),
3084 /// An external module, e.g. `extern { .. }`.
3085 ForeignMod { abi: Abi, items: &'hir [ForeignItemRef] },
3086 /// Module-level inline assembly (from `global_asm!`).
3087 GlobalAsm(&'hir InlineAsm<'hir>),
3088 /// A type alias, e.g., `type Foo = Bar<u8>`.
3089 TyAlias(&'hir Ty<'hir>, &'hir Generics<'hir>),
3090 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
3091 OpaqueTy(OpaqueTy<'hir>),
3092 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
3093 Enum(EnumDef<'hir>, &'hir Generics<'hir>),
3094 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
3095 Struct(VariantData<'hir>, &'hir Generics<'hir>),
3096 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
3097 Union(VariantData<'hir>, &'hir Generics<'hir>),
3098 /// A trait definition.
3099 Trait(IsAuto, Unsafety, &'hir Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
3101 TraitAlias(&'hir Generics<'hir>, GenericBounds<'hir>),
3103 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
3104 Impl(&'hir Impl<'hir>),
3107 #[derive(Debug, HashStable_Generic)]
3108 pub struct Impl<'hir> {
3109 pub unsafety: Unsafety,
3110 pub polarity: ImplPolarity,
3111 pub defaultness: Defaultness,
3112 // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata
3113 // decoding as `Span`s cannot be decoded when a `Session` is not available.
3114 pub defaultness_span: Option<Span>,
3115 pub constness: Constness,
3116 pub generics: &'hir Generics<'hir>,
3118 /// The trait being implemented, if any.
3119 pub of_trait: Option<TraitRef<'hir>>,
3121 pub self_ty: &'hir Ty<'hir>,
3122 pub items: &'hir [ImplItemRef],
3126 pub fn generics(&self) -> Option<&Generics<'_>> {
3128 ItemKind::Fn(_, ref generics, _)
3129 | ItemKind::TyAlias(_, ref generics)
3130 | ItemKind::OpaqueTy(OpaqueTy { ref generics, .. })
3131 | ItemKind::Enum(_, ref generics)
3132 | ItemKind::Struct(_, ref generics)
3133 | ItemKind::Union(_, ref generics)
3134 | ItemKind::Trait(_, _, ref generics, _, _)
3135 | ItemKind::TraitAlias(ref generics, _)
3136 | ItemKind::Impl(Impl { ref generics, .. }) => generics,
3141 pub fn descr(&self) -> &'static str {
3143 ItemKind::ExternCrate(..) => "extern crate",
3144 ItemKind::Use(..) => "`use` import",
3145 ItemKind::Static(..) => "static item",
3146 ItemKind::Const(..) => "constant item",
3147 ItemKind::Fn(..) => "function",
3148 ItemKind::Macro(..) => "macro",
3149 ItemKind::Mod(..) => "module",
3150 ItemKind::ForeignMod { .. } => "extern block",
3151 ItemKind::GlobalAsm(..) => "global asm item",
3152 ItemKind::TyAlias(..) => "type alias",
3153 ItemKind::OpaqueTy(..) => "opaque type",
3154 ItemKind::Enum(..) => "enum",
3155 ItemKind::Struct(..) => "struct",
3156 ItemKind::Union(..) => "union",
3157 ItemKind::Trait(..) => "trait",
3158 ItemKind::TraitAlias(..) => "trait alias",
3159 ItemKind::Impl(..) => "implementation",
3164 /// A reference from an trait to one of its associated items. This
3165 /// contains the item's id, naturally, but also the item's name and
3166 /// some other high-level details (like whether it is an associated
3167 /// type or method, and whether it is public). This allows other
3168 /// passes to find the impl they want without loading the ID (which
3169 /// means fewer edges in the incremental compilation graph).
3170 #[derive(Encodable, Debug, HashStable_Generic)]
3171 pub struct TraitItemRef {
3172 pub id: TraitItemId,
3174 pub kind: AssocItemKind,
3178 /// A reference from an impl to one of its associated items. This
3179 /// contains the item's ID, naturally, but also the item's name and
3180 /// some other high-level details (like whether it is an associated
3181 /// type or method, and whether it is public). This allows other
3182 /// passes to find the impl they want without loading the ID (which
3183 /// means fewer edges in the incremental compilation graph).
3184 #[derive(Debug, HashStable_Generic)]
3185 pub struct ImplItemRef {
3188 pub kind: AssocItemKind,
3190 /// When we are in a trait impl, link to the trait-item's id.
3191 pub trait_item_def_id: Option<DefId>,
3194 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
3195 pub enum AssocItemKind {
3197 Fn { has_self: bool },
3201 // The bodies for items are stored "out of line", in a separate
3202 // hashmap in the `Crate`. Here we just record the hir-id of the item
3203 // so it can fetched later.
3204 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3205 pub struct ForeignItemId {
3206 pub owner_id: OwnerId,
3209 impl ForeignItemId {
3211 pub fn hir_id(&self) -> HirId {
3212 // Items are always HIR owners.
3213 HirId::make_owner(self.owner_id.def_id)
3217 /// A reference from a foreign block to one of its items. This
3218 /// contains the item's ID, naturally, but also the item's name and
3219 /// some other high-level details (like whether it is an associated
3220 /// type or method, and whether it is public). This allows other
3221 /// passes to find the impl they want without loading the ID (which
3222 /// means fewer edges in the incremental compilation graph).
3223 #[derive(Debug, HashStable_Generic)]
3224 pub struct ForeignItemRef {
3225 pub id: ForeignItemId,
3230 #[derive(Debug, HashStable_Generic)]
3231 pub struct ForeignItem<'hir> {
3233 pub kind: ForeignItemKind<'hir>,
3234 pub owner_id: OwnerId,
3239 impl ForeignItem<'_> {
3241 pub fn hir_id(&self) -> HirId {
3242 // Items are always HIR owners.
3243 HirId::make_owner(self.owner_id.def_id)
3246 pub fn foreign_item_id(&self) -> ForeignItemId {
3247 ForeignItemId { owner_id: self.owner_id }
3251 /// An item within an `extern` block.
3252 #[derive(Debug, HashStable_Generic)]
3253 pub enum ForeignItemKind<'hir> {
3254 /// A foreign function.
3255 Fn(&'hir FnDecl<'hir>, &'hir [Ident], &'hir Generics<'hir>),
3256 /// A foreign static item (`static ext: u8`).
3257 Static(&'hir Ty<'hir>, Mutability),
3262 /// A variable captured by a closure.
3263 #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)]
3265 /// First span where it is accessed (there can be multiple).
3269 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
3270 // has length > 0 if the trait is found through an chain of imports, starting with the
3271 // import/use statement in the scope where the trait is used.
3272 #[derive(Encodable, Decodable, Clone, Debug, HashStable_Generic)]
3273 pub struct TraitCandidate {
3275 pub import_ids: SmallVec<[LocalDefId; 1]>,
3278 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3279 pub enum OwnerNode<'hir> {
3280 Item(&'hir Item<'hir>),
3281 ForeignItem(&'hir ForeignItem<'hir>),
3282 TraitItem(&'hir TraitItem<'hir>),
3283 ImplItem(&'hir ImplItem<'hir>),
3284 Crate(&'hir Mod<'hir>),
3287 impl<'hir> OwnerNode<'hir> {
3288 pub fn ident(&self) -> Option<Ident> {
3290 OwnerNode::Item(Item { ident, .. })
3291 | OwnerNode::ForeignItem(ForeignItem { ident, .. })
3292 | OwnerNode::ImplItem(ImplItem { ident, .. })
3293 | OwnerNode::TraitItem(TraitItem { ident, .. }) => Some(*ident),
3294 OwnerNode::Crate(..) => None,
3298 pub fn span(&self) -> Span {
3300 OwnerNode::Item(Item { span, .. })
3301 | OwnerNode::ForeignItem(ForeignItem { span, .. })
3302 | OwnerNode::ImplItem(ImplItem { span, .. })
3303 | OwnerNode::TraitItem(TraitItem { span, .. }) => *span,
3304 OwnerNode::Crate(Mod { spans: ModSpans { inner_span, .. }, .. }) => *inner_span,
3308 pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
3310 OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3311 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3312 | OwnerNode::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3313 OwnerNode::ForeignItem(ForeignItem {
3314 kind: ForeignItemKind::Fn(fn_decl, _, _),
3316 }) => Some(fn_decl),
3321 pub fn body_id(&self) -> Option<BodyId> {
3323 OwnerNode::TraitItem(TraitItem {
3324 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3327 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3328 | OwnerNode::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3333 pub fn generics(self) -> Option<&'hir Generics<'hir>> {
3334 Node::generics(self.into())
3337 pub fn def_id(self) -> OwnerId {
3339 OwnerNode::Item(Item { owner_id, .. })
3340 | OwnerNode::TraitItem(TraitItem { owner_id, .. })
3341 | OwnerNode::ImplItem(ImplItem { owner_id, .. })
3342 | OwnerNode::ForeignItem(ForeignItem { owner_id, .. }) => *owner_id,
3343 OwnerNode::Crate(..) => crate::CRATE_HIR_ID.owner,
3347 pub fn expect_item(self) -> &'hir Item<'hir> {
3349 OwnerNode::Item(n) => n,
3354 pub fn expect_foreign_item(self) -> &'hir ForeignItem<'hir> {
3356 OwnerNode::ForeignItem(n) => n,
3361 pub fn expect_impl_item(self) -> &'hir ImplItem<'hir> {
3363 OwnerNode::ImplItem(n) => n,
3368 pub fn expect_trait_item(self) -> &'hir TraitItem<'hir> {
3370 OwnerNode::TraitItem(n) => n,
3376 impl<'hir> Into<OwnerNode<'hir>> for &'hir Item<'hir> {
3377 fn into(self) -> OwnerNode<'hir> {
3378 OwnerNode::Item(self)
3382 impl<'hir> Into<OwnerNode<'hir>> for &'hir ForeignItem<'hir> {
3383 fn into(self) -> OwnerNode<'hir> {
3384 OwnerNode::ForeignItem(self)
3388 impl<'hir> Into<OwnerNode<'hir>> for &'hir ImplItem<'hir> {
3389 fn into(self) -> OwnerNode<'hir> {
3390 OwnerNode::ImplItem(self)
3394 impl<'hir> Into<OwnerNode<'hir>> for &'hir TraitItem<'hir> {
3395 fn into(self) -> OwnerNode<'hir> {
3396 OwnerNode::TraitItem(self)
3400 impl<'hir> Into<Node<'hir>> for OwnerNode<'hir> {
3401 fn into(self) -> Node<'hir> {
3403 OwnerNode::Item(n) => Node::Item(n),
3404 OwnerNode::ForeignItem(n) => Node::ForeignItem(n),
3405 OwnerNode::ImplItem(n) => Node::ImplItem(n),
3406 OwnerNode::TraitItem(n) => Node::TraitItem(n),
3407 OwnerNode::Crate(n) => Node::Crate(n),
3412 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3413 pub enum Node<'hir> {
3414 Param(&'hir Param<'hir>),
3415 Item(&'hir Item<'hir>),
3416 ForeignItem(&'hir ForeignItem<'hir>),
3417 TraitItem(&'hir TraitItem<'hir>),
3418 ImplItem(&'hir ImplItem<'hir>),
3419 Variant(&'hir Variant<'hir>),
3420 Field(&'hir FieldDef<'hir>),
3421 AnonConst(&'hir AnonConst),
3422 Expr(&'hir Expr<'hir>),
3423 ExprField(&'hir ExprField<'hir>),
3424 Stmt(&'hir Stmt<'hir>),
3425 PathSegment(&'hir PathSegment<'hir>),
3427 TypeBinding(&'hir TypeBinding<'hir>),
3428 TraitRef(&'hir TraitRef<'hir>),
3429 Pat(&'hir Pat<'hir>),
3430 PatField(&'hir PatField<'hir>),
3431 Arm(&'hir Arm<'hir>),
3432 Block(&'hir Block<'hir>),
3433 Local(&'hir Local<'hir>),
3435 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
3436 /// with synthesized constructors.
3437 Ctor(&'hir VariantData<'hir>),
3439 Lifetime(&'hir Lifetime),
3440 GenericParam(&'hir GenericParam<'hir>),
3442 Crate(&'hir Mod<'hir>),
3444 Infer(&'hir InferArg),
3447 impl<'hir> Node<'hir> {
3448 /// Get the identifier of this `Node`, if applicable.
3452 /// Calling `.ident()` on a [`Node::Ctor`] will return `None`
3453 /// because `Ctor`s do not have identifiers themselves.
3454 /// Instead, call `.ident()` on the parent struct/variant, like so:
3456 /// ```ignore (illustrative)
3459 /// .and_then(|ctor_id| tcx.hir().find(tcx.hir().get_parent_node(ctor_id)))
3460 /// .and_then(|parent| parent.ident())
3462 pub fn ident(&self) -> Option<Ident> {
3464 Node::TraitItem(TraitItem { ident, .. })
3465 | Node::ImplItem(ImplItem { ident, .. })
3466 | Node::ForeignItem(ForeignItem { ident, .. })
3467 | Node::Field(FieldDef { ident, .. })
3468 | Node::Variant(Variant { ident, .. })
3469 | Node::Item(Item { ident, .. })
3470 | Node::PathSegment(PathSegment { ident, .. }) => Some(*ident),
3471 Node::Lifetime(lt) => Some(lt.ident),
3472 Node::GenericParam(p) => Some(p.name.ident()),
3473 Node::TypeBinding(b) => Some(b.ident),
3475 | Node::AnonConst(..)
3481 | Node::PatField(..)
3482 | Node::ExprField(..)
3487 | Node::TraitRef(..)
3488 | Node::Infer(..) => None,
3492 pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
3494 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3495 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3496 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3497 Node::Expr(Expr { kind: ExprKind::Closure(Closure { fn_decl, .. }), .. })
3498 | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
3505 pub fn fn_sig(self) -> Option<&'hir FnSig<'hir>> {
3507 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3508 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3509 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig),
3514 pub fn body_id(&self) -> Option<BodyId> {
3516 Node::TraitItem(TraitItem {
3517 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3520 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3521 | Node::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3526 pub fn generics(self) -> Option<&'hir Generics<'hir>> {
3528 Node::ForeignItem(ForeignItem {
3529 kind: ForeignItemKind::Fn(_, _, generics), ..
3531 | Node::TraitItem(TraitItem { generics, .. })
3532 | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
3533 Node::Item(item) => item.kind.generics(),
3538 pub fn as_owner(self) -> Option<OwnerNode<'hir>> {
3540 Node::Item(i) => Some(OwnerNode::Item(i)),
3541 Node::ForeignItem(i) => Some(OwnerNode::ForeignItem(i)),
3542 Node::TraitItem(i) => Some(OwnerNode::TraitItem(i)),
3543 Node::ImplItem(i) => Some(OwnerNode::ImplItem(i)),
3544 Node::Crate(i) => Some(OwnerNode::Crate(i)),
3549 pub fn fn_kind(self) -> Option<FnKind<'hir>> {
3551 Node::Item(i) => match i.kind {
3552 ItemKind::Fn(ref sig, ref generics, _) => {
3553 Some(FnKind::ItemFn(i.ident, generics, sig.header))
3557 Node::TraitItem(ti) => match ti.kind {
3558 TraitItemKind::Fn(ref sig, TraitFn::Provided(_)) => {
3559 Some(FnKind::Method(ti.ident, sig))
3563 Node::ImplItem(ii) => match ii.kind {
3564 ImplItemKind::Fn(ref sig, _) => Some(FnKind::Method(ii.ident, sig)),
3567 Node::Expr(e) => match e.kind {
3568 ExprKind::Closure { .. } => Some(FnKind::Closure),
3575 /// Get the fields for the tuple-constructor,
3576 /// if this node is a tuple constructor, otherwise None
3577 pub fn tuple_fields(&self) -> Option<&'hir [FieldDef<'hir>]> {
3578 if let Node::Ctor(&VariantData::Tuple(fields, _, _)) = self { Some(fields) } else { None }
3582 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3583 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
3586 // tidy-alphabetical-start
3587 static_assert_size!(Block<'_>, 48);
3588 static_assert_size!(Body<'_>, 32);
3589 static_assert_size!(Expr<'_>, 64);
3590 static_assert_size!(ExprKind<'_>, 48);
3591 static_assert_size!(FnDecl<'_>, 40);
3592 static_assert_size!(ForeignItem<'_>, 72);
3593 static_assert_size!(ForeignItemKind<'_>, 40);
3594 static_assert_size!(GenericArg<'_>, 32);
3595 static_assert_size!(GenericBound<'_>, 48);
3596 static_assert_size!(Generics<'_>, 56);
3597 static_assert_size!(Impl<'_>, 80);
3598 static_assert_size!(ImplItem<'_>, 80);
3599 static_assert_size!(ImplItemKind<'_>, 32);
3600 static_assert_size!(Item<'_>, 80);
3601 static_assert_size!(ItemKind<'_>, 48);
3602 static_assert_size!(Local<'_>, 64);
3603 static_assert_size!(Param<'_>, 32);
3604 static_assert_size!(Pat<'_>, 72);
3605 static_assert_size!(Path<'_>, 40);
3606 static_assert_size!(PathSegment<'_>, 48);
3607 static_assert_size!(PatKind<'_>, 48);
3608 static_assert_size!(QPath<'_>, 24);
3609 static_assert_size!(Res, 12);
3610 static_assert_size!(Stmt<'_>, 32);
3611 static_assert_size!(StmtKind<'_>, 16);
3612 static_assert_size!(TraitItem<'_>, 80);
3613 static_assert_size!(TraitItemKind<'_>, 40);
3614 static_assert_size!(Ty<'_>, 48);
3615 static_assert_size!(TyKind<'_>, 32);
3616 // tidy-alphabetical-end