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 for param in self.params {
552 if name == param.name.ident().name {
559 pub fn spans(&self) -> MultiSpan {
560 if self.params.is_empty() {
563 self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
567 /// If there are generic parameters, return where to introduce a new one.
568 pub fn span_for_lifetime_suggestion(&self) -> Option<Span> {
569 if let Some(first) = self.params.first()
570 && self.span.contains(first.span)
572 // `fn foo<A>(t: impl Trait)`
573 // ^ suggest `'a, ` here
574 Some(first.span.shrink_to_lo())
580 /// If there are generic parameters, return where to introduce a new one.
581 pub fn span_for_param_suggestion(&self) -> Option<Span> {
582 if self.params.iter().any(|p| self.span.contains(p.span)) {
583 // `fn foo<A>(t: impl Trait)`
584 // ^ suggest `, T: Trait` here
585 let span = self.span.with_lo(self.span.hi() - BytePos(1)).shrink_to_lo();
592 /// `Span` where further predicates would be suggested, accounting for trailing commas, like
593 /// in `fn foo<T>(t: T) where T: Foo,` so we don't suggest two trailing commas.
594 pub fn tail_span_for_predicate_suggestion(&self) -> Span {
595 let end = self.where_clause_span.shrink_to_hi();
596 if self.has_where_clause_predicates {
599 .rfind(|&p| p.in_where_clause())
600 .map_or(end, |p| p.span())
608 pub fn add_where_or_trailing_comma(&self) -> &'static str {
609 if self.has_where_clause_predicates {
611 } else if self.where_clause_span.is_empty() {
614 // No where clause predicates, but we have `where` token
619 pub fn bounds_for_param(
621 param_def_id: LocalDefId,
622 ) -> impl Iterator<Item = &WhereBoundPredicate<'hir>> {
623 self.predicates.iter().filter_map(move |pred| match pred {
624 WherePredicate::BoundPredicate(bp) if bp.is_param_bound(param_def_id.to_def_id()) => {
631 pub fn outlives_for_param(
633 param_def_id: LocalDefId,
634 ) -> impl Iterator<Item = &WhereRegionPredicate<'_>> {
635 self.predicates.iter().filter_map(move |pred| match pred {
636 WherePredicate::RegionPredicate(rp) if rp.is_param_bound(param_def_id) => Some(rp),
641 pub fn bounds_span_for_suggestions(&self, param_def_id: LocalDefId) -> Option<Span> {
642 self.bounds_for_param(param_def_id).flat_map(|bp| bp.bounds.iter().rev()).find_map(
644 // We include bounds that come from a `#[derive(_)]` but point at the user's code,
645 // as we use this method to get a span appropriate for suggestions.
646 let bs = bound.span();
647 if bs.can_be_used_for_suggestions() { Some(bs.shrink_to_hi()) } else { None }
652 pub fn span_for_predicate_removal(&self, pos: usize) -> Span {
653 let predicate = &self.predicates[pos];
654 let span = predicate.span();
656 if !predicate.in_where_clause() {
662 // We need to find out which comma to remove.
663 if pos < self.predicates.len() - 1 {
664 let next_pred = &self.predicates[pos + 1];
665 if next_pred.in_where_clause() {
666 // where T: ?Sized, Foo: Bar,
668 return span.until(next_pred.span());
673 let prev_pred = &self.predicates[pos - 1];
674 if prev_pred.in_where_clause() {
675 // where Foo: Bar, T: ?Sized,
677 return prev_pred.span().shrink_to_hi().to(span);
681 // This is the only predicate in the where clause.
684 self.where_clause_span
687 pub fn span_for_bound_removal(&self, predicate_pos: usize, bound_pos: usize) -> Span {
688 let predicate = &self.predicates[predicate_pos];
689 let bounds = predicate.bounds();
691 if bounds.len() == 1 {
692 return self.span_for_predicate_removal(predicate_pos);
695 let span = bounds[bound_pos].span();
697 // where T: ?Sized + Bar, Foo: Bar,
699 span.to(bounds[1].span().shrink_to_lo())
701 // where T: Bar + ?Sized, Foo: Bar,
703 bounds[bound_pos - 1].span().shrink_to_hi().to(span)
708 /// A single predicate in a where-clause.
709 #[derive(Debug, HashStable_Generic)]
710 pub enum WherePredicate<'hir> {
711 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
712 BoundPredicate(WhereBoundPredicate<'hir>),
713 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
714 RegionPredicate(WhereRegionPredicate<'hir>),
715 /// An equality predicate (unsupported).
716 EqPredicate(WhereEqPredicate<'hir>),
719 impl<'hir> WherePredicate<'hir> {
720 pub fn span(&self) -> Span {
722 WherePredicate::BoundPredicate(p) => p.span,
723 WherePredicate::RegionPredicate(p) => p.span,
724 WherePredicate::EqPredicate(p) => p.span,
728 pub fn in_where_clause(&self) -> bool {
730 WherePredicate::BoundPredicate(p) => p.origin == PredicateOrigin::WhereClause,
731 WherePredicate::RegionPredicate(p) => p.in_where_clause,
732 WherePredicate::EqPredicate(_) => false,
736 pub fn bounds(&self) -> GenericBounds<'hir> {
738 WherePredicate::BoundPredicate(p) => p.bounds,
739 WherePredicate::RegionPredicate(p) => p.bounds,
740 WherePredicate::EqPredicate(_) => &[],
745 #[derive(Copy, Clone, Debug, HashStable_Generic, PartialEq, Eq)]
746 pub enum PredicateOrigin {
752 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
753 #[derive(Debug, HashStable_Generic)]
754 pub struct WhereBoundPredicate<'hir> {
757 /// Origin of the predicate.
758 pub origin: PredicateOrigin,
759 /// Any generics from a `for` binding.
760 pub bound_generic_params: &'hir [GenericParam<'hir>],
761 /// The type being bounded.
762 pub bounded_ty: &'hir Ty<'hir>,
763 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
764 pub bounds: GenericBounds<'hir>,
767 impl<'hir> WhereBoundPredicate<'hir> {
768 /// Returns `true` if `param_def_id` matches the `bounded_ty` of this predicate.
769 pub fn is_param_bound(&self, param_def_id: DefId) -> bool {
770 self.bounded_ty.as_generic_param().map_or(false, |(def_id, _)| def_id == param_def_id)
774 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
775 #[derive(Debug, HashStable_Generic)]
776 pub struct WhereRegionPredicate<'hir> {
778 pub in_where_clause: bool,
779 pub lifetime: &'hir Lifetime,
780 pub bounds: GenericBounds<'hir>,
783 impl<'hir> WhereRegionPredicate<'hir> {
784 /// Returns `true` if `param_def_id` matches the `lifetime` of this predicate.
785 pub fn is_param_bound(&self, param_def_id: LocalDefId) -> bool {
786 self.lifetime.res == LifetimeName::Param(param_def_id)
790 /// An equality predicate (e.g., `T = int`); currently unsupported.
791 #[derive(Debug, HashStable_Generic)]
792 pub struct WhereEqPredicate<'hir> {
794 pub lhs_ty: &'hir Ty<'hir>,
795 pub rhs_ty: &'hir Ty<'hir>,
798 /// HIR node coupled with its parent's id in the same HIR owner.
800 /// The parent is trash when the node is a HIR owner.
801 #[derive(Clone, Debug)]
802 pub struct ParentedNode<'tcx> {
803 pub parent: ItemLocalId,
804 pub node: Node<'tcx>,
807 /// Attributes owned by a HIR owner.
809 pub struct AttributeMap<'tcx> {
810 pub map: SortedMap<ItemLocalId, &'tcx [Attribute]>,
811 pub hash: Fingerprint,
814 impl<'tcx> AttributeMap<'tcx> {
815 pub const EMPTY: &'static AttributeMap<'static> =
816 &AttributeMap { map: SortedMap::new(), hash: Fingerprint::ZERO };
819 pub fn get(&self, id: ItemLocalId) -> &'tcx [Attribute] {
820 self.map.get(&id).copied().unwrap_or(&[])
824 /// Map of all HIR nodes inside the current owner.
825 /// These nodes are mapped by `ItemLocalId` alongside the index of their parent node.
826 /// The HIR tree, including bodies, is pre-hashed.
827 pub struct OwnerNodes<'tcx> {
828 /// Pre-computed hash of the full HIR.
829 pub hash_including_bodies: Fingerprint,
830 /// Pre-computed hash of the item signature, sithout recursing into the body.
831 pub hash_without_bodies: Fingerprint,
832 /// Full HIR for the current owner.
833 // The zeroth node's parent should never be accessed: the owner's parent is computed by the
834 // hir_owner_parent query. It is set to `ItemLocalId::INVALID` to force an ICE if accidentally
836 pub nodes: IndexVec<ItemLocalId, Option<ParentedNode<'tcx>>>,
837 /// Content of local bodies.
838 pub bodies: SortedMap<ItemLocalId, &'tcx Body<'tcx>>,
839 /// Non-owning definitions contained in this owner.
840 pub local_id_to_def_id: SortedMap<ItemLocalId, LocalDefId>,
843 impl<'tcx> OwnerNodes<'tcx> {
844 pub fn node(&self) -> OwnerNode<'tcx> {
845 use rustc_index::vec::Idx;
846 let node = self.nodes[ItemLocalId::new(0)].as_ref().unwrap().node;
847 let node = node.as_owner().unwrap(); // Indexing must ensure it is an OwnerNode.
852 impl fmt::Debug for OwnerNodes<'_> {
853 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
854 f.debug_struct("OwnerNodes")
855 // Do not print all the pointers to all the nodes, as it would be unreadable.
856 .field("node", &self.nodes[ItemLocalId::from_u32(0)])
862 .map(|(id, parented_node)| (id, parented_node.as_ref().map(|node| node.parent)))
863 .collect::<Vec<_>>(),
865 .field("bodies", &self.bodies)
866 .field("local_id_to_def_id", &self.local_id_to_def_id)
867 .field("hash_without_bodies", &self.hash_without_bodies)
868 .field("hash_including_bodies", &self.hash_including_bodies)
873 /// Full information resulting from lowering an AST node.
874 #[derive(Debug, HashStable_Generic)]
875 pub struct OwnerInfo<'hir> {
876 /// Contents of the HIR.
877 pub nodes: OwnerNodes<'hir>,
878 /// Map from each nested owner to its parent's local id.
879 pub parenting: FxHashMap<LocalDefId, ItemLocalId>,
880 /// Collected attributes of the HIR nodes.
881 pub attrs: AttributeMap<'hir>,
882 /// Map indicating what traits are in scope for places where this
883 /// is relevant; generated by resolve.
884 pub trait_map: FxHashMap<ItemLocalId, Box<[TraitCandidate]>>,
887 impl<'tcx> OwnerInfo<'tcx> {
889 pub fn node(&self) -> OwnerNode<'tcx> {
894 #[derive(Copy, Clone, Debug, HashStable_Generic)]
895 pub enum MaybeOwner<T> {
898 /// Used as a placeholder for unused LocalDefId.
902 impl<T> MaybeOwner<T> {
903 pub fn as_owner(self) -> Option<T> {
905 MaybeOwner::Owner(i) => Some(i),
906 MaybeOwner::NonOwner(_) | MaybeOwner::Phantom => None,
910 pub fn map<U>(self, f: impl FnOnce(T) -> U) -> MaybeOwner<U> {
912 MaybeOwner::Owner(i) => MaybeOwner::Owner(f(i)),
913 MaybeOwner::NonOwner(hir_id) => MaybeOwner::NonOwner(hir_id),
914 MaybeOwner::Phantom => MaybeOwner::Phantom,
918 pub fn unwrap(self) -> T {
920 MaybeOwner::Owner(i) => i,
921 MaybeOwner::NonOwner(_) | MaybeOwner::Phantom => panic!("Not a HIR owner"),
926 /// The top-level data structure that stores the entire contents of
927 /// the crate currently being compiled.
929 /// For more details, see the [rustc dev guide].
931 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
933 pub struct Crate<'hir> {
934 pub owners: IndexVec<LocalDefId, MaybeOwner<&'hir OwnerInfo<'hir>>>,
935 pub hir_hash: Fingerprint,
938 #[derive(Debug, HashStable_Generic)]
939 pub struct Closure<'hir> {
940 pub def_id: LocalDefId,
941 pub binder: ClosureBinder,
942 pub capture_clause: CaptureBy,
943 pub bound_generic_params: &'hir [GenericParam<'hir>],
944 pub fn_decl: &'hir FnDecl<'hir>,
946 pub fn_decl_span: Span,
947 pub movability: Option<Movability>,
950 /// A block of statements `{ .. }`, which may have a label (in this case the
951 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
952 /// the `rules` being anything but `DefaultBlock`.
953 #[derive(Debug, HashStable_Generic)]
954 pub struct Block<'hir> {
955 /// Statements in a block.
956 pub stmts: &'hir [Stmt<'hir>],
957 /// An expression at the end of the block
958 /// without a semicolon, if any.
959 pub expr: Option<&'hir Expr<'hir>>,
960 #[stable_hasher(ignore)]
962 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
963 pub rules: BlockCheckMode,
965 /// If true, then there may exist `break 'a` values that aim to
966 /// break out of this block early.
967 /// Used by `'label: {}` blocks and by `try {}` blocks.
968 pub targeted_by_break: bool,
971 impl<'hir> Block<'hir> {
972 pub fn innermost_block(&self) -> &Block<'hir> {
973 let mut block = self;
974 while let Some(Expr { kind: ExprKind::Block(inner_block, _), .. }) = block.expr {
981 #[derive(Debug, HashStable_Generic)]
982 pub struct Pat<'hir> {
983 #[stable_hasher(ignore)]
985 pub kind: PatKind<'hir>,
987 /// Whether to use default binding modes.
988 /// At present, this is false only for destructuring assignment.
989 pub default_binding_modes: bool,
992 impl<'hir> Pat<'hir> {
993 // FIXME(#19596) this is a workaround, but there should be a better way
994 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) -> bool {
1001 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
1002 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
1003 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
1004 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
1005 Slice(before, slice, after) => {
1006 before.iter().chain(slice).chain(after.iter()).all(|p| p.walk_short_(it))
1011 /// Walk the pattern in left-to-right order,
1012 /// short circuiting (with `.all(..)`) if `false` is returned.
1014 /// Note that when visiting e.g. `Tuple(ps)`,
1015 /// if visiting `ps[0]` returns `false`,
1016 /// then `ps[1]` will not be visited.
1017 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) -> bool {
1018 self.walk_short_(&mut it)
1021 // FIXME(#19596) this is a workaround, but there should be a better way
1022 fn walk_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) {
1029 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
1030 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
1031 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
1032 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
1033 Slice(before, slice, after) => {
1034 before.iter().chain(slice).chain(after.iter()).for_each(|p| p.walk_(it))
1039 /// Walk the pattern in left-to-right order.
1041 /// If `it(pat)` returns `false`, the children are not visited.
1042 pub fn walk(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) {
1046 /// Walk the pattern in left-to-right order.
1048 /// If you always want to recurse, prefer this method over `walk`.
1049 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
1057 /// A single field in a struct pattern.
1059 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
1060 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
1061 /// except `is_shorthand` is true.
1062 #[derive(Debug, HashStable_Generic)]
1063 pub struct PatField<'hir> {
1064 #[stable_hasher(ignore)]
1066 /// The identifier for the field.
1068 /// The pattern the field is destructured to.
1069 pub pat: &'hir Pat<'hir>,
1070 pub is_shorthand: bool,
1074 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1080 impl fmt::Display for RangeEnd {
1081 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1082 f.write_str(match self {
1083 RangeEnd::Included => "..=",
1084 RangeEnd::Excluded => "..",
1089 // Equivalent to `Option<usize>`. That type takes up 16 bytes on 64-bit, but
1090 // this type only takes up 4 bytes, at the cost of being restricted to a
1091 // maximum value of `u32::MAX - 1`. In practice, this is more than enough.
1092 #[derive(Clone, Copy, PartialEq, Eq, Hash, HashStable_Generic)]
1093 pub struct DotDotPos(u32);
1096 /// Panics if n >= u32::MAX.
1097 pub fn new(n: Option<usize>) -> Self {
1100 assert!(n < u32::MAX as usize);
1103 None => Self(u32::MAX),
1107 pub fn as_opt_usize(&self) -> Option<usize> {
1108 if self.0 == u32::MAX { None } else { Some(self.0 as usize) }
1112 impl fmt::Debug for DotDotPos {
1113 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1114 self.as_opt_usize().fmt(f)
1118 #[derive(Debug, HashStable_Generic)]
1119 pub enum PatKind<'hir> {
1120 /// Represents a wildcard pattern (i.e., `_`).
1123 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
1124 /// The `HirId` is the canonical ID for the variable being bound,
1125 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
1126 /// which is the pattern ID of the first `x`.
1127 Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
1129 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
1130 /// The `bool` is `true` in the presence of a `..`.
1131 Struct(QPath<'hir>, &'hir [PatField<'hir>], bool),
1133 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
1134 /// If the `..` pattern fragment is present, then `DotDotPos` denotes its position.
1135 /// `0 <= position <= subpats.len()`
1136 TupleStruct(QPath<'hir>, &'hir [Pat<'hir>], DotDotPos),
1138 /// An or-pattern `A | B | C`.
1139 /// Invariant: `pats.len() >= 2`.
1140 Or(&'hir [Pat<'hir>]),
1142 /// A path pattern for a unit struct/variant or a (maybe-associated) constant.
1145 /// A tuple pattern (e.g., `(a, b)`).
1146 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
1147 /// `0 <= position <= subpats.len()`
1148 Tuple(&'hir [Pat<'hir>], DotDotPos),
1150 /// A `box` pattern.
1151 Box(&'hir Pat<'hir>),
1153 /// A reference pattern (e.g., `&mut (a, b)`).
1154 Ref(&'hir Pat<'hir>, Mutability),
1157 Lit(&'hir Expr<'hir>),
1159 /// A range pattern (e.g., `1..=2` or `1..2`).
1160 Range(Option<&'hir Expr<'hir>>, Option<&'hir Expr<'hir>>, RangeEnd),
1162 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
1164 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
1165 /// If `slice` exists, then `after` can be non-empty.
1167 /// The representation for e.g., `[a, b, .., c, d]` is:
1168 /// ```ignore (illustrative)
1169 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
1171 Slice(&'hir [Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [Pat<'hir>]),
1174 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1175 pub enum BinOpKind {
1176 /// The `+` operator (addition).
1178 /// The `-` operator (subtraction).
1180 /// The `*` operator (multiplication).
1182 /// The `/` operator (division).
1184 /// The `%` operator (modulus).
1186 /// The `&&` operator (logical and).
1188 /// The `||` operator (logical or).
1190 /// The `^` operator (bitwise xor).
1192 /// The `&` operator (bitwise and).
1194 /// The `|` operator (bitwise or).
1196 /// The `<<` operator (shift left).
1198 /// The `>>` operator (shift right).
1200 /// The `==` operator (equality).
1202 /// The `<` operator (less than).
1204 /// The `<=` operator (less than or equal to).
1206 /// The `!=` operator (not equal to).
1208 /// The `>=` operator (greater than or equal to).
1210 /// The `>` operator (greater than).
1215 pub fn as_str(self) -> &'static str {
1217 BinOpKind::Add => "+",
1218 BinOpKind::Sub => "-",
1219 BinOpKind::Mul => "*",
1220 BinOpKind::Div => "/",
1221 BinOpKind::Rem => "%",
1222 BinOpKind::And => "&&",
1223 BinOpKind::Or => "||",
1224 BinOpKind::BitXor => "^",
1225 BinOpKind::BitAnd => "&",
1226 BinOpKind::BitOr => "|",
1227 BinOpKind::Shl => "<<",
1228 BinOpKind::Shr => ">>",
1229 BinOpKind::Eq => "==",
1230 BinOpKind::Lt => "<",
1231 BinOpKind::Le => "<=",
1232 BinOpKind::Ne => "!=",
1233 BinOpKind::Ge => ">=",
1234 BinOpKind::Gt => ">",
1238 pub fn is_lazy(self) -> bool {
1239 matches!(self, BinOpKind::And | BinOpKind::Or)
1242 pub fn is_shift(self) -> bool {
1243 matches!(self, BinOpKind::Shl | BinOpKind::Shr)
1246 pub fn is_comparison(self) -> bool {
1253 | BinOpKind::Ge => true,
1265 | BinOpKind::Shr => false,
1269 /// Returns `true` if the binary operator takes its arguments by value.
1270 pub fn is_by_value(self) -> bool {
1271 !self.is_comparison()
1275 impl Into<ast::BinOpKind> for BinOpKind {
1276 fn into(self) -> ast::BinOpKind {
1278 BinOpKind::Add => ast::BinOpKind::Add,
1279 BinOpKind::Sub => ast::BinOpKind::Sub,
1280 BinOpKind::Mul => ast::BinOpKind::Mul,
1281 BinOpKind::Div => ast::BinOpKind::Div,
1282 BinOpKind::Rem => ast::BinOpKind::Rem,
1283 BinOpKind::And => ast::BinOpKind::And,
1284 BinOpKind::Or => ast::BinOpKind::Or,
1285 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1286 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1287 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1288 BinOpKind::Shl => ast::BinOpKind::Shl,
1289 BinOpKind::Shr => ast::BinOpKind::Shr,
1290 BinOpKind::Eq => ast::BinOpKind::Eq,
1291 BinOpKind::Lt => ast::BinOpKind::Lt,
1292 BinOpKind::Le => ast::BinOpKind::Le,
1293 BinOpKind::Ne => ast::BinOpKind::Ne,
1294 BinOpKind::Ge => ast::BinOpKind::Ge,
1295 BinOpKind::Gt => ast::BinOpKind::Gt,
1300 pub type BinOp = Spanned<BinOpKind>;
1302 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1304 /// The `*` operator (dereferencing).
1306 /// The `!` operator (logical negation).
1308 /// The `-` operator (negation).
1313 pub fn as_str(self) -> &'static str {
1321 /// Returns `true` if the unary operator takes its argument by value.
1322 pub fn is_by_value(self) -> bool {
1323 matches!(self, Self::Neg | Self::Not)
1328 #[derive(Debug, HashStable_Generic)]
1329 pub struct Stmt<'hir> {
1331 pub kind: StmtKind<'hir>,
1335 /// The contents of a statement.
1336 #[derive(Debug, HashStable_Generic)]
1337 pub enum StmtKind<'hir> {
1338 /// A local (`let`) binding.
1339 Local(&'hir Local<'hir>),
1341 /// An item binding.
1344 /// An expression without a trailing semi-colon (must have unit type).
1345 Expr(&'hir Expr<'hir>),
1347 /// An expression with a trailing semi-colon (may have any type).
1348 Semi(&'hir Expr<'hir>),
1351 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <init>;`).
1352 #[derive(Debug, HashStable_Generic)]
1353 pub struct Local<'hir> {
1354 pub pat: &'hir Pat<'hir>,
1355 /// Type annotation, if any (otherwise the type will be inferred).
1356 pub ty: Option<&'hir Ty<'hir>>,
1357 /// Initializer expression to set the value, if any.
1358 pub init: Option<&'hir Expr<'hir>>,
1359 /// Else block for a `let...else` binding.
1360 pub els: Option<&'hir Block<'hir>>,
1363 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1364 /// desugaring. Otherwise will be `Normal`.
1365 pub source: LocalSource,
1368 /// Represents a single arm of a `match` expression, e.g.
1369 /// `<pat> (if <guard>) => <body>`.
1370 #[derive(Debug, HashStable_Generic)]
1371 pub struct Arm<'hir> {
1372 #[stable_hasher(ignore)]
1375 /// If this pattern and the optional guard matches, then `body` is evaluated.
1376 pub pat: &'hir Pat<'hir>,
1377 /// Optional guard clause.
1378 pub guard: Option<Guard<'hir>>,
1379 /// The expression the arm evaluates to if this arm matches.
1380 pub body: &'hir Expr<'hir>,
1383 /// Represents a `let <pat>[: <ty>] = <expr>` expression (not a Local), occurring in an `if-let` or
1384 /// `let-else`, evaluating to a boolean. Typically the pattern is refutable.
1386 /// In an if-let, imagine it as `if (let <pat> = <expr>) { ... }`; in a let-else, it is part of the
1387 /// desugaring to if-let. Only let-else supports the type annotation at present.
1388 #[derive(Debug, HashStable_Generic)]
1389 pub struct Let<'hir> {
1392 pub pat: &'hir Pat<'hir>,
1393 pub ty: Option<&'hir Ty<'hir>>,
1394 pub init: &'hir Expr<'hir>,
1397 #[derive(Debug, HashStable_Generic)]
1398 pub enum Guard<'hir> {
1399 If(&'hir Expr<'hir>),
1400 IfLet(&'hir Let<'hir>),
1403 impl<'hir> Guard<'hir> {
1404 /// Returns the body of the guard
1406 /// In other words, returns the e in either of the following:
1409 /// - `if let x = e`
1410 pub fn body(&self) -> &'hir Expr<'hir> {
1412 Guard::If(e) | Guard::IfLet(Let { init: e, .. }) => e,
1417 #[derive(Debug, HashStable_Generic)]
1418 pub struct ExprField<'hir> {
1419 #[stable_hasher(ignore)]
1422 pub expr: &'hir Expr<'hir>,
1424 pub is_shorthand: bool,
1427 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1428 pub enum BlockCheckMode {
1430 UnsafeBlock(UnsafeSource),
1433 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1434 pub enum UnsafeSource {
1439 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
1444 /// The body of a function, closure, or constant value. In the case of
1445 /// a function, the body contains not only the function body itself
1446 /// (which is an expression), but also the argument patterns, since
1447 /// those are something that the caller doesn't really care about.
1452 /// fn foo((x, y): (u32, u32)) -> u32 {
1457 /// Here, the `Body` associated with `foo()` would contain:
1459 /// - an `params` array containing the `(x, y)` pattern
1460 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1461 /// - `generator_kind` would be `None`
1463 /// All bodies have an **owner**, which can be accessed via the HIR
1464 /// map using `body_owner_def_id()`.
1465 #[derive(Debug, HashStable_Generic)]
1466 pub struct Body<'hir> {
1467 pub params: &'hir [Param<'hir>],
1468 pub value: &'hir Expr<'hir>,
1469 pub generator_kind: Option<GeneratorKind>,
1472 impl<'hir> Body<'hir> {
1473 pub fn id(&self) -> BodyId {
1474 BodyId { hir_id: self.value.hir_id }
1477 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1482 /// The type of source expression that caused this generator to be created.
1483 #[derive(Clone, PartialEq, PartialOrd, Eq, Hash, Debug, Copy)]
1484 #[derive(HashStable_Generic, Encodable, Decodable)]
1485 pub enum GeneratorKind {
1486 /// An explicit `async` block or the body of an async function.
1487 Async(AsyncGeneratorKind),
1489 /// A generator literal created via a `yield` inside a closure.
1493 impl fmt::Display for GeneratorKind {
1494 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1496 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1497 GeneratorKind::Gen => f.write_str("generator"),
1502 impl GeneratorKind {
1503 pub fn descr(&self) -> &'static str {
1505 GeneratorKind::Async(ask) => ask.descr(),
1506 GeneratorKind::Gen => "generator",
1511 /// In the case of a generator created as part of an async construct,
1512 /// which kind of async construct caused it to be created?
1514 /// This helps error messages but is also used to drive coercions in
1515 /// type-checking (see #60424).
1516 #[derive(Clone, PartialEq, PartialOrd, Eq, Hash, Debug, Copy)]
1517 #[derive(HashStable_Generic, Encodable, Decodable)]
1518 pub enum AsyncGeneratorKind {
1519 /// An explicit `async` block written by the user.
1522 /// An explicit `async` closure written by the user.
1525 /// The `async` block generated as the body of an async function.
1529 impl fmt::Display for AsyncGeneratorKind {
1530 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1531 f.write_str(match self {
1532 AsyncGeneratorKind::Block => "async block",
1533 AsyncGeneratorKind::Closure => "async closure body",
1534 AsyncGeneratorKind::Fn => "async fn body",
1539 impl AsyncGeneratorKind {
1540 pub fn descr(&self) -> &'static str {
1542 AsyncGeneratorKind::Block => "`async` block",
1543 AsyncGeneratorKind::Closure => "`async` closure body",
1544 AsyncGeneratorKind::Fn => "`async fn` body",
1549 #[derive(Copy, Clone, Debug)]
1550 pub enum BodyOwnerKind {
1551 /// Functions and methods.
1557 /// Constants and associated constants.
1560 /// Initializer of a `static` item.
1564 impl BodyOwnerKind {
1565 pub fn is_fn_or_closure(self) -> bool {
1567 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1568 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1573 /// The kind of an item that requires const-checking.
1574 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1575 pub enum ConstContext {
1579 /// A `static` or `static mut`.
1582 /// A `const`, associated `const`, or other const context.
1584 /// Other contexts include:
1585 /// - Array length expressions
1586 /// - Enum discriminants
1587 /// - Const generics
1589 /// For the most part, other contexts are treated just like a regular `const`, so they are
1590 /// lumped into the same category.
1595 /// A description of this const context that can appear between backticks in an error message.
1597 /// E.g. `const` or `static mut`.
1598 pub fn keyword_name(self) -> &'static str {
1600 Self::Const => "const",
1601 Self::Static(Mutability::Not) => "static",
1602 Self::Static(Mutability::Mut) => "static mut",
1603 Self::ConstFn => "const fn",
1608 /// A colloquial, trivially pluralizable description of this const context for use in error
1610 impl fmt::Display for ConstContext {
1611 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1613 Self::Const => write!(f, "constant"),
1614 Self::Static(_) => write!(f, "static"),
1615 Self::ConstFn => write!(f, "constant function"),
1620 // NOTE: `IntoDiagnosticArg` impl for `ConstContext` lives in `rustc_errors`
1621 // due to a cyclical dependency between hir that crate.
1624 pub type Lit = Spanned<LitKind>;
1626 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1633 pub fn hir_id(&self) -> HirId {
1635 &ArrayLen::Infer(hir_id, _) | &ArrayLen::Body(AnonConst { hir_id, .. }) => hir_id,
1640 /// A constant (expression) that's not an item or associated item,
1641 /// but needs its own `DefId` for type-checking, const-eval, etc.
1642 /// These are usually found nested inside types (e.g., array lengths)
1643 /// or expressions (e.g., repeat counts), and also used to define
1644 /// explicit discriminant values for enum variants.
1646 /// You can check if this anon const is a default in a const param
1647 /// `const N: usize = { ... }` with `tcx.hir().opt_const_param_default_param_def_id(..)`
1648 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1649 pub struct AnonConst {
1651 pub def_id: LocalDefId,
1656 #[derive(Debug, HashStable_Generic)]
1657 pub struct Expr<'hir> {
1659 pub kind: ExprKind<'hir>,
1664 pub fn precedence(&self) -> ExprPrecedence {
1666 ExprKind::Box(_) => ExprPrecedence::Box,
1667 ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1668 ExprKind::Array(_) => ExprPrecedence::Array,
1669 ExprKind::Call(..) => ExprPrecedence::Call,
1670 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1671 ExprKind::Tup(_) => ExprPrecedence::Tup,
1672 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1673 ExprKind::Unary(..) => ExprPrecedence::Unary,
1674 ExprKind::Lit(_) => ExprPrecedence::Lit,
1675 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1676 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1677 ExprKind::If(..) => ExprPrecedence::If,
1678 ExprKind::Let(..) => ExprPrecedence::Let,
1679 ExprKind::Loop(..) => ExprPrecedence::Loop,
1680 ExprKind::Match(..) => ExprPrecedence::Match,
1681 ExprKind::Closure { .. } => ExprPrecedence::Closure,
1682 ExprKind::Block(..) => ExprPrecedence::Block,
1683 ExprKind::Assign(..) => ExprPrecedence::Assign,
1684 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1685 ExprKind::Field(..) => ExprPrecedence::Field,
1686 ExprKind::Index(..) => ExprPrecedence::Index,
1687 ExprKind::Path(..) => ExprPrecedence::Path,
1688 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1689 ExprKind::Break(..) => ExprPrecedence::Break,
1690 ExprKind::Continue(..) => ExprPrecedence::Continue,
1691 ExprKind::Ret(..) => ExprPrecedence::Ret,
1692 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1693 ExprKind::Struct(..) => ExprPrecedence::Struct,
1694 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1695 ExprKind::Yield(..) => ExprPrecedence::Yield,
1696 ExprKind::Err => ExprPrecedence::Err,
1700 /// Whether this looks like a place expr, without checking for deref
1702 /// This will return `true` in some potentially surprising cases such as
1703 /// `CONSTANT.field`.
1704 pub fn is_syntactic_place_expr(&self) -> bool {
1705 self.is_place_expr(|_| true)
1708 /// Whether this is a place expression.
1710 /// `allow_projections_from` should return `true` if indexing a field or index expression based
1711 /// on the given expression should be considered a place expression.
1712 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1714 ExprKind::Path(QPath::Resolved(_, ref path)) => {
1715 matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static(_), _) | Res::Err)
1718 // Type ascription inherits its place expression kind from its
1720 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1721 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1723 ExprKind::Unary(UnOp::Deref, _) => true,
1725 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1726 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1729 // Lang item paths cannot currently be local variables or statics.
1730 ExprKind::Path(QPath::LangItem(..)) => false,
1732 // Partially qualified paths in expressions can only legally
1733 // refer to associated items which are always rvalues.
1734 ExprKind::Path(QPath::TypeRelative(..))
1735 | ExprKind::Call(..)
1736 | ExprKind::MethodCall(..)
1737 | ExprKind::Struct(..)
1740 | ExprKind::Match(..)
1741 | ExprKind::Closure { .. }
1742 | ExprKind::Block(..)
1743 | ExprKind::Repeat(..)
1744 | ExprKind::Array(..)
1745 | ExprKind::Break(..)
1746 | ExprKind::Continue(..)
1749 | ExprKind::Loop(..)
1750 | ExprKind::Assign(..)
1751 | ExprKind::InlineAsm(..)
1752 | ExprKind::AssignOp(..)
1754 | ExprKind::ConstBlock(..)
1755 | ExprKind::Unary(..)
1757 | ExprKind::AddrOf(..)
1758 | ExprKind::Binary(..)
1759 | ExprKind::Yield(..)
1760 | ExprKind::Cast(..)
1761 | ExprKind::DropTemps(..)
1762 | ExprKind::Err => false,
1766 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1767 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1768 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1769 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1770 /// beyond remembering to call this function before doing analysis on it.
1771 pub fn peel_drop_temps(&self) -> &Self {
1772 let mut expr = self;
1773 while let ExprKind::DropTemps(inner) = &expr.kind {
1779 pub fn peel_blocks(&self) -> &Self {
1780 let mut expr = self;
1781 while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind {
1787 pub fn can_have_side_effects(&self) -> bool {
1788 match self.peel_drop_temps().kind {
1789 ExprKind::Path(_) | ExprKind::Lit(_) => false,
1790 ExprKind::Type(base, _)
1791 | ExprKind::Unary(_, base)
1792 | ExprKind::Field(base, _)
1793 | ExprKind::Index(base, _)
1794 | ExprKind::AddrOf(.., base)
1795 | ExprKind::Cast(base, _) => {
1796 // This isn't exactly true for `Index` and all `Unary`, but we are using this
1797 // method exclusively for diagnostics and there's a *cultural* pressure against
1798 // them being used only for its side-effects.
1799 base.can_have_side_effects()
1801 ExprKind::Struct(_, fields, init) => fields
1803 .map(|field| field.expr)
1804 .chain(init.into_iter())
1805 .all(|e| e.can_have_side_effects()),
1807 ExprKind::Array(args)
1808 | ExprKind::Tup(args)
1812 ExprKind::Path(QPath::Resolved(
1814 Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. },
1819 ) => args.iter().all(|arg| arg.can_have_side_effects()),
1821 | ExprKind::Match(..)
1822 | ExprKind::MethodCall(..)
1823 | ExprKind::Call(..)
1824 | ExprKind::Closure { .. }
1825 | ExprKind::Block(..)
1826 | ExprKind::Repeat(..)
1827 | ExprKind::Break(..)
1828 | ExprKind::Continue(..)
1831 | ExprKind::Loop(..)
1832 | ExprKind::Assign(..)
1833 | ExprKind::InlineAsm(..)
1834 | ExprKind::AssignOp(..)
1835 | ExprKind::ConstBlock(..)
1837 | ExprKind::Binary(..)
1838 | ExprKind::Yield(..)
1839 | ExprKind::DropTemps(..)
1840 | ExprKind::Err => true,
1844 /// To a first-order approximation, is this a pattern?
1845 pub fn is_approximately_pattern(&self) -> bool {
1848 | ExprKind::Array(_)
1849 | ExprKind::Call(..)
1853 | ExprKind::Struct(..) => true,
1858 pub fn method_ident(&self) -> Option<Ident> {
1860 ExprKind::MethodCall(receiver_method, ..) => Some(receiver_method.ident),
1861 ExprKind::Unary(_, expr) | ExprKind::AddrOf(.., expr) => expr.method_ident(),
1867 /// Checks if the specified expression is a built-in range literal.
1868 /// (See: `LoweringContext::lower_expr()`).
1869 pub fn is_range_literal(expr: &Expr<'_>) -> bool {
1871 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1872 ExprKind::Struct(ref qpath, _, _) => matches!(
1877 | LangItem::RangeFrom
1878 | LangItem::RangeFull
1879 | LangItem::RangeToInclusive,
1884 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1885 ExprKind::Call(ref func, _) => {
1886 matches!(func.kind, ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, ..)))
1893 #[derive(Debug, HashStable_Generic)]
1894 pub enum ExprKind<'hir> {
1895 /// A `box x` expression.
1896 Box(&'hir Expr<'hir>),
1897 /// Allow anonymous constants from an inline `const` block
1898 ConstBlock(AnonConst),
1899 /// An array (e.g., `[a, b, c, d]`).
1900 Array(&'hir [Expr<'hir>]),
1901 /// A function call.
1903 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1904 /// and the second field is the list of arguments.
1905 /// This also represents calling the constructor of
1906 /// tuple-like ADTs such as tuple structs and enum variants.
1907 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1908 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1910 /// The `PathSegment` represents the method name and its generic arguments
1911 /// (within the angle brackets).
1912 /// The `&Expr` is the expression that evaluates
1913 /// to the object on which the method is being called on (the receiver),
1914 /// and the `&[Expr]` is the rest of the arguments.
1915 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1916 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, x, [a, b, c, d], span)`.
1917 /// The final `Span` represents the span of the function and arguments
1918 /// (e.g. `foo::<Bar, Baz>(a, b, c, d)` in `x.foo::<Bar, Baz>(a, b, c, d)`
1920 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1921 /// the `hir_id` of the `MethodCall` node itself.
1923 /// [`type_dependent_def_id`]: ../../rustc_middle/ty/struct.TypeckResults.html#method.type_dependent_def_id
1924 MethodCall(&'hir PathSegment<'hir>, &'hir Expr<'hir>, &'hir [Expr<'hir>], Span),
1925 /// A tuple (e.g., `(a, b, c, d)`).
1926 Tup(&'hir [Expr<'hir>]),
1927 /// A binary operation (e.g., `a + b`, `a * b`).
1928 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1929 /// A unary operation (e.g., `!x`, `*x`).
1930 Unary(UnOp, &'hir Expr<'hir>),
1931 /// A literal (e.g., `1`, `"foo"`).
1933 /// A cast (e.g., `foo as f64`).
1934 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1935 /// A type reference (e.g., `Foo`).
1936 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1937 /// Wraps the expression in a terminating scope.
1938 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1940 /// This construct only exists to tweak the drop order in HIR lowering.
1941 /// An example of that is the desugaring of `for` loops.
1942 DropTemps(&'hir Expr<'hir>),
1943 /// A `let $pat = $expr` expression.
1945 /// These are not `Local` and only occur as expressions.
1946 /// The `let Some(x) = foo()` in `if let Some(x) = foo()` is an example of `Let(..)`.
1947 Let(&'hir Let<'hir>),
1948 /// An `if` block, with an optional else block.
1950 /// I.e., `if <expr> { <expr> } else { <expr> }`.
1951 If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
1952 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1954 /// I.e., `'label: loop { <block> }`.
1956 /// The `Span` is the loop header (`for x in y`/`while let pat = expr`).
1957 Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span),
1958 /// A `match` block, with a source that indicates whether or not it is
1959 /// the result of a desugaring, and if so, which kind.
1960 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1961 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1963 /// The `Span` is the argument block `|...|`.
1965 /// This may also be a generator literal or an `async block` as indicated by the
1966 /// `Option<Movability>`.
1967 Closure(&'hir Closure<'hir>),
1968 /// A block (e.g., `'label: { ... }`).
1969 Block(&'hir Block<'hir>, Option<Label>),
1971 /// An assignment (e.g., `a = foo()`).
1972 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1973 /// An assignment with an operator.
1976 AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1977 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1978 Field(&'hir Expr<'hir>, Ident),
1979 /// An indexing operation (`foo[2]`).
1980 Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1982 /// Path to a definition, possibly containing lifetime or type parameters.
1985 /// A referencing operation (i.e., `&a` or `&mut a`).
1986 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1987 /// A `break`, with an optional label to break.
1988 Break(Destination, Option<&'hir Expr<'hir>>),
1989 /// A `continue`, with an optional label.
1990 Continue(Destination),
1991 /// A `return`, with an optional value to be returned.
1992 Ret(Option<&'hir Expr<'hir>>),
1994 /// Inline assembly (from `asm!`), with its outputs and inputs.
1995 InlineAsm(&'hir InlineAsm<'hir>),
1997 /// A struct or struct-like variant literal expression.
1999 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
2000 /// where `base` is the `Option<Expr>`.
2001 Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], Option<&'hir Expr<'hir>>),
2003 /// An array literal constructed from one repeated element.
2005 /// E.g., `[1; 5]`. The first expression is the element
2006 /// to be repeated; the second is the number of times to repeat it.
2007 Repeat(&'hir Expr<'hir>, ArrayLen),
2009 /// A suspension point for generators (i.e., `yield <expr>`).
2010 Yield(&'hir Expr<'hir>, YieldSource),
2012 /// A placeholder for an expression that wasn't syntactically well formed in some way.
2016 /// Represents an optionally `Self`-qualified value/type path or associated extension.
2018 /// To resolve the path to a `DefId`, call [`qpath_res`].
2020 /// [`qpath_res`]: ../../rustc_middle/ty/struct.TypeckResults.html#method.qpath_res
2021 #[derive(Debug, HashStable_Generic)]
2022 pub enum QPath<'hir> {
2023 /// Path to a definition, optionally "fully-qualified" with a `Self`
2024 /// type, if the path points to an associated item in a trait.
2026 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
2027 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
2028 /// even though they both have the same two-segment `Clone::clone` `Path`.
2029 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
2031 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
2032 /// Will be resolved by type-checking to an associated item.
2034 /// UFCS source paths can desugar into this, with `Vec::new` turning into
2035 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
2036 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
2037 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
2039 /// Reference to a `#[lang = "foo"]` item. `HirId` of the inner expr.
2040 LangItem(LangItem, Span, Option<HirId>),
2043 impl<'hir> QPath<'hir> {
2044 /// Returns the span of this `QPath`.
2045 pub fn span(&self) -> Span {
2047 QPath::Resolved(_, path) => path.span,
2048 QPath::TypeRelative(qself, ps) => qself.span.to(ps.ident.span),
2049 QPath::LangItem(_, span, _) => span,
2053 /// Returns the span of the qself of this `QPath`. For example, `()` in
2054 /// `<() as Trait>::method`.
2055 pub fn qself_span(&self) -> Span {
2057 QPath::Resolved(_, path) => path.span,
2058 QPath::TypeRelative(qself, _) => qself.span,
2059 QPath::LangItem(_, span, _) => span,
2063 /// Returns the span of the last segment of this `QPath`. For example, `method` in
2064 /// `<() as Trait>::method`.
2065 pub fn last_segment_span(&self) -> Span {
2067 QPath::Resolved(_, path) => path.segments.last().unwrap().ident.span,
2068 QPath::TypeRelative(_, segment) => segment.ident.span,
2069 QPath::LangItem(_, span, _) => span,
2074 /// Hints at the original code for a let statement.
2075 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2076 pub enum LocalSource {
2077 /// A `match _ { .. }`.
2079 /// When lowering async functions, we create locals within the `async move` so that
2080 /// all parameters are dropped after the future is polled.
2082 /// ```ignore (pseudo-Rust)
2083 /// async fn foo(<pattern> @ x: Type) {
2085 /// let <pattern> = x;
2090 /// A desugared `<expr>.await`.
2092 /// A desugared `expr = expr`, where the LHS is a tuple, struct or array.
2093 /// The span is that of the `=` sign.
2094 AssignDesugar(Span),
2097 /// Hints at the original code for a `match _ { .. }`.
2098 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
2099 #[derive(HashStable_Generic)]
2100 pub enum MatchSource {
2101 /// A `match _ { .. }`.
2103 /// A desugared `for _ in _ { .. }` loop.
2105 /// A desugared `?` operator.
2107 /// A desugared `<expr>.await`.
2113 pub const fn name(self) -> &'static str {
2117 ForLoopDesugar => "for",
2119 AwaitDesugar => ".await",
2124 /// The loop type that yielded an `ExprKind::Loop`.
2125 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2126 pub enum LoopSource {
2127 /// A `loop { .. }` loop.
2129 /// A `while _ { .. }` loop.
2131 /// A `for _ in _ { .. }` loop.
2136 pub fn name(self) -> &'static str {
2138 LoopSource::Loop => "loop",
2139 LoopSource::While => "while",
2140 LoopSource::ForLoop => "for",
2145 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2146 pub enum LoopIdError {
2148 UnlabeledCfInWhileCondition,
2152 impl fmt::Display for LoopIdError {
2153 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2154 f.write_str(match self {
2155 LoopIdError::OutsideLoopScope => "not inside loop scope",
2156 LoopIdError::UnlabeledCfInWhileCondition => {
2157 "unlabeled control flow (break or continue) in while condition"
2159 LoopIdError::UnresolvedLabel => "label not found",
2164 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2165 pub struct Destination {
2166 /// This is `Some(_)` iff there is an explicit user-specified 'label
2167 pub label: Option<Label>,
2169 /// These errors are caught and then reported during the diagnostics pass in
2170 /// `librustc_passes/loops.rs`
2171 pub target_id: Result<HirId, LoopIdError>,
2174 /// The yield kind that caused an `ExprKind::Yield`.
2175 #[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
2176 pub enum YieldSource {
2177 /// An `<expr>.await`.
2178 Await { expr: Option<HirId> },
2179 /// A plain `yield`.
2184 pub fn is_await(&self) -> bool {
2185 matches!(self, YieldSource::Await { .. })
2189 impl fmt::Display for YieldSource {
2190 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2191 f.write_str(match self {
2192 YieldSource::Await { .. } => "`await`",
2193 YieldSource::Yield => "`yield`",
2198 impl From<GeneratorKind> for YieldSource {
2199 fn from(kind: GeneratorKind) -> Self {
2201 // Guess based on the kind of the current generator.
2202 GeneratorKind::Gen => Self::Yield,
2203 GeneratorKind::Async(_) => Self::Await { expr: None },
2208 // N.B., if you change this, you'll probably want to change the corresponding
2209 // type structure in middle/ty.rs as well.
2210 #[derive(Debug, HashStable_Generic)]
2211 pub struct MutTy<'hir> {
2212 pub ty: &'hir Ty<'hir>,
2213 pub mutbl: Mutability,
2216 /// Represents a function's signature in a trait declaration,
2217 /// trait implementation, or a free function.
2218 #[derive(Debug, HashStable_Generic)]
2219 pub struct FnSig<'hir> {
2220 pub header: FnHeader,
2221 pub decl: &'hir FnDecl<'hir>,
2225 // The bodies for items are stored "out of line", in a separate
2226 // hashmap in the `Crate`. Here we just record the hir-id of the item
2227 // so it can fetched later.
2228 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2229 pub struct TraitItemId {
2230 pub owner_id: OwnerId,
2235 pub fn hir_id(&self) -> HirId {
2236 // Items are always HIR owners.
2237 HirId::make_owner(self.owner_id.def_id)
2241 /// Represents an item declaration within a trait declaration,
2242 /// possibly including a default implementation. A trait item is
2243 /// either required (meaning it doesn't have an implementation, just a
2244 /// signature) or provided (meaning it has a default implementation).
2245 #[derive(Debug, HashStable_Generic)]
2246 pub struct TraitItem<'hir> {
2248 pub owner_id: OwnerId,
2249 pub generics: &'hir Generics<'hir>,
2250 pub kind: TraitItemKind<'hir>,
2252 pub defaultness: Defaultness,
2255 impl TraitItem<'_> {
2257 pub fn hir_id(&self) -> HirId {
2258 // Items are always HIR owners.
2259 HirId::make_owner(self.owner_id.def_id)
2262 pub fn trait_item_id(&self) -> TraitItemId {
2263 TraitItemId { owner_id: self.owner_id }
2267 /// Represents a trait method's body (or just argument names).
2268 #[derive(Encodable, Debug, HashStable_Generic)]
2269 pub enum TraitFn<'hir> {
2270 /// No default body in the trait, just a signature.
2271 Required(&'hir [Ident]),
2273 /// Both signature and body are provided in the trait.
2277 /// Represents a trait method or associated constant or type
2278 #[derive(Debug, HashStable_Generic)]
2279 pub enum TraitItemKind<'hir> {
2280 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
2281 Const(&'hir Ty<'hir>, Option<BodyId>),
2282 /// An associated function with an optional body.
2283 Fn(FnSig<'hir>, TraitFn<'hir>),
2284 /// An associated type with (possibly empty) bounds and optional concrete
2286 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
2289 // The bodies for items are stored "out of line", in a separate
2290 // hashmap in the `Crate`. Here we just record the hir-id of the item
2291 // so it can fetched later.
2292 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2293 pub struct ImplItemId {
2294 pub owner_id: OwnerId,
2299 pub fn hir_id(&self) -> HirId {
2300 // Items are always HIR owners.
2301 HirId::make_owner(self.owner_id.def_id)
2305 /// Represents anything within an `impl` block.
2306 #[derive(Debug, HashStable_Generic)]
2307 pub struct ImplItem<'hir> {
2309 pub owner_id: OwnerId,
2310 pub generics: &'hir Generics<'hir>,
2311 pub kind: ImplItemKind<'hir>,
2312 pub defaultness: Defaultness,
2319 pub fn hir_id(&self) -> HirId {
2320 // Items are always HIR owners.
2321 HirId::make_owner(self.owner_id.def_id)
2324 pub fn impl_item_id(&self) -> ImplItemId {
2325 ImplItemId { owner_id: self.owner_id }
2329 /// Represents various kinds of content within an `impl`.
2330 #[derive(Debug, HashStable_Generic)]
2331 pub enum ImplItemKind<'hir> {
2332 /// An associated constant of the given type, set to the constant result
2333 /// of the expression.
2334 Const(&'hir Ty<'hir>, BodyId),
2335 /// An associated function implementation with the given signature and body.
2336 Fn(FnSig<'hir>, BodyId),
2337 /// An associated type.
2338 Type(&'hir Ty<'hir>),
2341 /// The name of the associated type for `Fn` return types.
2342 pub const FN_OUTPUT_NAME: Symbol = sym::Output;
2344 /// Bind a type to an associated type (i.e., `A = Foo`).
2346 /// Bindings like `A: Debug` are represented as a special type `A =
2347 /// $::Debug` that is understood by the astconv code.
2349 /// FIXME(alexreg): why have a separate type for the binding case,
2350 /// wouldn't it be better to make the `ty` field an enum like the
2353 /// ```ignore (pseudo-rust)
2354 /// enum TypeBindingKind {
2359 #[derive(Debug, HashStable_Generic)]
2360 pub struct TypeBinding<'hir> {
2363 pub gen_args: &'hir GenericArgs<'hir>,
2364 pub kind: TypeBindingKind<'hir>,
2368 #[derive(Debug, HashStable_Generic)]
2369 pub enum Term<'hir> {
2374 impl<'hir> From<&'hir Ty<'hir>> for Term<'hir> {
2375 fn from(ty: &'hir Ty<'hir>) -> Self {
2380 impl<'hir> From<AnonConst> for Term<'hir> {
2381 fn from(c: AnonConst) -> Self {
2386 // Represents the two kinds of type bindings.
2387 #[derive(Debug, HashStable_Generic)]
2388 pub enum TypeBindingKind<'hir> {
2389 /// E.g., `Foo<Bar: Send>`.
2390 Constraint { bounds: &'hir [GenericBound<'hir>] },
2391 /// E.g., `Foo<Bar = ()>`, `Foo<Bar = ()>`
2392 Equality { term: Term<'hir> },
2395 impl TypeBinding<'_> {
2396 pub fn ty(&self) -> &Ty<'_> {
2398 TypeBindingKind::Equality { term: Term::Ty(ref ty) } => ty,
2399 _ => panic!("expected equality type binding for parenthesized generic args"),
2402 pub fn opt_const(&self) -> Option<&'_ AnonConst> {
2404 TypeBindingKind::Equality { term: Term::Const(ref c) } => Some(c),
2410 #[derive(Debug, HashStable_Generic)]
2411 pub struct Ty<'hir> {
2413 pub kind: TyKind<'hir>,
2417 impl<'hir> Ty<'hir> {
2418 /// Returns `true` if `param_def_id` matches the `bounded_ty` of this predicate.
2419 pub fn as_generic_param(&self) -> Option<(DefId, Ident)> {
2420 let TyKind::Path(QPath::Resolved(None, path)) = self.kind else {
2423 let [segment] = &path.segments else {
2427 Res::Def(DefKind::TyParam, def_id) | Res::SelfTyParam { trait_: def_id } => {
2428 Some((def_id, segment.ident))
2434 pub fn peel_refs(&self) -> &Self {
2435 let mut final_ty = self;
2436 while let TyKind::Rptr(_, MutTy { ty, .. }) = &final_ty.kind {
2442 pub fn find_self_aliases(&self) -> Vec<Span> {
2443 use crate::intravisit::Visitor;
2444 struct MyVisitor(Vec<Span>);
2445 impl<'v> Visitor<'v> for MyVisitor {
2446 fn visit_ty(&mut self, t: &'v Ty<'v>) {
2449 TyKind::Path(QPath::Resolved(
2451 Path { res: crate::def::Res::SelfTyAlias { .. }, .. },
2454 self.0.push(t.span);
2457 crate::intravisit::walk_ty(self, t);
2461 let mut my_visitor = MyVisitor(vec![]);
2462 my_visitor.visit_ty(self);
2467 /// Not represented directly in the AST; referred to by name through a `ty_path`.
2468 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
2469 #[derive(HashStable_Generic)]
2480 /// All of the primitive types
2481 pub const ALL: [Self; 17] = [
2482 // any changes here should also be reflected in `PrimTy::from_name`
2483 Self::Int(IntTy::I8),
2484 Self::Int(IntTy::I16),
2485 Self::Int(IntTy::I32),
2486 Self::Int(IntTy::I64),
2487 Self::Int(IntTy::I128),
2488 Self::Int(IntTy::Isize),
2489 Self::Uint(UintTy::U8),
2490 Self::Uint(UintTy::U16),
2491 Self::Uint(UintTy::U32),
2492 Self::Uint(UintTy::U64),
2493 Self::Uint(UintTy::U128),
2494 Self::Uint(UintTy::Usize),
2495 Self::Float(FloatTy::F32),
2496 Self::Float(FloatTy::F64),
2502 /// Like [`PrimTy::name`], but returns a &str instead of a symbol.
2505 pub fn name_str(self) -> &'static str {
2507 PrimTy::Int(i) => i.name_str(),
2508 PrimTy::Uint(u) => u.name_str(),
2509 PrimTy::Float(f) => f.name_str(),
2510 PrimTy::Str => "str",
2511 PrimTy::Bool => "bool",
2512 PrimTy::Char => "char",
2516 pub fn name(self) -> Symbol {
2518 PrimTy::Int(i) => i.name(),
2519 PrimTy::Uint(u) => u.name(),
2520 PrimTy::Float(f) => f.name(),
2521 PrimTy::Str => sym::str,
2522 PrimTy::Bool => sym::bool,
2523 PrimTy::Char => sym::char,
2527 /// Returns the matching `PrimTy` for a `Symbol` such as "str" or "i32".
2528 /// Returns `None` if no matching type is found.
2529 pub fn from_name(name: Symbol) -> Option<Self> {
2530 let ty = match name {
2531 // any changes here should also be reflected in `PrimTy::ALL`
2532 sym::i8 => Self::Int(IntTy::I8),
2533 sym::i16 => Self::Int(IntTy::I16),
2534 sym::i32 => Self::Int(IntTy::I32),
2535 sym::i64 => Self::Int(IntTy::I64),
2536 sym::i128 => Self::Int(IntTy::I128),
2537 sym::isize => Self::Int(IntTy::Isize),
2538 sym::u8 => Self::Uint(UintTy::U8),
2539 sym::u16 => Self::Uint(UintTy::U16),
2540 sym::u32 => Self::Uint(UintTy::U32),
2541 sym::u64 => Self::Uint(UintTy::U64),
2542 sym::u128 => Self::Uint(UintTy::U128),
2543 sym::usize => Self::Uint(UintTy::Usize),
2544 sym::f32 => Self::Float(FloatTy::F32),
2545 sym::f64 => Self::Float(FloatTy::F64),
2546 sym::bool => Self::Bool,
2547 sym::char => Self::Char,
2548 sym::str => Self::Str,
2555 #[derive(Debug, HashStable_Generic)]
2556 pub struct BareFnTy<'hir> {
2557 pub unsafety: Unsafety,
2559 pub generic_params: &'hir [GenericParam<'hir>],
2560 pub decl: &'hir FnDecl<'hir>,
2561 pub param_names: &'hir [Ident],
2564 #[derive(Debug, HashStable_Generic)]
2565 pub struct OpaqueTy<'hir> {
2566 pub generics: &'hir Generics<'hir>,
2567 pub bounds: GenericBounds<'hir>,
2568 pub origin: OpaqueTyOrigin,
2572 /// From whence the opaque type came.
2573 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2574 pub enum OpaqueTyOrigin {
2576 FnReturn(LocalDefId),
2578 AsyncFn(LocalDefId),
2579 /// type aliases: `type Foo = impl Trait;`
2583 /// The various kinds of types recognized by the compiler.
2584 #[derive(Debug, HashStable_Generic)]
2585 pub enum TyKind<'hir> {
2586 /// A variable length slice (i.e., `[T]`).
2587 Slice(&'hir Ty<'hir>),
2588 /// A fixed length array (i.e., `[T; n]`).
2589 Array(&'hir Ty<'hir>, ArrayLen),
2590 /// A raw pointer (i.e., `*const T` or `*mut T`).
2592 /// A reference (i.e., `&'a T` or `&'a mut T`).
2593 Rptr(&'hir Lifetime, MutTy<'hir>),
2594 /// A bare function (e.g., `fn(usize) -> bool`).
2595 BareFn(&'hir BareFnTy<'hir>),
2596 /// The never type (`!`).
2598 /// A tuple (`(A, B, C, D, ...)`).
2599 Tup(&'hir [Ty<'hir>]),
2600 /// A path to a type definition (`module::module::...::Type`), or an
2601 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2603 /// Type parameters may be stored in each `PathSegment`.
2605 /// An opaque type definition itself. This is only used for `impl Trait`.
2607 /// The generic argument list contains the lifetimes (and in the future
2608 /// possibly parameters) that are actually bound on the `impl Trait`.
2610 /// The last parameter specifies whether this opaque appears in a trait definition.
2611 OpaqueDef(ItemId, &'hir [GenericArg<'hir>], bool),
2612 /// A trait object type `Bound1 + Bound2 + Bound3`
2613 /// where `Bound` is a trait or a lifetime.
2614 TraitObject(&'hir [PolyTraitRef<'hir>], &'hir Lifetime, TraitObjectSyntax),
2617 /// `TyKind::Infer` means the type should be inferred instead of it having been
2618 /// specified. This can appear anywhere in a type.
2620 /// Placeholder for a type that has failed to be defined.
2624 #[derive(Debug, HashStable_Generic)]
2625 pub enum InlineAsmOperand<'hir> {
2627 reg: InlineAsmRegOrRegClass,
2628 expr: &'hir Expr<'hir>,
2631 reg: InlineAsmRegOrRegClass,
2633 expr: Option<&'hir Expr<'hir>>,
2636 reg: InlineAsmRegOrRegClass,
2638 expr: &'hir Expr<'hir>,
2641 reg: InlineAsmRegOrRegClass,
2643 in_expr: &'hir Expr<'hir>,
2644 out_expr: Option<&'hir Expr<'hir>>,
2647 anon_const: AnonConst,
2650 anon_const: AnonConst,
2658 impl<'hir> InlineAsmOperand<'hir> {
2659 pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
2661 Self::In { reg, .. }
2662 | Self::Out { reg, .. }
2663 | Self::InOut { reg, .. }
2664 | Self::SplitInOut { reg, .. } => Some(reg),
2665 Self::Const { .. } | Self::SymFn { .. } | Self::SymStatic { .. } => None,
2669 pub fn is_clobber(&self) -> bool {
2672 InlineAsmOperand::Out { reg: InlineAsmRegOrRegClass::Reg(_), late: _, expr: None }
2677 #[derive(Debug, HashStable_Generic)]
2678 pub struct InlineAsm<'hir> {
2679 pub template: &'hir [InlineAsmTemplatePiece],
2680 pub template_strs: &'hir [(Symbol, Option<Symbol>, Span)],
2681 pub operands: &'hir [(InlineAsmOperand<'hir>, Span)],
2682 pub options: InlineAsmOptions,
2683 pub line_spans: &'hir [Span],
2686 /// Represents a parameter in a function header.
2687 #[derive(Debug, HashStable_Generic)]
2688 pub struct Param<'hir> {
2690 pub pat: &'hir Pat<'hir>,
2695 /// Represents the header (not the body) of a function declaration.
2696 #[derive(Debug, HashStable_Generic)]
2697 pub struct FnDecl<'hir> {
2698 /// The types of the function's parameters.
2700 /// Additional argument data is stored in the function's [body](Body::params).
2701 pub inputs: &'hir [Ty<'hir>],
2702 pub output: FnRetTy<'hir>,
2703 pub c_variadic: bool,
2704 /// Does the function have an implicit self?
2705 pub implicit_self: ImplicitSelfKind,
2706 /// Is lifetime elision allowed.
2707 pub lifetime_elision_allowed: bool,
2710 /// Represents what type of implicit self a function has, if any.
2711 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2712 pub enum ImplicitSelfKind {
2713 /// Represents a `fn x(self);`.
2715 /// Represents a `fn x(mut self);`.
2717 /// Represents a `fn x(&self);`.
2719 /// Represents a `fn x(&mut self);`.
2721 /// Represents when a function does not have a self argument or
2722 /// when a function has a `self: X` argument.
2726 impl ImplicitSelfKind {
2727 /// Does this represent an implicit self?
2728 pub fn has_implicit_self(&self) -> bool {
2729 !matches!(*self, ImplicitSelfKind::None)
2733 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable, Debug)]
2734 #[derive(HashStable_Generic)]
2741 pub fn is_async(self) -> bool {
2742 self == IsAsync::Async
2746 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable, HashStable_Generic)]
2747 pub enum Defaultness {
2748 Default { has_value: bool },
2753 pub fn has_value(&self) -> bool {
2755 Defaultness::Default { has_value } => has_value,
2756 Defaultness::Final => true,
2760 pub fn is_final(&self) -> bool {
2761 *self == Defaultness::Final
2764 pub fn is_default(&self) -> bool {
2765 matches!(*self, Defaultness::Default { .. })
2769 #[derive(Debug, HashStable_Generic)]
2770 pub enum FnRetTy<'hir> {
2771 /// Return type is not specified.
2773 /// Functions default to `()` and
2774 /// closures default to inference. Span points to where return
2775 /// type would be inserted.
2776 DefaultReturn(Span),
2777 /// Everything else.
2778 Return(&'hir Ty<'hir>),
2783 pub fn span(&self) -> Span {
2785 Self::DefaultReturn(span) => span,
2786 Self::Return(ref ty) => ty.span,
2791 /// Represents `for<...>` binder before a closure
2792 #[derive(Copy, Clone, Debug, HashStable_Generic)]
2793 pub enum ClosureBinder {
2794 /// Binder is not specified.
2796 /// Binder is specified.
2798 /// Span points to the whole `for<...>`.
2802 #[derive(Encodable, Debug, HashStable_Generic)]
2803 pub struct Mod<'hir> {
2804 pub spans: ModSpans,
2805 pub item_ids: &'hir [ItemId],
2808 #[derive(Copy, Clone, Debug, HashStable_Generic, Encodable)]
2809 pub struct ModSpans {
2810 /// A span from the first token past `{` to the last token until `}`.
2811 /// For `mod foo;`, the inner span ranges from the first token
2812 /// to the last token in the external file.
2813 pub inner_span: Span,
2814 pub inject_use_span: Span,
2817 #[derive(Debug, HashStable_Generic)]
2818 pub struct EnumDef<'hir> {
2819 pub variants: &'hir [Variant<'hir>],
2822 #[derive(Debug, HashStable_Generic)]
2823 pub struct Variant<'hir> {
2824 /// Name of the variant.
2826 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2828 pub def_id: LocalDefId,
2829 /// Fields and constructor id of the variant.
2830 pub data: VariantData<'hir>,
2831 /// Explicit discriminant (e.g., `Foo = 1`).
2832 pub disr_expr: Option<AnonConst>,
2837 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2839 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2840 /// Also produced for each element of a list `use`, e.g.
2841 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2844 /// Glob import, e.g., `use foo::*`.
2847 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2848 /// an additional `use foo::{}` for performing checks such as
2849 /// unstable feature gating. May be removed in the future.
2853 /// References to traits in impls.
2855 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2856 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2857 /// trait being referred to but just a unique `HirId` that serves as a key
2858 /// within the resolution map.
2859 #[derive(Clone, Debug, HashStable_Generic)]
2860 pub struct TraitRef<'hir> {
2861 pub path: &'hir Path<'hir>,
2862 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2863 #[stable_hasher(ignore)]
2864 pub hir_ref_id: HirId,
2868 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2869 pub fn trait_def_id(&self) -> Option<DefId> {
2870 match self.path.res {
2871 Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
2873 _ => unreachable!(),
2878 #[derive(Clone, Debug, HashStable_Generic)]
2879 pub struct PolyTraitRef<'hir> {
2880 /// The `'a` in `for<'a> Foo<&'a T>`.
2881 pub bound_generic_params: &'hir [GenericParam<'hir>],
2883 /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
2884 pub trait_ref: TraitRef<'hir>,
2889 #[derive(Debug, HashStable_Generic)]
2890 pub struct FieldDef<'hir> {
2895 pub def_id: LocalDefId,
2896 pub ty: &'hir Ty<'hir>,
2900 // Still necessary in couple of places
2901 pub fn is_positional(&self) -> bool {
2902 let first = self.ident.as_str().as_bytes()[0];
2903 (b'0'..=b'9').contains(&first)
2907 /// Fields and constructor IDs of enum variants and structs.
2908 #[derive(Debug, HashStable_Generic)]
2909 pub enum VariantData<'hir> {
2910 /// A struct variant.
2912 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2913 Struct(&'hir [FieldDef<'hir>], /* recovered */ bool),
2914 /// A tuple variant.
2916 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2917 Tuple(&'hir [FieldDef<'hir>], HirId, LocalDefId),
2920 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2921 Unit(HirId, LocalDefId),
2924 impl<'hir> VariantData<'hir> {
2925 /// Return the fields of this variant.
2926 pub fn fields(&self) -> &'hir [FieldDef<'hir>] {
2928 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2933 pub fn ctor(&self) -> Option<(CtorKind, HirId, LocalDefId)> {
2935 VariantData::Tuple(_, hir_id, def_id) => Some((CtorKind::Fn, hir_id, def_id)),
2936 VariantData::Unit(hir_id, def_id) => Some((CtorKind::Const, hir_id, def_id)),
2937 VariantData::Struct(..) => None,
2942 pub fn ctor_kind(&self) -> Option<CtorKind> {
2943 self.ctor().map(|(kind, ..)| kind)
2946 /// Return the `HirId` of this variant's constructor, if it has one.
2948 pub fn ctor_hir_id(&self) -> Option<HirId> {
2949 self.ctor().map(|(_, hir_id, _)| hir_id)
2952 /// Return the `LocalDefId` of this variant's constructor, if it has one.
2954 pub fn ctor_def_id(&self) -> Option<LocalDefId> {
2955 self.ctor().map(|(.., def_id)| def_id)
2959 // The bodies for items are stored "out of line", in a separate
2960 // hashmap in the `Crate`. Here we just record the hir-id of the item
2961 // so it can fetched later.
2962 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
2964 pub owner_id: OwnerId,
2969 pub fn hir_id(&self) -> HirId {
2970 // Items are always HIR owners.
2971 HirId::make_owner(self.owner_id.def_id)
2977 /// The name might be a dummy name in case of anonymous items
2978 #[derive(Debug, HashStable_Generic)]
2979 pub struct Item<'hir> {
2981 pub owner_id: OwnerId,
2982 pub kind: ItemKind<'hir>,
2989 pub fn hir_id(&self) -> HirId {
2990 // Items are always HIR owners.
2991 HirId::make_owner(self.owner_id.def_id)
2994 pub fn item_id(&self) -> ItemId {
2995 ItemId { owner_id: self.owner_id }
2999 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
3000 #[derive(Encodable, Decodable, HashStable_Generic)]
3007 pub fn prefix_str(&self) -> &'static str {
3009 Self::Unsafe => "unsafe ",
3015 impl fmt::Display for Unsafety {
3016 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3017 f.write_str(match *self {
3018 Self::Unsafe => "unsafe",
3019 Self::Normal => "normal",
3024 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
3025 #[derive(Encodable, Decodable, HashStable_Generic)]
3026 pub enum Constness {
3031 impl fmt::Display for Constness {
3032 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3033 f.write_str(match *self {
3034 Self::Const => "const",
3035 Self::NotConst => "non-const",
3040 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
3041 pub struct FnHeader {
3042 pub unsafety: Unsafety,
3043 pub constness: Constness,
3044 pub asyncness: IsAsync,
3049 pub fn is_async(&self) -> bool {
3050 matches!(&self.asyncness, IsAsync::Async)
3053 pub fn is_const(&self) -> bool {
3054 matches!(&self.constness, Constness::Const)
3057 pub fn is_unsafe(&self) -> bool {
3058 matches!(&self.unsafety, Unsafety::Unsafe)
3062 #[derive(Debug, HashStable_Generic)]
3063 pub enum ItemKind<'hir> {
3064 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
3066 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
3067 ExternCrate(Option<Symbol>),
3069 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
3073 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
3074 Use(&'hir UsePath<'hir>, UseKind),
3076 /// A `static` item.
3077 Static(&'hir Ty<'hir>, Mutability, BodyId),
3079 Const(&'hir Ty<'hir>, BodyId),
3080 /// A function declaration.
3081 Fn(FnSig<'hir>, &'hir Generics<'hir>, BodyId),
3082 /// A MBE macro definition (`macro_rules!` or `macro`).
3083 Macro(ast::MacroDef, MacroKind),
3085 Mod(&'hir Mod<'hir>),
3086 /// An external module, e.g. `extern { .. }`.
3087 ForeignMod { abi: Abi, items: &'hir [ForeignItemRef] },
3088 /// Module-level inline assembly (from `global_asm!`).
3089 GlobalAsm(&'hir InlineAsm<'hir>),
3090 /// A type alias, e.g., `type Foo = Bar<u8>`.
3091 TyAlias(&'hir Ty<'hir>, &'hir Generics<'hir>),
3092 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
3093 OpaqueTy(OpaqueTy<'hir>),
3094 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
3095 Enum(EnumDef<'hir>, &'hir Generics<'hir>),
3096 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
3097 Struct(VariantData<'hir>, &'hir Generics<'hir>),
3098 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
3099 Union(VariantData<'hir>, &'hir Generics<'hir>),
3100 /// A trait definition.
3101 Trait(IsAuto, Unsafety, &'hir Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
3103 TraitAlias(&'hir Generics<'hir>, GenericBounds<'hir>),
3105 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
3106 Impl(&'hir Impl<'hir>),
3109 #[derive(Debug, HashStable_Generic)]
3110 pub struct Impl<'hir> {
3111 pub unsafety: Unsafety,
3112 pub polarity: ImplPolarity,
3113 pub defaultness: Defaultness,
3114 // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata
3115 // decoding as `Span`s cannot be decoded when a `Session` is not available.
3116 pub defaultness_span: Option<Span>,
3117 pub constness: Constness,
3118 pub generics: &'hir Generics<'hir>,
3120 /// The trait being implemented, if any.
3121 pub of_trait: Option<TraitRef<'hir>>,
3123 pub self_ty: &'hir Ty<'hir>,
3124 pub items: &'hir [ImplItemRef],
3128 pub fn generics(&self) -> Option<&Generics<'_>> {
3130 ItemKind::Fn(_, ref generics, _)
3131 | ItemKind::TyAlias(_, ref generics)
3132 | ItemKind::OpaqueTy(OpaqueTy { ref generics, .. })
3133 | ItemKind::Enum(_, ref generics)
3134 | ItemKind::Struct(_, ref generics)
3135 | ItemKind::Union(_, ref generics)
3136 | ItemKind::Trait(_, _, ref generics, _, _)
3137 | ItemKind::TraitAlias(ref generics, _)
3138 | ItemKind::Impl(Impl { ref generics, .. }) => generics,
3143 pub fn descr(&self) -> &'static str {
3145 ItemKind::ExternCrate(..) => "extern crate",
3146 ItemKind::Use(..) => "`use` import",
3147 ItemKind::Static(..) => "static item",
3148 ItemKind::Const(..) => "constant item",
3149 ItemKind::Fn(..) => "function",
3150 ItemKind::Macro(..) => "macro",
3151 ItemKind::Mod(..) => "module",
3152 ItemKind::ForeignMod { .. } => "extern block",
3153 ItemKind::GlobalAsm(..) => "global asm item",
3154 ItemKind::TyAlias(..) => "type alias",
3155 ItemKind::OpaqueTy(..) => "opaque type",
3156 ItemKind::Enum(..) => "enum",
3157 ItemKind::Struct(..) => "struct",
3158 ItemKind::Union(..) => "union",
3159 ItemKind::Trait(..) => "trait",
3160 ItemKind::TraitAlias(..) => "trait alias",
3161 ItemKind::Impl(..) => "implementation",
3166 /// A reference from an trait to one of its associated items. This
3167 /// contains the item's id, naturally, but also the item's name and
3168 /// some other high-level details (like whether it is an associated
3169 /// type or method, and whether it is public). This allows other
3170 /// passes to find the impl they want without loading the ID (which
3171 /// means fewer edges in the incremental compilation graph).
3172 #[derive(Encodable, Debug, HashStable_Generic)]
3173 pub struct TraitItemRef {
3174 pub id: TraitItemId,
3176 pub kind: AssocItemKind,
3180 /// A reference from an impl to one of its associated items. This
3181 /// contains the item's ID, naturally, but also the item's name and
3182 /// some other high-level details (like whether it is an associated
3183 /// type or method, and whether it is public). This allows other
3184 /// passes to find the impl they want without loading the ID (which
3185 /// means fewer edges in the incremental compilation graph).
3186 #[derive(Debug, HashStable_Generic)]
3187 pub struct ImplItemRef {
3190 pub kind: AssocItemKind,
3192 /// When we are in a trait impl, link to the trait-item's id.
3193 pub trait_item_def_id: Option<DefId>,
3196 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
3197 pub enum AssocItemKind {
3199 Fn { has_self: bool },
3203 // The bodies for items are stored "out of line", in a separate
3204 // hashmap in the `Crate`. Here we just record the hir-id of the item
3205 // so it can fetched later.
3206 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3207 pub struct ForeignItemId {
3208 pub owner_id: OwnerId,
3211 impl ForeignItemId {
3213 pub fn hir_id(&self) -> HirId {
3214 // Items are always HIR owners.
3215 HirId::make_owner(self.owner_id.def_id)
3219 /// A reference from a foreign block to one of its items. This
3220 /// contains the item's ID, naturally, but also the item's name and
3221 /// some other high-level details (like whether it is an associated
3222 /// type or method, and whether it is public). This allows other
3223 /// passes to find the impl they want without loading the ID (which
3224 /// means fewer edges in the incremental compilation graph).
3225 #[derive(Debug, HashStable_Generic)]
3226 pub struct ForeignItemRef {
3227 pub id: ForeignItemId,
3232 #[derive(Debug, HashStable_Generic)]
3233 pub struct ForeignItem<'hir> {
3235 pub kind: ForeignItemKind<'hir>,
3236 pub owner_id: OwnerId,
3241 impl ForeignItem<'_> {
3243 pub fn hir_id(&self) -> HirId {
3244 // Items are always HIR owners.
3245 HirId::make_owner(self.owner_id.def_id)
3248 pub fn foreign_item_id(&self) -> ForeignItemId {
3249 ForeignItemId { owner_id: self.owner_id }
3253 /// An item within an `extern` block.
3254 #[derive(Debug, HashStable_Generic)]
3255 pub enum ForeignItemKind<'hir> {
3256 /// A foreign function.
3257 Fn(&'hir FnDecl<'hir>, &'hir [Ident], &'hir Generics<'hir>),
3258 /// A foreign static item (`static ext: u8`).
3259 Static(&'hir Ty<'hir>, Mutability),
3264 /// A variable captured by a closure.
3265 #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)]
3267 /// First span where it is accessed (there can be multiple).
3271 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
3272 // has length > 0 if the trait is found through an chain of imports, starting with the
3273 // import/use statement in the scope where the trait is used.
3274 #[derive(Encodable, Decodable, Clone, Debug, HashStable_Generic)]
3275 pub struct TraitCandidate {
3277 pub import_ids: SmallVec<[LocalDefId; 1]>,
3280 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3281 pub enum OwnerNode<'hir> {
3282 Item(&'hir Item<'hir>),
3283 ForeignItem(&'hir ForeignItem<'hir>),
3284 TraitItem(&'hir TraitItem<'hir>),
3285 ImplItem(&'hir ImplItem<'hir>),
3286 Crate(&'hir Mod<'hir>),
3289 impl<'hir> OwnerNode<'hir> {
3290 pub fn ident(&self) -> Option<Ident> {
3292 OwnerNode::Item(Item { ident, .. })
3293 | OwnerNode::ForeignItem(ForeignItem { ident, .. })
3294 | OwnerNode::ImplItem(ImplItem { ident, .. })
3295 | OwnerNode::TraitItem(TraitItem { ident, .. }) => Some(*ident),
3296 OwnerNode::Crate(..) => None,
3300 pub fn span(&self) -> Span {
3302 OwnerNode::Item(Item { span, .. })
3303 | OwnerNode::ForeignItem(ForeignItem { span, .. })
3304 | OwnerNode::ImplItem(ImplItem { span, .. })
3305 | OwnerNode::TraitItem(TraitItem { span, .. }) => *span,
3306 OwnerNode::Crate(Mod { spans: ModSpans { inner_span, .. }, .. }) => *inner_span,
3310 pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
3312 OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3313 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3314 | OwnerNode::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3315 OwnerNode::ForeignItem(ForeignItem {
3316 kind: ForeignItemKind::Fn(fn_decl, _, _),
3318 }) => Some(fn_decl),
3323 pub fn body_id(&self) -> Option<BodyId> {
3325 OwnerNode::TraitItem(TraitItem {
3326 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3329 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3330 | OwnerNode::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3335 pub fn generics(self) -> Option<&'hir Generics<'hir>> {
3336 Node::generics(self.into())
3339 pub fn def_id(self) -> OwnerId {
3341 OwnerNode::Item(Item { owner_id, .. })
3342 | OwnerNode::TraitItem(TraitItem { owner_id, .. })
3343 | OwnerNode::ImplItem(ImplItem { owner_id, .. })
3344 | OwnerNode::ForeignItem(ForeignItem { owner_id, .. }) => *owner_id,
3345 OwnerNode::Crate(..) => crate::CRATE_HIR_ID.owner,
3349 pub fn expect_item(self) -> &'hir Item<'hir> {
3351 OwnerNode::Item(n) => n,
3356 pub fn expect_foreign_item(self) -> &'hir ForeignItem<'hir> {
3358 OwnerNode::ForeignItem(n) => n,
3363 pub fn expect_impl_item(self) -> &'hir ImplItem<'hir> {
3365 OwnerNode::ImplItem(n) => n,
3370 pub fn expect_trait_item(self) -> &'hir TraitItem<'hir> {
3372 OwnerNode::TraitItem(n) => n,
3378 impl<'hir> Into<OwnerNode<'hir>> for &'hir Item<'hir> {
3379 fn into(self) -> OwnerNode<'hir> {
3380 OwnerNode::Item(self)
3384 impl<'hir> Into<OwnerNode<'hir>> for &'hir ForeignItem<'hir> {
3385 fn into(self) -> OwnerNode<'hir> {
3386 OwnerNode::ForeignItem(self)
3390 impl<'hir> Into<OwnerNode<'hir>> for &'hir ImplItem<'hir> {
3391 fn into(self) -> OwnerNode<'hir> {
3392 OwnerNode::ImplItem(self)
3396 impl<'hir> Into<OwnerNode<'hir>> for &'hir TraitItem<'hir> {
3397 fn into(self) -> OwnerNode<'hir> {
3398 OwnerNode::TraitItem(self)
3402 impl<'hir> Into<Node<'hir>> for OwnerNode<'hir> {
3403 fn into(self) -> Node<'hir> {
3405 OwnerNode::Item(n) => Node::Item(n),
3406 OwnerNode::ForeignItem(n) => Node::ForeignItem(n),
3407 OwnerNode::ImplItem(n) => Node::ImplItem(n),
3408 OwnerNode::TraitItem(n) => Node::TraitItem(n),
3409 OwnerNode::Crate(n) => Node::Crate(n),
3414 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3415 pub enum Node<'hir> {
3416 Param(&'hir Param<'hir>),
3417 Item(&'hir Item<'hir>),
3418 ForeignItem(&'hir ForeignItem<'hir>),
3419 TraitItem(&'hir TraitItem<'hir>),
3420 ImplItem(&'hir ImplItem<'hir>),
3421 Variant(&'hir Variant<'hir>),
3422 Field(&'hir FieldDef<'hir>),
3423 AnonConst(&'hir AnonConst),
3424 Expr(&'hir Expr<'hir>),
3425 ExprField(&'hir ExprField<'hir>),
3426 Stmt(&'hir Stmt<'hir>),
3427 PathSegment(&'hir PathSegment<'hir>),
3429 TypeBinding(&'hir TypeBinding<'hir>),
3430 TraitRef(&'hir TraitRef<'hir>),
3431 Pat(&'hir Pat<'hir>),
3432 PatField(&'hir PatField<'hir>),
3433 Arm(&'hir Arm<'hir>),
3434 Block(&'hir Block<'hir>),
3435 Local(&'hir Local<'hir>),
3437 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
3438 /// with synthesized constructors.
3439 Ctor(&'hir VariantData<'hir>),
3441 Lifetime(&'hir Lifetime),
3442 GenericParam(&'hir GenericParam<'hir>),
3444 Crate(&'hir Mod<'hir>),
3446 Infer(&'hir InferArg),
3449 impl<'hir> Node<'hir> {
3450 /// Get the identifier of this `Node`, if applicable.
3454 /// Calling `.ident()` on a [`Node::Ctor`] will return `None`
3455 /// because `Ctor`s do not have identifiers themselves.
3456 /// Instead, call `.ident()` on the parent struct/variant, like so:
3458 /// ```ignore (illustrative)
3461 /// .and_then(|ctor_id| tcx.hir().find(tcx.hir().get_parent_node(ctor_id)))
3462 /// .and_then(|parent| parent.ident())
3464 pub fn ident(&self) -> Option<Ident> {
3466 Node::TraitItem(TraitItem { ident, .. })
3467 | Node::ImplItem(ImplItem { ident, .. })
3468 | Node::ForeignItem(ForeignItem { ident, .. })
3469 | Node::Field(FieldDef { ident, .. })
3470 | Node::Variant(Variant { ident, .. })
3471 | Node::Item(Item { ident, .. })
3472 | Node::PathSegment(PathSegment { ident, .. }) => Some(*ident),
3473 Node::Lifetime(lt) => Some(lt.ident),
3474 Node::GenericParam(p) => Some(p.name.ident()),
3475 Node::TypeBinding(b) => Some(b.ident),
3477 | Node::AnonConst(..)
3483 | Node::PatField(..)
3484 | Node::ExprField(..)
3489 | Node::TraitRef(..)
3490 | Node::Infer(..) => None,
3494 pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
3496 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3497 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3498 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3499 Node::Expr(Expr { kind: ExprKind::Closure(Closure { fn_decl, .. }), .. })
3500 | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
3507 pub fn fn_sig(self) -> Option<&'hir FnSig<'hir>> {
3509 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3510 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3511 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig),
3516 pub fn body_id(&self) -> Option<BodyId> {
3518 Node::TraitItem(TraitItem {
3519 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3522 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3523 | Node::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3528 pub fn generics(self) -> Option<&'hir Generics<'hir>> {
3530 Node::ForeignItem(ForeignItem {
3531 kind: ForeignItemKind::Fn(_, _, generics), ..
3533 | Node::TraitItem(TraitItem { generics, .. })
3534 | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
3535 Node::Item(item) => item.kind.generics(),
3540 pub fn as_owner(self) -> Option<OwnerNode<'hir>> {
3542 Node::Item(i) => Some(OwnerNode::Item(i)),
3543 Node::ForeignItem(i) => Some(OwnerNode::ForeignItem(i)),
3544 Node::TraitItem(i) => Some(OwnerNode::TraitItem(i)),
3545 Node::ImplItem(i) => Some(OwnerNode::ImplItem(i)),
3546 Node::Crate(i) => Some(OwnerNode::Crate(i)),
3551 pub fn fn_kind(self) -> Option<FnKind<'hir>> {
3553 Node::Item(i) => match i.kind {
3554 ItemKind::Fn(ref sig, ref generics, _) => {
3555 Some(FnKind::ItemFn(i.ident, generics, sig.header))
3559 Node::TraitItem(ti) => match ti.kind {
3560 TraitItemKind::Fn(ref sig, TraitFn::Provided(_)) => {
3561 Some(FnKind::Method(ti.ident, sig))
3565 Node::ImplItem(ii) => match ii.kind {
3566 ImplItemKind::Fn(ref sig, _) => Some(FnKind::Method(ii.ident, sig)),
3569 Node::Expr(e) => match e.kind {
3570 ExprKind::Closure { .. } => Some(FnKind::Closure),
3577 /// Get the fields for the tuple-constructor,
3578 /// if this node is a tuple constructor, otherwise None
3579 pub fn tuple_fields(&self) -> Option<&'hir [FieldDef<'hir>]> {
3580 if let Node::Ctor(&VariantData::Tuple(fields, _, _)) = self { Some(fields) } else { None }
3584 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3585 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
3588 // tidy-alphabetical-start
3589 static_assert_size!(Block<'_>, 48);
3590 static_assert_size!(Body<'_>, 32);
3591 static_assert_size!(Expr<'_>, 64);
3592 static_assert_size!(ExprKind<'_>, 48);
3593 static_assert_size!(FnDecl<'_>, 40);
3594 static_assert_size!(ForeignItem<'_>, 72);
3595 static_assert_size!(ForeignItemKind<'_>, 40);
3596 static_assert_size!(GenericArg<'_>, 32);
3597 static_assert_size!(GenericBound<'_>, 48);
3598 static_assert_size!(Generics<'_>, 56);
3599 static_assert_size!(Impl<'_>, 80);
3600 static_assert_size!(ImplItem<'_>, 80);
3601 static_assert_size!(ImplItemKind<'_>, 32);
3602 static_assert_size!(Item<'_>, 80);
3603 static_assert_size!(ItemKind<'_>, 48);
3604 static_assert_size!(Local<'_>, 64);
3605 static_assert_size!(Param<'_>, 32);
3606 static_assert_size!(Pat<'_>, 72);
3607 static_assert_size!(Path<'_>, 40);
3608 static_assert_size!(PathSegment<'_>, 48);
3609 static_assert_size!(PatKind<'_>, 48);
3610 static_assert_size!(QPath<'_>, 24);
3611 static_assert_size!(Res, 12);
3612 static_assert_size!(Stmt<'_>, 32);
3613 static_assert_size!(StmtKind<'_>, 16);
3614 // tidy-alphabetical-end
3615 // FIXME: move the tidy directive to the end after the next bootstrap bump
3617 static_assert_size!(TraitItem<'_>, 88);
3618 #[cfg(not(bootstrap))]
3619 static_assert_size!(TraitItem<'_>, 80);
3621 static_assert_size!(TraitItemKind<'_>, 48);
3622 #[cfg(not(bootstrap))]
3623 static_assert_size!(TraitItemKind<'_>, 40);
3624 static_assert_size!(Ty<'_>, 48);
3625 static_assert_size!(TyKind<'_>, 32);