1 use crate::def::{CtorKind, DefKind, Res};
2 use crate::def_id::DefId;
3 pub(crate) use crate::hir_id::{HirId, ItemLocalId, OwnerId};
4 use crate::intravisit::FnKind;
8 use rustc_ast::util::parser::ExprPrecedence;
9 use rustc_ast::{Attribute, FloatTy, IntTy, Label, LitKind, TraitObjectSyntax, UintTy};
10 pub use rustc_ast::{BindingAnnotation, BorrowKind, ByRef, ImplPolarity, IsAuto};
11 pub use rustc_ast::{CaptureBy, Movability, Mutability};
12 use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
13 use rustc_data_structures::fingerprint::Fingerprint;
14 use rustc_data_structures::fx::FxHashMap;
15 use rustc_data_structures::sorted_map::SortedMap;
16 use rustc_error_messages::MultiSpan;
17 use rustc_index::vec::IndexVec;
18 use rustc_macros::HashStable_Generic;
19 use rustc_span::hygiene::MacroKind;
20 use rustc_span::source_map::Spanned;
21 use rustc_span::symbol::{kw, sym, Ident, Symbol};
22 use rustc_span::{def_id::LocalDefId, BytePos, Span, DUMMY_SP};
23 use rustc_target::asm::InlineAsmRegOrRegClass;
24 use rustc_target::spec::abi::Abi;
26 use smallvec::SmallVec;
29 #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)]
34 /// Either "`'a`", referring to a named lifetime definition,
35 /// or "``" (i.e., `kw::Empty`), for elision placeholders.
37 /// HIR lowering inserts these placeholders in type paths that
38 /// refer to type definitions needing lifetime parameters,
39 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
40 pub name: LifetimeName,
43 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
44 #[derive(HashStable_Generic)]
46 /// Some user-given name like `T` or `'x`.
49 /// Synthetic name generated when user elided a lifetime in an impl header.
51 /// E.g., the lifetimes in cases like these:
52 /// ```ignore (fragment)
54 /// impl Foo<'_> for u32
56 /// in that case, we rewrite to
57 /// ```ignore (fragment)
58 /// impl<'f> Foo for &'f u32
59 /// impl<'f> Foo<'f> for u32
61 /// where `'f` is something like `Fresh(0)`. The indices are
62 /// unique per impl, but not necessarily continuous.
65 /// Indicates an illegal name was given and an error has been
66 /// reported (so we should squelch other derived errors). Occurs
67 /// when, e.g., `'_` is used in the wrong place.
72 pub fn ident(&self) -> Ident {
74 ParamName::Plain(ident) => ident,
75 ParamName::Fresh | ParamName::Error => Ident::with_dummy_span(kw::UnderscoreLifetime),
79 pub fn normalize_to_macros_2_0(&self) -> ParamName {
81 ParamName::Plain(ident) => ParamName::Plain(ident.normalize_to_macros_2_0()),
82 param_name => param_name,
87 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
88 #[derive(HashStable_Generic)]
89 pub enum LifetimeName {
90 /// User-given names or fresh (synthetic) names.
91 Param(LocalDefId, ParamName),
93 /// Implicit lifetime in a context like `dyn Foo`. This is
94 /// distinguished from implicit lifetimes elsewhere because the
95 /// lifetime that they default to must appear elsewhere within the
96 /// enclosing type. This means that, in an `impl Trait` context, we
97 /// don't have to create a parameter for them. That is, `impl
98 /// Trait<Item = &u32>` expands to an opaque type like `type
99 /// Foo<'a> = impl Trait<Item = &'a u32>`, but `impl Trait<item =
100 /// dyn Bar>` expands to `type Foo = impl Trait<Item = dyn Bar +
101 /// 'static>`. The latter uses `ImplicitObjectLifetimeDefault` so
102 /// that surrounding code knows not to create a lifetime
104 ImplicitObjectLifetimeDefault,
106 /// Indicates an error during lowering (usually `'_` in wrong place)
107 /// that was already reported.
110 /// User wrote an anonymous lifetime, either `'_` or nothing.
111 /// The semantics of this lifetime should be inferred by typechecking code.
114 /// User wrote `'static`.
119 pub fn ident(&self) -> Ident {
121 LifetimeName::ImplicitObjectLifetimeDefault | LifetimeName::Error => Ident::empty(),
122 LifetimeName::Infer => Ident::with_dummy_span(kw::UnderscoreLifetime),
123 LifetimeName::Static => Ident::with_dummy_span(kw::StaticLifetime),
124 LifetimeName::Param(_, param_name) => param_name.ident(),
128 pub fn is_anonymous(&self) -> bool {
130 LifetimeName::ImplicitObjectLifetimeDefault
131 | LifetimeName::Infer
132 | LifetimeName::Param(_, ParamName::Fresh)
133 | LifetimeName::Error => true,
134 LifetimeName::Static | LifetimeName::Param(..) => false,
138 pub fn is_elided(&self) -> bool {
140 LifetimeName::ImplicitObjectLifetimeDefault | LifetimeName::Infer => true,
142 // It might seem surprising that `Fresh` counts as not *elided*
143 // -- but this is because, as far as the code in the compiler is
144 // concerned -- `Fresh` variants act equivalently to "some fresh name".
145 // They correspond to early-bound regions on an impl, in other words.
146 LifetimeName::Error | LifetimeName::Param(..) | LifetimeName::Static => false,
150 fn is_static(&self) -> bool {
151 self == &LifetimeName::Static
154 pub fn normalize_to_macros_2_0(&self) -> LifetimeName {
156 LifetimeName::Param(def_id, param_name) => {
157 LifetimeName::Param(def_id, param_name.normalize_to_macros_2_0())
159 lifetime_name => lifetime_name,
164 impl fmt::Display for Lifetime {
165 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166 self.name.ident().fmt(f)
171 pub fn is_elided(&self) -> bool {
172 self.name.is_elided()
175 pub fn is_static(&self) -> bool {
176 self.name.is_static()
180 /// A `Path` is essentially Rust's notion of a name; for instance,
181 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
182 /// along with a bunch of supporting information.
183 #[derive(Debug, HashStable_Generic)]
184 pub struct Path<'hir> {
186 /// The resolution for the path.
188 /// The segments in the path: the things separated by `::`.
189 pub segments: &'hir [PathSegment<'hir>],
193 pub fn is_global(&self) -> bool {
194 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
198 /// A segment of a path: an identifier, an optional lifetime, and a set of
200 #[derive(Debug, HashStable_Generic)]
201 pub struct PathSegment<'hir> {
202 /// The identifier portion of this path segment.
207 /// Type/lifetime parameters attached to this path. They come in
208 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
209 /// this is more than just simple syntactic sugar; the use of
210 /// parens affects the region binding rules, so we preserve the
212 pub args: Option<&'hir GenericArgs<'hir>>,
214 /// Whether to infer remaining type parameters, if any.
215 /// This only applies to expression and pattern paths, and
216 /// out of those only the segments with no type parameters
217 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
218 pub infer_args: bool,
221 impl<'hir> PathSegment<'hir> {
222 /// Converts an identifier to the corresponding segment.
223 pub fn new(ident: Ident, hir_id: HirId, res: Res) -> PathSegment<'hir> {
224 PathSegment { ident, hir_id, res, infer_args: true, args: None }
227 pub fn invalid() -> Self {
228 Self::new(Ident::empty(), HirId::INVALID, Res::Err)
231 pub fn args(&self) -> &GenericArgs<'hir> {
232 if let Some(ref args) = self.args {
235 const DUMMY: &GenericArgs<'_> = &GenericArgs::none();
241 #[derive(Encodable, Debug, HashStable_Generic)]
242 pub struct ConstArg {
243 pub value: AnonConst,
247 #[derive(Encodable, Debug, HashStable_Generic)]
248 pub struct InferArg {
254 pub fn to_ty(&self) -> Ty<'_> {
255 Ty { kind: TyKind::Infer, span: self.span, hir_id: self.hir_id }
259 #[derive(Debug, HashStable_Generic)]
260 pub enum GenericArg<'hir> {
261 Lifetime(&'hir Lifetime),
262 Type(&'hir Ty<'hir>),
267 impl GenericArg<'_> {
268 pub fn span(&self) -> Span {
270 GenericArg::Lifetime(l) => l.span,
271 GenericArg::Type(t) => t.span,
272 GenericArg::Const(c) => c.span,
273 GenericArg::Infer(i) => i.span,
277 pub fn hir_id(&self) -> HirId {
279 GenericArg::Lifetime(l) => l.hir_id,
280 GenericArg::Type(t) => t.hir_id,
281 GenericArg::Const(c) => c.value.hir_id,
282 GenericArg::Infer(i) => i.hir_id,
286 pub fn is_synthetic(&self) -> bool {
287 matches!(self, GenericArg::Lifetime(lifetime) if lifetime.name.ident() == Ident::empty())
290 pub fn descr(&self) -> &'static str {
292 GenericArg::Lifetime(_) => "lifetime",
293 GenericArg::Type(_) => "type",
294 GenericArg::Const(_) => "constant",
295 GenericArg::Infer(_) => "inferred",
299 pub fn to_ord(&self) -> ast::ParamKindOrd {
301 GenericArg::Lifetime(_) => ast::ParamKindOrd::Lifetime,
302 GenericArg::Type(_) | GenericArg::Const(_) | GenericArg::Infer(_) => {
303 ast::ParamKindOrd::TypeOrConst
308 pub fn is_ty_or_const(&self) -> bool {
310 GenericArg::Lifetime(_) => false,
311 GenericArg::Type(_) | GenericArg::Const(_) | GenericArg::Infer(_) => true,
316 #[derive(Debug, HashStable_Generic)]
317 pub struct GenericArgs<'hir> {
318 /// The generic arguments for this path segment.
319 pub args: &'hir [GenericArg<'hir>],
320 /// Bindings (equality constraints) on associated types, if present.
321 /// E.g., `Foo<A = Bar>`.
322 pub bindings: &'hir [TypeBinding<'hir>],
323 /// Were arguments written in parenthesized form `Fn(T) -> U`?
324 /// This is required mostly for pretty-printing and diagnostics,
325 /// but also for changing lifetime elision rules to be "function-like".
326 pub parenthesized: bool,
327 /// The span encompassing arguments and the surrounding brackets `<>` or `()`
328 /// Foo<A, B, AssocTy = D> Fn(T, U, V) -> W
329 /// ^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^
330 /// Note that this may be:
331 /// - empty, if there are no generic brackets (but there may be hidden lifetimes)
332 /// - dummy, if this was generated while desugaring
336 impl<'hir> GenericArgs<'hir> {
337 pub const fn none() -> Self {
338 Self { args: &[], bindings: &[], parenthesized: false, span_ext: DUMMY_SP }
341 pub fn inputs(&self) -> &[Ty<'hir>] {
342 if self.parenthesized {
343 for arg in self.args {
345 GenericArg::Lifetime(_) => {}
346 GenericArg::Type(ref ty) => {
347 if let TyKind::Tup(ref tys) = ty.kind {
352 GenericArg::Const(_) => {}
353 GenericArg::Infer(_) => {}
357 panic!("GenericArgs::inputs: not a `Fn(T) -> U`");
361 pub fn has_type_params(&self) -> bool {
362 self.args.iter().any(|arg| matches!(arg, GenericArg::Type(_)))
365 pub fn has_err(&self) -> bool {
366 self.args.iter().any(|arg| match arg {
367 GenericArg::Type(ty) => matches!(ty.kind, TyKind::Err),
369 }) || self.bindings.iter().any(|arg| match arg.kind {
370 TypeBindingKind::Equality { term: Term::Ty(ty) } => matches!(ty.kind, TyKind::Err),
376 pub fn num_type_params(&self) -> usize {
377 self.args.iter().filter(|arg| matches!(arg, GenericArg::Type(_))).count()
381 pub fn num_lifetime_params(&self) -> usize {
382 self.args.iter().filter(|arg| matches!(arg, GenericArg::Lifetime(_))).count()
386 pub fn has_lifetime_params(&self) -> bool {
387 self.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)))
391 /// This function returns the number of type and const generic params.
392 /// It should only be used for diagnostics.
393 pub fn num_generic_params(&self) -> usize {
394 self.args.iter().filter(|arg| !matches!(arg, GenericArg::Lifetime(_))).count()
397 /// The span encompassing the text inside the surrounding brackets.
398 /// It will also include bindings if they aren't in the form `-> Ret`
399 /// Returns `None` if the span is empty (e.g. no brackets) or dummy
400 pub fn span(&self) -> Option<Span> {
401 let span_ext = self.span_ext()?;
402 Some(span_ext.with_lo(span_ext.lo() + BytePos(1)).with_hi(span_ext.hi() - BytePos(1)))
405 /// Returns span encompassing arguments and their surrounding `<>` or `()`
406 pub fn span_ext(&self) -> Option<Span> {
407 Some(self.span_ext).filter(|span| !span.is_empty())
410 pub fn is_empty(&self) -> bool {
415 /// A modifier on a bound, currently this is only used for `?Sized`, where the
416 /// modifier is `Maybe`. Negative bounds should also be handled here.
417 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
418 #[derive(HashStable_Generic)]
419 pub enum TraitBoundModifier {
425 /// The AST represents all type param bounds as types.
426 /// `typeck::collect::compute_bounds` matches these against
427 /// the "special" built-in traits (see `middle::lang_items`) and
428 /// detects `Copy`, `Send` and `Sync`.
429 #[derive(Clone, Debug, HashStable_Generic)]
430 pub enum GenericBound<'hir> {
431 Trait(PolyTraitRef<'hir>, TraitBoundModifier),
432 // FIXME(davidtwco): Introduce `PolyTraitRef::LangItem`
433 LangItemTrait(LangItem, Span, HirId, &'hir GenericArgs<'hir>),
434 Outlives(&'hir Lifetime),
437 impl GenericBound<'_> {
438 pub fn trait_ref(&self) -> Option<&TraitRef<'_>> {
440 GenericBound::Trait(data, _) => Some(&data.trait_ref),
445 pub fn span(&self) -> Span {
447 GenericBound::Trait(t, ..) => t.span,
448 GenericBound::LangItemTrait(_, span, ..) => *span,
449 GenericBound::Outlives(l) => l.span,
454 pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
456 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
457 pub enum LifetimeParamKind {
458 // Indicates that the lifetime definition was explicitly declared (e.g., in
459 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
462 // Indication that the lifetime was elided (e.g., in both cases in
463 // `fn foo(x: &u8) -> &'_ u8 { x }`).
466 // Indication that the lifetime name was somehow in error.
470 #[derive(Debug, HashStable_Generic)]
471 pub enum GenericParamKind<'hir> {
472 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
474 kind: LifetimeParamKind,
477 default: Option<&'hir Ty<'hir>>,
482 /// Optional default value for the const generic param
483 default: Option<AnonConst>,
487 #[derive(Debug, HashStable_Generic)]
488 pub struct GenericParam<'hir> {
492 pub pure_wrt_drop: bool,
493 pub kind: GenericParamKind<'hir>,
494 pub colon_span: Option<Span>,
497 impl<'hir> GenericParam<'hir> {
498 /// Synthetic type-parameters are inserted after normal ones.
499 /// In order for normal parameters to be able to refer to synthetic ones,
500 /// scans them first.
501 pub fn is_impl_trait(&self) -> bool {
502 matches!(self.kind, GenericParamKind::Type { synthetic: true, .. })
505 /// This can happen for `async fn`, e.g. `async fn f<'_>(&'_ self)`.
507 /// See `lifetime_to_generic_param` in `rustc_ast_lowering` for more information.
508 pub fn is_elided_lifetime(&self) -> bool {
509 matches!(self.kind, GenericParamKind::Lifetime { kind: LifetimeParamKind::Elided })
514 pub struct GenericParamCount {
515 pub lifetimes: usize,
521 /// Represents lifetimes and type parameters attached to a declaration
522 /// of a function, enum, trait, etc.
523 #[derive(Debug, HashStable_Generic)]
524 pub struct Generics<'hir> {
525 pub params: &'hir [GenericParam<'hir>],
526 pub predicates: &'hir [WherePredicate<'hir>],
527 pub has_where_clause_predicates: bool,
528 pub where_clause_span: Span,
532 impl<'hir> Generics<'hir> {
533 pub const fn empty() -> &'hir Generics<'hir> {
534 const NOPE: Generics<'_> = Generics {
537 has_where_clause_predicates: false,
538 where_clause_span: DUMMY_SP,
544 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'hir>> {
545 for param in self.params {
546 if name == param.name.ident().name {
553 pub fn spans(&self) -> MultiSpan {
554 if self.params.is_empty() {
557 self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
561 /// If there are generic parameters, return where to introduce a new one.
562 pub fn span_for_param_suggestion(&self) -> Option<Span> {
563 if self.params.iter().any(|p| self.span.contains(p.span)) {
564 // `fn foo<A>(t: impl Trait)`
565 // ^ suggest `, T: Trait` here
566 let span = self.span.with_lo(self.span.hi() - BytePos(1)).shrink_to_lo();
573 /// `Span` where further predicates would be suggested, accounting for trailing commas, like
574 /// in `fn foo<T>(t: T) where T: Foo,` so we don't suggest two trailing commas.
575 pub fn tail_span_for_predicate_suggestion(&self) -> Span {
576 let end = self.where_clause_span.shrink_to_hi();
577 if self.has_where_clause_predicates {
580 .rfind(|&p| p.in_where_clause())
581 .map_or(end, |p| p.span())
589 pub fn add_where_or_trailing_comma(&self) -> &'static str {
590 if self.has_where_clause_predicates {
592 } else if self.where_clause_span.is_empty() {
595 // No where clause predicates, but we have `where` token
600 pub fn bounds_for_param(
602 param_def_id: LocalDefId,
603 ) -> impl Iterator<Item = &WhereBoundPredicate<'hir>> {
604 self.predicates.iter().filter_map(move |pred| match pred {
605 WherePredicate::BoundPredicate(bp) if bp.is_param_bound(param_def_id.to_def_id()) => {
612 pub fn outlives_for_param(
614 param_def_id: LocalDefId,
615 ) -> impl Iterator<Item = &WhereRegionPredicate<'_>> {
616 self.predicates.iter().filter_map(move |pred| match pred {
617 WherePredicate::RegionPredicate(rp) if rp.is_param_bound(param_def_id) => Some(rp),
622 pub fn bounds_span_for_suggestions(&self, param_def_id: LocalDefId) -> Option<Span> {
623 self.bounds_for_param(param_def_id).flat_map(|bp| bp.bounds.iter().rev()).find_map(
625 // We include bounds that come from a `#[derive(_)]` but point at the user's code,
626 // as we use this method to get a span appropriate for suggestions.
627 let bs = bound.span();
628 if bs.can_be_used_for_suggestions() { Some(bs.shrink_to_hi()) } else { None }
633 pub fn span_for_predicate_removal(&self, pos: usize) -> Span {
634 let predicate = &self.predicates[pos];
635 let span = predicate.span();
637 if !predicate.in_where_clause() {
643 // We need to find out which comma to remove.
644 if pos < self.predicates.len() - 1 {
645 let next_pred = &self.predicates[pos + 1];
646 if next_pred.in_where_clause() {
647 // where T: ?Sized, Foo: Bar,
649 return span.until(next_pred.span());
654 let prev_pred = &self.predicates[pos - 1];
655 if prev_pred.in_where_clause() {
656 // where Foo: Bar, T: ?Sized,
658 return prev_pred.span().shrink_to_hi().to(span);
662 // This is the only predicate in the where clause.
665 self.where_clause_span
668 pub fn span_for_bound_removal(&self, predicate_pos: usize, bound_pos: usize) -> Span {
669 let predicate = &self.predicates[predicate_pos];
670 let bounds = predicate.bounds();
672 if bounds.len() == 1 {
673 return self.span_for_predicate_removal(predicate_pos);
676 let span = bounds[bound_pos].span();
678 // where T: ?Sized + Bar, Foo: Bar,
680 span.to(bounds[1].span().shrink_to_lo())
682 // where T: Bar + ?Sized, Foo: Bar,
684 bounds[bound_pos - 1].span().shrink_to_hi().to(span)
689 /// A single predicate in a where-clause.
690 #[derive(Debug, HashStable_Generic)]
691 pub enum WherePredicate<'hir> {
692 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
693 BoundPredicate(WhereBoundPredicate<'hir>),
694 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
695 RegionPredicate(WhereRegionPredicate<'hir>),
696 /// An equality predicate (unsupported).
697 EqPredicate(WhereEqPredicate<'hir>),
700 impl<'hir> WherePredicate<'hir> {
701 pub fn span(&self) -> Span {
703 WherePredicate::BoundPredicate(p) => p.span,
704 WherePredicate::RegionPredicate(p) => p.span,
705 WherePredicate::EqPredicate(p) => p.span,
709 pub fn in_where_clause(&self) -> bool {
711 WherePredicate::BoundPredicate(p) => p.origin == PredicateOrigin::WhereClause,
712 WherePredicate::RegionPredicate(p) => p.in_where_clause,
713 WherePredicate::EqPredicate(_) => false,
717 pub fn bounds(&self) -> GenericBounds<'hir> {
719 WherePredicate::BoundPredicate(p) => p.bounds,
720 WherePredicate::RegionPredicate(p) => p.bounds,
721 WherePredicate::EqPredicate(_) => &[],
726 #[derive(Copy, Clone, Debug, HashStable_Generic, PartialEq, Eq)]
727 pub enum PredicateOrigin {
733 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
734 #[derive(Debug, HashStable_Generic)]
735 pub struct WhereBoundPredicate<'hir> {
738 /// Origin of the predicate.
739 pub origin: PredicateOrigin,
740 /// Any generics from a `for` binding.
741 pub bound_generic_params: &'hir [GenericParam<'hir>],
742 /// The type being bounded.
743 pub bounded_ty: &'hir Ty<'hir>,
744 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
745 pub bounds: GenericBounds<'hir>,
748 impl<'hir> WhereBoundPredicate<'hir> {
749 /// Returns `true` if `param_def_id` matches the `bounded_ty` of this predicate.
750 pub fn is_param_bound(&self, param_def_id: DefId) -> bool {
751 self.bounded_ty.as_generic_param().map_or(false, |(def_id, _)| def_id == param_def_id)
755 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
756 #[derive(Debug, HashStable_Generic)]
757 pub struct WhereRegionPredicate<'hir> {
759 pub in_where_clause: bool,
760 pub lifetime: &'hir Lifetime,
761 pub bounds: GenericBounds<'hir>,
764 impl<'hir> WhereRegionPredicate<'hir> {
765 /// Returns `true` if `param_def_id` matches the `lifetime` of this predicate.
766 pub fn is_param_bound(&self, param_def_id: LocalDefId) -> bool {
767 match self.lifetime.name {
768 LifetimeName::Param(id, _) => id == param_def_id,
774 /// An equality predicate (e.g., `T = int`); currently unsupported.
775 #[derive(Debug, HashStable_Generic)]
776 pub struct WhereEqPredicate<'hir> {
778 pub lhs_ty: &'hir Ty<'hir>,
779 pub rhs_ty: &'hir Ty<'hir>,
782 /// HIR node coupled with its parent's id in the same HIR owner.
784 /// The parent is trash when the node is a HIR owner.
785 #[derive(Clone, Debug)]
786 pub struct ParentedNode<'tcx> {
787 pub parent: ItemLocalId,
788 pub node: Node<'tcx>,
791 /// Attributes owned by a HIR owner.
793 pub struct AttributeMap<'tcx> {
794 pub map: SortedMap<ItemLocalId, &'tcx [Attribute]>,
795 pub hash: Fingerprint,
798 impl<'tcx> AttributeMap<'tcx> {
799 pub const EMPTY: &'static AttributeMap<'static> =
800 &AttributeMap { map: SortedMap::new(), hash: Fingerprint::ZERO };
803 pub fn get(&self, id: ItemLocalId) -> &'tcx [Attribute] {
804 self.map.get(&id).copied().unwrap_or(&[])
808 /// Map of all HIR nodes inside the current owner.
809 /// These nodes are mapped by `ItemLocalId` alongside the index of their parent node.
810 /// The HIR tree, including bodies, is pre-hashed.
811 pub struct OwnerNodes<'tcx> {
812 /// Pre-computed hash of the full HIR.
813 pub hash_including_bodies: Fingerprint,
814 /// Pre-computed hash of the item signature, sithout recursing into the body.
815 pub hash_without_bodies: Fingerprint,
816 /// Full HIR for the current owner.
817 // The zeroth node's parent should never be accessed: the owner's parent is computed by the
818 // hir_owner_parent query. It is set to `ItemLocalId::INVALID` to force an ICE if accidentally
820 pub nodes: IndexVec<ItemLocalId, Option<ParentedNode<'tcx>>>,
821 /// Content of local bodies.
822 pub bodies: SortedMap<ItemLocalId, &'tcx Body<'tcx>>,
823 /// Non-owning definitions contained in this owner.
824 pub local_id_to_def_id: SortedMap<ItemLocalId, LocalDefId>,
827 impl<'tcx> OwnerNodes<'tcx> {
828 pub fn node(&self) -> OwnerNode<'tcx> {
829 use rustc_index::vec::Idx;
830 let node = self.nodes[ItemLocalId::new(0)].as_ref().unwrap().node;
831 let node = node.as_owner().unwrap(); // Indexing must ensure it is an OwnerNode.
836 impl fmt::Debug for OwnerNodes<'_> {
837 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
838 f.debug_struct("OwnerNodes")
839 // Do not print all the pointers to all the nodes, as it would be unreadable.
840 .field("node", &self.nodes[ItemLocalId::from_u32(0)])
846 .map(|(id, parented_node)| (id, parented_node.as_ref().map(|node| node.parent)))
847 .collect::<Vec<_>>(),
849 .field("bodies", &self.bodies)
850 .field("local_id_to_def_id", &self.local_id_to_def_id)
851 .field("hash_without_bodies", &self.hash_without_bodies)
852 .field("hash_including_bodies", &self.hash_including_bodies)
857 /// Full information resulting from lowering an AST node.
858 #[derive(Debug, HashStable_Generic)]
859 pub struct OwnerInfo<'hir> {
860 /// Contents of the HIR.
861 pub nodes: OwnerNodes<'hir>,
862 /// Map from each nested owner to its parent's local id.
863 pub parenting: FxHashMap<LocalDefId, ItemLocalId>,
864 /// Collected attributes of the HIR nodes.
865 pub attrs: AttributeMap<'hir>,
866 /// Map indicating what traits are in scope for places where this
867 /// is relevant; generated by resolve.
868 pub trait_map: FxHashMap<ItemLocalId, Box<[TraitCandidate]>>,
871 impl<'tcx> OwnerInfo<'tcx> {
873 pub fn node(&self) -> OwnerNode<'tcx> {
878 #[derive(Copy, Clone, Debug, HashStable_Generic)]
879 pub enum MaybeOwner<T> {
882 /// Used as a placeholder for unused LocalDefId.
886 impl<T> MaybeOwner<T> {
887 pub fn as_owner(self) -> Option<T> {
889 MaybeOwner::Owner(i) => Some(i),
890 MaybeOwner::NonOwner(_) | MaybeOwner::Phantom => None,
894 pub fn map<U>(self, f: impl FnOnce(T) -> U) -> MaybeOwner<U> {
896 MaybeOwner::Owner(i) => MaybeOwner::Owner(f(i)),
897 MaybeOwner::NonOwner(hir_id) => MaybeOwner::NonOwner(hir_id),
898 MaybeOwner::Phantom => MaybeOwner::Phantom,
902 pub fn unwrap(self) -> T {
904 MaybeOwner::Owner(i) => i,
905 MaybeOwner::NonOwner(_) | MaybeOwner::Phantom => panic!("Not a HIR owner"),
910 /// The top-level data structure that stores the entire contents of
911 /// the crate currently being compiled.
913 /// For more details, see the [rustc dev guide].
915 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
917 pub struct Crate<'hir> {
918 pub owners: IndexVec<LocalDefId, MaybeOwner<&'hir OwnerInfo<'hir>>>,
919 pub hir_hash: Fingerprint,
922 #[derive(Debug, HashStable_Generic)]
923 pub struct Closure<'hir> {
924 pub binder: ClosureBinder,
925 pub capture_clause: CaptureBy,
926 pub bound_generic_params: &'hir [GenericParam<'hir>],
927 pub fn_decl: &'hir FnDecl<'hir>,
929 pub fn_decl_span: Span,
930 pub movability: Option<Movability>,
933 /// A block of statements `{ .. }`, which may have a label (in this case the
934 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
935 /// the `rules` being anything but `DefaultBlock`.
936 #[derive(Debug, HashStable_Generic)]
937 pub struct Block<'hir> {
938 /// Statements in a block.
939 pub stmts: &'hir [Stmt<'hir>],
940 /// An expression at the end of the block
941 /// without a semicolon, if any.
942 pub expr: Option<&'hir Expr<'hir>>,
943 #[stable_hasher(ignore)]
945 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
946 pub rules: BlockCheckMode,
948 /// If true, then there may exist `break 'a` values that aim to
949 /// break out of this block early.
950 /// Used by `'label: {}` blocks and by `try {}` blocks.
951 pub targeted_by_break: bool,
954 impl<'hir> Block<'hir> {
955 pub fn innermost_block(&self) -> &Block<'hir> {
956 let mut block = self;
957 while let Some(Expr { kind: ExprKind::Block(inner_block, _), .. }) = block.expr {
964 #[derive(Debug, HashStable_Generic)]
965 pub struct Pat<'hir> {
966 #[stable_hasher(ignore)]
968 pub kind: PatKind<'hir>,
970 // Whether to use default binding modes.
971 // At present, this is false only for destructuring assignment.
972 pub default_binding_modes: bool,
975 impl<'hir> Pat<'hir> {
976 // FIXME(#19596) this is a workaround, but there should be a better way
977 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) -> bool {
984 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
985 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
986 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
987 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
988 Slice(before, slice, after) => {
989 before.iter().chain(slice).chain(after.iter()).all(|p| p.walk_short_(it))
994 /// Walk the pattern in left-to-right order,
995 /// short circuiting (with `.all(..)`) if `false` is returned.
997 /// Note that when visiting e.g. `Tuple(ps)`,
998 /// if visiting `ps[0]` returns `false`,
999 /// then `ps[1]` will not be visited.
1000 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) -> bool {
1001 self.walk_short_(&mut it)
1004 // FIXME(#19596) this is a workaround, but there should be a better way
1005 fn walk_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) {
1012 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
1013 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
1014 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
1015 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
1016 Slice(before, slice, after) => {
1017 before.iter().chain(slice).chain(after.iter()).for_each(|p| p.walk_(it))
1022 /// Walk the pattern in left-to-right order.
1024 /// If `it(pat)` returns `false`, the children are not visited.
1025 pub fn walk(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) {
1029 /// Walk the pattern in left-to-right order.
1031 /// If you always want to recurse, prefer this method over `walk`.
1032 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
1040 /// A single field in a struct pattern.
1042 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
1043 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
1044 /// except `is_shorthand` is true.
1045 #[derive(Debug, HashStable_Generic)]
1046 pub struct PatField<'hir> {
1047 #[stable_hasher(ignore)]
1049 /// The identifier for the field.
1051 /// The pattern the field is destructured to.
1052 pub pat: &'hir Pat<'hir>,
1053 pub is_shorthand: bool,
1057 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1063 impl fmt::Display for RangeEnd {
1064 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1065 f.write_str(match self {
1066 RangeEnd::Included => "..=",
1067 RangeEnd::Excluded => "..",
1072 // Equivalent to `Option<usize>`. That type takes up 16 bytes on 64-bit, but
1073 // this type only takes up 4 bytes, at the cost of being restricted to a
1074 // maximum value of `u32::MAX - 1`. In practice, this is more than enough.
1075 #[derive(Clone, Copy, PartialEq, Eq, Hash, HashStable_Generic)]
1076 pub struct DotDotPos(u32);
1079 // Panics if n >= u32::MAX.
1080 pub fn new(n: Option<usize>) -> Self {
1083 assert!(n < u32::MAX as usize);
1086 None => Self(u32::MAX),
1090 pub fn as_opt_usize(&self) -> Option<usize> {
1091 if self.0 == u32::MAX { None } else { Some(self.0 as usize) }
1095 impl fmt::Debug for DotDotPos {
1096 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1097 self.as_opt_usize().fmt(f)
1101 #[derive(Debug, HashStable_Generic)]
1102 pub enum PatKind<'hir> {
1103 /// Represents a wildcard pattern (i.e., `_`).
1106 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
1107 /// The `HirId` is the canonical ID for the variable being bound,
1108 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
1109 /// which is the pattern ID of the first `x`.
1110 Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
1112 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
1113 /// The `bool` is `true` in the presence of a `..`.
1114 Struct(QPath<'hir>, &'hir [PatField<'hir>], bool),
1116 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
1117 /// If the `..` pattern fragment is present, then `DotDotPos` denotes its position.
1118 /// `0 <= position <= subpats.len()`
1119 TupleStruct(QPath<'hir>, &'hir [Pat<'hir>], DotDotPos),
1121 /// An or-pattern `A | B | C`.
1122 /// Invariant: `pats.len() >= 2`.
1123 Or(&'hir [Pat<'hir>]),
1125 /// A path pattern for a unit struct/variant or a (maybe-associated) constant.
1128 /// A tuple pattern (e.g., `(a, b)`).
1129 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
1130 /// `0 <= position <= subpats.len()`
1131 Tuple(&'hir [Pat<'hir>], DotDotPos),
1133 /// A `box` pattern.
1134 Box(&'hir Pat<'hir>),
1136 /// A reference pattern (e.g., `&mut (a, b)`).
1137 Ref(&'hir Pat<'hir>, Mutability),
1140 Lit(&'hir Expr<'hir>),
1142 /// A range pattern (e.g., `1..=2` or `1..2`).
1143 Range(Option<&'hir Expr<'hir>>, Option<&'hir Expr<'hir>>, RangeEnd),
1145 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
1147 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
1148 /// If `slice` exists, then `after` can be non-empty.
1150 /// The representation for e.g., `[a, b, .., c, d]` is:
1151 /// ```ignore (illustrative)
1152 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
1154 Slice(&'hir [Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [Pat<'hir>]),
1157 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1158 pub enum BinOpKind {
1159 /// The `+` operator (addition).
1161 /// The `-` operator (subtraction).
1163 /// The `*` operator (multiplication).
1165 /// The `/` operator (division).
1167 /// The `%` operator (modulus).
1169 /// The `&&` operator (logical and).
1171 /// The `||` operator (logical or).
1173 /// The `^` operator (bitwise xor).
1175 /// The `&` operator (bitwise and).
1177 /// The `|` operator (bitwise or).
1179 /// The `<<` operator (shift left).
1181 /// The `>>` operator (shift right).
1183 /// The `==` operator (equality).
1185 /// The `<` operator (less than).
1187 /// The `<=` operator (less than or equal to).
1189 /// The `!=` operator (not equal to).
1191 /// The `>=` operator (greater than or equal to).
1193 /// The `>` operator (greater than).
1198 pub fn as_str(self) -> &'static str {
1200 BinOpKind::Add => "+",
1201 BinOpKind::Sub => "-",
1202 BinOpKind::Mul => "*",
1203 BinOpKind::Div => "/",
1204 BinOpKind::Rem => "%",
1205 BinOpKind::And => "&&",
1206 BinOpKind::Or => "||",
1207 BinOpKind::BitXor => "^",
1208 BinOpKind::BitAnd => "&",
1209 BinOpKind::BitOr => "|",
1210 BinOpKind::Shl => "<<",
1211 BinOpKind::Shr => ">>",
1212 BinOpKind::Eq => "==",
1213 BinOpKind::Lt => "<",
1214 BinOpKind::Le => "<=",
1215 BinOpKind::Ne => "!=",
1216 BinOpKind::Ge => ">=",
1217 BinOpKind::Gt => ">",
1221 pub fn is_lazy(self) -> bool {
1222 matches!(self, BinOpKind::And | BinOpKind::Or)
1225 pub fn is_shift(self) -> bool {
1226 matches!(self, BinOpKind::Shl | BinOpKind::Shr)
1229 pub fn is_comparison(self) -> bool {
1236 | BinOpKind::Ge => true,
1248 | BinOpKind::Shr => false,
1252 /// Returns `true` if the binary operator takes its arguments by value.
1253 pub fn is_by_value(self) -> bool {
1254 !self.is_comparison()
1258 impl Into<ast::BinOpKind> for BinOpKind {
1259 fn into(self) -> ast::BinOpKind {
1261 BinOpKind::Add => ast::BinOpKind::Add,
1262 BinOpKind::Sub => ast::BinOpKind::Sub,
1263 BinOpKind::Mul => ast::BinOpKind::Mul,
1264 BinOpKind::Div => ast::BinOpKind::Div,
1265 BinOpKind::Rem => ast::BinOpKind::Rem,
1266 BinOpKind::And => ast::BinOpKind::And,
1267 BinOpKind::Or => ast::BinOpKind::Or,
1268 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1269 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1270 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1271 BinOpKind::Shl => ast::BinOpKind::Shl,
1272 BinOpKind::Shr => ast::BinOpKind::Shr,
1273 BinOpKind::Eq => ast::BinOpKind::Eq,
1274 BinOpKind::Lt => ast::BinOpKind::Lt,
1275 BinOpKind::Le => ast::BinOpKind::Le,
1276 BinOpKind::Ne => ast::BinOpKind::Ne,
1277 BinOpKind::Ge => ast::BinOpKind::Ge,
1278 BinOpKind::Gt => ast::BinOpKind::Gt,
1283 pub type BinOp = Spanned<BinOpKind>;
1285 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1287 /// The `*` operator (dereferencing).
1289 /// The `!` operator (logical negation).
1291 /// The `-` operator (negation).
1296 pub fn as_str(self) -> &'static str {
1304 /// Returns `true` if the unary operator takes its argument by value.
1305 pub fn is_by_value(self) -> bool {
1306 matches!(self, Self::Neg | Self::Not)
1311 #[derive(Debug, HashStable_Generic)]
1312 pub struct Stmt<'hir> {
1314 pub kind: StmtKind<'hir>,
1318 /// The contents of a statement.
1319 #[derive(Debug, HashStable_Generic)]
1320 pub enum StmtKind<'hir> {
1321 /// A local (`let`) binding.
1322 Local(&'hir Local<'hir>),
1324 /// An item binding.
1327 /// An expression without a trailing semi-colon (must have unit type).
1328 Expr(&'hir Expr<'hir>),
1330 /// An expression with a trailing semi-colon (may have any type).
1331 Semi(&'hir Expr<'hir>),
1334 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <init>;`).
1335 #[derive(Debug, HashStable_Generic)]
1336 pub struct Local<'hir> {
1337 pub pat: &'hir Pat<'hir>,
1338 /// Type annotation, if any (otherwise the type will be inferred).
1339 pub ty: Option<&'hir Ty<'hir>>,
1340 /// Initializer expression to set the value, if any.
1341 pub init: Option<&'hir Expr<'hir>>,
1342 /// Else block for a `let...else` binding.
1343 pub els: Option<&'hir Block<'hir>>,
1346 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1347 /// desugaring. Otherwise will be `Normal`.
1348 pub source: LocalSource,
1351 /// Represents a single arm of a `match` expression, e.g.
1352 /// `<pat> (if <guard>) => <body>`.
1353 #[derive(Debug, HashStable_Generic)]
1354 pub struct Arm<'hir> {
1355 #[stable_hasher(ignore)]
1358 /// If this pattern and the optional guard matches, then `body` is evaluated.
1359 pub pat: &'hir Pat<'hir>,
1360 /// Optional guard clause.
1361 pub guard: Option<Guard<'hir>>,
1362 /// The expression the arm evaluates to if this arm matches.
1363 pub body: &'hir Expr<'hir>,
1366 /// Represents a `let <pat>[: <ty>] = <expr>` expression (not a Local), occurring in an `if-let` or
1367 /// `let-else`, evaluating to a boolean. Typically the pattern is refutable.
1369 /// In an if-let, imagine it as `if (let <pat> = <expr>) { ... }`; in a let-else, it is part of the
1370 /// desugaring to if-let. Only let-else supports the type annotation at present.
1371 #[derive(Debug, HashStable_Generic)]
1372 pub struct Let<'hir> {
1375 pub pat: &'hir Pat<'hir>,
1376 pub ty: Option<&'hir Ty<'hir>>,
1377 pub init: &'hir Expr<'hir>,
1380 #[derive(Debug, HashStable_Generic)]
1381 pub enum Guard<'hir> {
1382 If(&'hir Expr<'hir>),
1383 IfLet(&'hir Let<'hir>),
1386 impl<'hir> Guard<'hir> {
1387 /// Returns the body of the guard
1389 /// In other words, returns the e in either of the following:
1392 /// - `if let x = e`
1393 pub fn body(&self) -> &'hir Expr<'hir> {
1395 Guard::If(e) | Guard::IfLet(Let { init: e, .. }) => e,
1400 #[derive(Debug, HashStable_Generic)]
1401 pub struct ExprField<'hir> {
1402 #[stable_hasher(ignore)]
1405 pub expr: &'hir Expr<'hir>,
1407 pub is_shorthand: bool,
1410 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1411 pub enum BlockCheckMode {
1413 UnsafeBlock(UnsafeSource),
1416 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1417 pub enum UnsafeSource {
1422 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
1427 /// The body of a function, closure, or constant value. In the case of
1428 /// a function, the body contains not only the function body itself
1429 /// (which is an expression), but also the argument patterns, since
1430 /// those are something that the caller doesn't really care about.
1435 /// fn foo((x, y): (u32, u32)) -> u32 {
1440 /// Here, the `Body` associated with `foo()` would contain:
1442 /// - an `params` array containing the `(x, y)` pattern
1443 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1444 /// - `generator_kind` would be `None`
1446 /// All bodies have an **owner**, which can be accessed via the HIR
1447 /// map using `body_owner_def_id()`.
1448 #[derive(Debug, HashStable_Generic)]
1449 pub struct Body<'hir> {
1450 pub params: &'hir [Param<'hir>],
1451 pub value: &'hir Expr<'hir>,
1452 pub generator_kind: Option<GeneratorKind>,
1455 impl<'hir> Body<'hir> {
1456 pub fn id(&self) -> BodyId {
1457 BodyId { hir_id: self.value.hir_id }
1460 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1465 /// The type of source expression that caused this generator to be created.
1466 #[derive(Clone, PartialEq, PartialOrd, Eq, Hash, Debug, Copy)]
1467 #[derive(HashStable_Generic, Encodable, Decodable)]
1468 pub enum GeneratorKind {
1469 /// An explicit `async` block or the body of an async function.
1470 Async(AsyncGeneratorKind),
1472 /// A generator literal created via a `yield` inside a closure.
1476 impl fmt::Display for GeneratorKind {
1477 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1479 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1480 GeneratorKind::Gen => f.write_str("generator"),
1485 impl GeneratorKind {
1486 pub fn descr(&self) -> &'static str {
1488 GeneratorKind::Async(ask) => ask.descr(),
1489 GeneratorKind::Gen => "generator",
1494 /// In the case of a generator created as part of an async construct,
1495 /// which kind of async construct caused it to be created?
1497 /// This helps error messages but is also used to drive coercions in
1498 /// type-checking (see #60424).
1499 #[derive(Clone, PartialEq, PartialOrd, Eq, Hash, Debug, Copy)]
1500 #[derive(HashStable_Generic, Encodable, Decodable)]
1501 pub enum AsyncGeneratorKind {
1502 /// An explicit `async` block written by the user.
1505 /// An explicit `async` closure written by the user.
1508 /// The `async` block generated as the body of an async function.
1512 impl fmt::Display for AsyncGeneratorKind {
1513 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1514 f.write_str(match self {
1515 AsyncGeneratorKind::Block => "`async` block",
1516 AsyncGeneratorKind::Closure => "`async` closure body",
1517 AsyncGeneratorKind::Fn => "`async fn` body",
1522 impl AsyncGeneratorKind {
1523 pub fn descr(&self) -> &'static str {
1525 AsyncGeneratorKind::Block => "`async` block",
1526 AsyncGeneratorKind::Closure => "`async` closure body",
1527 AsyncGeneratorKind::Fn => "`async fn` body",
1532 #[derive(Copy, Clone, Debug)]
1533 pub enum BodyOwnerKind {
1534 /// Functions and methods.
1540 /// Constants and associated constants.
1543 /// Initializer of a `static` item.
1547 impl BodyOwnerKind {
1548 pub fn is_fn_or_closure(self) -> bool {
1550 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1551 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1556 /// The kind of an item that requires const-checking.
1557 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1558 pub enum ConstContext {
1562 /// A `static` or `static mut`.
1565 /// A `const`, associated `const`, or other const context.
1567 /// Other contexts include:
1568 /// - Array length expressions
1569 /// - Enum discriminants
1570 /// - Const generics
1572 /// For the most part, other contexts are treated just like a regular `const`, so they are
1573 /// lumped into the same category.
1578 /// A description of this const context that can appear between backticks in an error message.
1580 /// E.g. `const` or `static mut`.
1581 pub fn keyword_name(self) -> &'static str {
1583 Self::Const => "const",
1584 Self::Static(Mutability::Not) => "static",
1585 Self::Static(Mutability::Mut) => "static mut",
1586 Self::ConstFn => "const fn",
1591 /// A colloquial, trivially pluralizable description of this const context for use in error
1593 impl fmt::Display for ConstContext {
1594 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1596 Self::Const => write!(f, "constant"),
1597 Self::Static(_) => write!(f, "static"),
1598 Self::ConstFn => write!(f, "constant function"),
1603 // NOTE: `IntoDiagnosticArg` impl for `ConstContext` lives in `rustc_errors`
1604 // due to a cyclical dependency between hir that crate.
1607 pub type Lit = Spanned<LitKind>;
1609 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1616 pub fn hir_id(&self) -> HirId {
1618 &ArrayLen::Infer(hir_id, _) | &ArrayLen::Body(AnonConst { hir_id, body: _ }) => hir_id,
1623 /// A constant (expression) that's not an item or associated item,
1624 /// but needs its own `DefId` for type-checking, const-eval, etc.
1625 /// These are usually found nested inside types (e.g., array lengths)
1626 /// or expressions (e.g., repeat counts), and also used to define
1627 /// explicit discriminant values for enum variants.
1629 /// You can check if this anon const is a default in a const param
1630 /// `const N: usize = { ... }` with `tcx.hir().opt_const_param_default_param_hir_id(..)`
1631 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1632 pub struct AnonConst {
1638 #[derive(Debug, HashStable_Generic)]
1639 pub struct Expr<'hir> {
1641 pub kind: ExprKind<'hir>,
1646 pub fn precedence(&self) -> ExprPrecedence {
1648 ExprKind::Box(_) => ExprPrecedence::Box,
1649 ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1650 ExprKind::Array(_) => ExprPrecedence::Array,
1651 ExprKind::Call(..) => ExprPrecedence::Call,
1652 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1653 ExprKind::Tup(_) => ExprPrecedence::Tup,
1654 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1655 ExprKind::Unary(..) => ExprPrecedence::Unary,
1656 ExprKind::Lit(_) => ExprPrecedence::Lit,
1657 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1658 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1659 ExprKind::If(..) => ExprPrecedence::If,
1660 ExprKind::Let(..) => ExprPrecedence::Let,
1661 ExprKind::Loop(..) => ExprPrecedence::Loop,
1662 ExprKind::Match(..) => ExprPrecedence::Match,
1663 ExprKind::Closure { .. } => ExprPrecedence::Closure,
1664 ExprKind::Block(..) => ExprPrecedence::Block,
1665 ExprKind::Assign(..) => ExprPrecedence::Assign,
1666 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1667 ExprKind::Field(..) => ExprPrecedence::Field,
1668 ExprKind::Index(..) => ExprPrecedence::Index,
1669 ExprKind::Path(..) => ExprPrecedence::Path,
1670 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1671 ExprKind::Break(..) => ExprPrecedence::Break,
1672 ExprKind::Continue(..) => ExprPrecedence::Continue,
1673 ExprKind::Ret(..) => ExprPrecedence::Ret,
1674 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1675 ExprKind::Struct(..) => ExprPrecedence::Struct,
1676 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1677 ExprKind::Yield(..) => ExprPrecedence::Yield,
1678 ExprKind::Err => ExprPrecedence::Err,
1682 // Whether this looks like a place expr, without checking for deref
1684 // This will return `true` in some potentially surprising cases such as
1685 // `CONSTANT.field`.
1686 pub fn is_syntactic_place_expr(&self) -> bool {
1687 self.is_place_expr(|_| true)
1690 /// Whether this is a place expression.
1692 /// `allow_projections_from` should return `true` if indexing a field or index expression based
1693 /// on the given expression should be considered a place expression.
1694 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1696 ExprKind::Path(QPath::Resolved(_, ref path)) => {
1697 matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static(_), _) | Res::Err)
1700 // Type ascription inherits its place expression kind from its
1702 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1703 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1705 ExprKind::Unary(UnOp::Deref, _) => true,
1707 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1708 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1711 // Lang item paths cannot currently be local variables or statics.
1712 ExprKind::Path(QPath::LangItem(..)) => false,
1714 // Partially qualified paths in expressions can only legally
1715 // refer to associated items which are always rvalues.
1716 ExprKind::Path(QPath::TypeRelative(..))
1717 | ExprKind::Call(..)
1718 | ExprKind::MethodCall(..)
1719 | ExprKind::Struct(..)
1722 | ExprKind::Match(..)
1723 | ExprKind::Closure { .. }
1724 | ExprKind::Block(..)
1725 | ExprKind::Repeat(..)
1726 | ExprKind::Array(..)
1727 | ExprKind::Break(..)
1728 | ExprKind::Continue(..)
1731 | ExprKind::Loop(..)
1732 | ExprKind::Assign(..)
1733 | ExprKind::InlineAsm(..)
1734 | ExprKind::AssignOp(..)
1736 | ExprKind::ConstBlock(..)
1737 | ExprKind::Unary(..)
1739 | ExprKind::AddrOf(..)
1740 | ExprKind::Binary(..)
1741 | ExprKind::Yield(..)
1742 | ExprKind::Cast(..)
1743 | ExprKind::DropTemps(..)
1744 | ExprKind::Err => false,
1748 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1749 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1750 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1751 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1752 /// beyond remembering to call this function before doing analysis on it.
1753 pub fn peel_drop_temps(&self) -> &Self {
1754 let mut expr = self;
1755 while let ExprKind::DropTemps(inner) = &expr.kind {
1761 pub fn peel_blocks(&self) -> &Self {
1762 let mut expr = self;
1763 while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind {
1769 pub fn can_have_side_effects(&self) -> bool {
1770 match self.peel_drop_temps().kind {
1771 ExprKind::Path(_) | ExprKind::Lit(_) => false,
1772 ExprKind::Type(base, _)
1773 | ExprKind::Unary(_, base)
1774 | ExprKind::Field(base, _)
1775 | ExprKind::Index(base, _)
1776 | ExprKind::AddrOf(.., base)
1777 | ExprKind::Cast(base, _) => {
1778 // This isn't exactly true for `Index` and all `Unary`, but we are using this
1779 // method exclusively for diagnostics and there's a *cultural* pressure against
1780 // them being used only for its side-effects.
1781 base.can_have_side_effects()
1783 ExprKind::Struct(_, fields, init) => fields
1785 .map(|field| field.expr)
1786 .chain(init.into_iter())
1787 .all(|e| e.can_have_side_effects()),
1789 ExprKind::Array(args)
1790 | ExprKind::Tup(args)
1794 ExprKind::Path(QPath::Resolved(
1796 Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. },
1801 ) => args.iter().all(|arg| arg.can_have_side_effects()),
1803 | ExprKind::Match(..)
1804 | ExprKind::MethodCall(..)
1805 | ExprKind::Call(..)
1806 | ExprKind::Closure { .. }
1807 | ExprKind::Block(..)
1808 | ExprKind::Repeat(..)
1809 | ExprKind::Break(..)
1810 | ExprKind::Continue(..)
1813 | ExprKind::Loop(..)
1814 | ExprKind::Assign(..)
1815 | ExprKind::InlineAsm(..)
1816 | ExprKind::AssignOp(..)
1817 | ExprKind::ConstBlock(..)
1819 | ExprKind::Binary(..)
1820 | ExprKind::Yield(..)
1821 | ExprKind::DropTemps(..)
1822 | ExprKind::Err => true,
1826 // To a first-order approximation, is this a pattern
1827 pub fn is_approximately_pattern(&self) -> bool {
1830 | ExprKind::Array(_)
1831 | ExprKind::Call(..)
1835 | ExprKind::Struct(..) => true,
1840 pub fn method_ident(&self) -> Option<Ident> {
1842 ExprKind::MethodCall(receiver_method, ..) => Some(receiver_method.ident),
1843 ExprKind::Unary(_, expr) | ExprKind::AddrOf(.., expr) => expr.method_ident(),
1849 /// Checks if the specified expression is a built-in range literal.
1850 /// (See: `LoweringContext::lower_expr()`).
1851 pub fn is_range_literal(expr: &Expr<'_>) -> bool {
1853 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1854 ExprKind::Struct(ref qpath, _, _) => matches!(
1859 | LangItem::RangeFrom
1860 | LangItem::RangeFull
1861 | LangItem::RangeToInclusive,
1866 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1867 ExprKind::Call(ref func, _) => {
1868 matches!(func.kind, ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, ..)))
1875 #[derive(Debug, HashStable_Generic)]
1876 pub enum ExprKind<'hir> {
1877 /// A `box x` expression.
1878 Box(&'hir Expr<'hir>),
1879 /// Allow anonymous constants from an inline `const` block
1880 ConstBlock(AnonConst),
1881 /// An array (e.g., `[a, b, c, d]`).
1882 Array(&'hir [Expr<'hir>]),
1883 /// A function call.
1885 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1886 /// and the second field is the list of arguments.
1887 /// This also represents calling the constructor of
1888 /// tuple-like ADTs such as tuple structs and enum variants.
1889 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1890 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1892 /// The `PathSegment` represents the method name and its generic arguments
1893 /// (within the angle brackets).
1894 /// The `&Expr` is the expression that evaluates
1895 /// to the object on which the method is being called on (the receiver),
1896 /// and the `&[Expr]` is the rest of the arguments.
1897 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1898 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, x, [a, b, c, d], span)`.
1899 /// The final `Span` represents the span of the function and arguments
1900 /// (e.g. `foo::<Bar, Baz>(a, b, c, d)` in `x.foo::<Bar, Baz>(a, b, c, d)`
1902 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1903 /// the `hir_id` of the `MethodCall` node itself.
1905 /// [`type_dependent_def_id`]: ../../rustc_middle/ty/struct.TypeckResults.html#method.type_dependent_def_id
1906 MethodCall(&'hir PathSegment<'hir>, &'hir Expr<'hir>, &'hir [Expr<'hir>], Span),
1907 /// A tuple (e.g., `(a, b, c, d)`).
1908 Tup(&'hir [Expr<'hir>]),
1909 /// A binary operation (e.g., `a + b`, `a * b`).
1910 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1911 /// A unary operation (e.g., `!x`, `*x`).
1912 Unary(UnOp, &'hir Expr<'hir>),
1913 /// A literal (e.g., `1`, `"foo"`).
1915 /// A cast (e.g., `foo as f64`).
1916 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1917 /// A type reference (e.g., `Foo`).
1918 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1919 /// Wraps the expression in a terminating scope.
1920 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1922 /// This construct only exists to tweak the drop order in HIR lowering.
1923 /// An example of that is the desugaring of `for` loops.
1924 DropTemps(&'hir Expr<'hir>),
1925 /// A `let $pat = $expr` expression.
1927 /// These are not `Local` and only occur as expressions.
1928 /// The `let Some(x) = foo()` in `if let Some(x) = foo()` is an example of `Let(..)`.
1929 Let(&'hir Let<'hir>),
1930 /// An `if` block, with an optional else block.
1932 /// I.e., `if <expr> { <expr> } else { <expr> }`.
1933 If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
1934 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1936 /// I.e., `'label: loop { <block> }`.
1938 /// The `Span` is the loop header (`for x in y`/`while let pat = expr`).
1939 Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span),
1940 /// A `match` block, with a source that indicates whether or not it is
1941 /// the result of a desugaring, and if so, which kind.
1942 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1943 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1945 /// The `Span` is the argument block `|...|`.
1947 /// This may also be a generator literal or an `async block` as indicated by the
1948 /// `Option<Movability>`.
1949 Closure(&'hir Closure<'hir>),
1950 /// A block (e.g., `'label: { ... }`).
1951 Block(&'hir Block<'hir>, Option<Label>),
1953 /// An assignment (e.g., `a = foo()`).
1954 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1955 /// An assignment with an operator.
1958 AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1959 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1960 Field(&'hir Expr<'hir>, Ident),
1961 /// An indexing operation (`foo[2]`).
1962 Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1964 /// Path to a definition, possibly containing lifetime or type parameters.
1967 /// A referencing operation (i.e., `&a` or `&mut a`).
1968 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1969 /// A `break`, with an optional label to break.
1970 Break(Destination, Option<&'hir Expr<'hir>>),
1971 /// A `continue`, with an optional label.
1972 Continue(Destination),
1973 /// A `return`, with an optional value to be returned.
1974 Ret(Option<&'hir Expr<'hir>>),
1976 /// Inline assembly (from `asm!`), with its outputs and inputs.
1977 InlineAsm(&'hir InlineAsm<'hir>),
1979 /// A struct or struct-like variant literal expression.
1981 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1982 /// where `base` is the `Option<Expr>`.
1983 Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], Option<&'hir Expr<'hir>>),
1985 /// An array literal constructed from one repeated element.
1987 /// E.g., `[1; 5]`. The first expression is the element
1988 /// to be repeated; the second is the number of times to repeat it.
1989 Repeat(&'hir Expr<'hir>, ArrayLen),
1991 /// A suspension point for generators (i.e., `yield <expr>`).
1992 Yield(&'hir Expr<'hir>, YieldSource),
1994 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1998 /// Represents an optionally `Self`-qualified value/type path or associated extension.
2000 /// To resolve the path to a `DefId`, call [`qpath_res`].
2002 /// [`qpath_res`]: ../../rustc_middle/ty/struct.TypeckResults.html#method.qpath_res
2003 #[derive(Debug, HashStable_Generic)]
2004 pub enum QPath<'hir> {
2005 /// Path to a definition, optionally "fully-qualified" with a `Self`
2006 /// type, if the path points to an associated item in a trait.
2008 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
2009 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
2010 /// even though they both have the same two-segment `Clone::clone` `Path`.
2011 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
2013 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
2014 /// Will be resolved by type-checking to an associated item.
2016 /// UFCS source paths can desugar into this, with `Vec::new` turning into
2017 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
2018 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
2019 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
2021 /// Reference to a `#[lang = "foo"]` item. `HirId` of the inner expr.
2022 LangItem(LangItem, Span, Option<HirId>),
2025 impl<'hir> QPath<'hir> {
2026 /// Returns the span of this `QPath`.
2027 pub fn span(&self) -> Span {
2029 QPath::Resolved(_, path) => path.span,
2030 QPath::TypeRelative(qself, ps) => qself.span.to(ps.ident.span),
2031 QPath::LangItem(_, span, _) => span,
2035 /// Returns the span of the qself of this `QPath`. For example, `()` in
2036 /// `<() as Trait>::method`.
2037 pub fn qself_span(&self) -> Span {
2039 QPath::Resolved(_, path) => path.span,
2040 QPath::TypeRelative(qself, _) => qself.span,
2041 QPath::LangItem(_, span, _) => span,
2045 /// Returns the span of the last segment of this `QPath`. For example, `method` in
2046 /// `<() as Trait>::method`.
2047 pub fn last_segment_span(&self) -> Span {
2049 QPath::Resolved(_, path) => path.segments.last().unwrap().ident.span,
2050 QPath::TypeRelative(_, segment) => segment.ident.span,
2051 QPath::LangItem(_, span, _) => span,
2056 /// Hints at the original code for a let statement.
2057 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2058 pub enum LocalSource {
2059 /// A `match _ { .. }`.
2061 /// When lowering async functions, we create locals within the `async move` so that
2062 /// all parameters are dropped after the future is polled.
2064 /// ```ignore (pseudo-Rust)
2065 /// async fn foo(<pattern> @ x: Type) {
2067 /// let <pattern> = x;
2072 /// A desugared `<expr>.await`.
2074 /// A desugared `expr = expr`, where the LHS is a tuple, struct or array.
2075 /// The span is that of the `=` sign.
2076 AssignDesugar(Span),
2079 /// Hints at the original code for a `match _ { .. }`.
2080 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
2081 #[derive(HashStable_Generic)]
2082 pub enum MatchSource {
2083 /// A `match _ { .. }`.
2085 /// A desugared `for _ in _ { .. }` loop.
2087 /// A desugared `?` operator.
2089 /// A desugared `<expr>.await`.
2095 pub const fn name(self) -> &'static str {
2099 ForLoopDesugar => "for",
2101 AwaitDesugar => ".await",
2106 /// The loop type that yielded an `ExprKind::Loop`.
2107 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2108 pub enum LoopSource {
2109 /// A `loop { .. }` loop.
2111 /// A `while _ { .. }` loop.
2113 /// A `for _ in _ { .. }` loop.
2118 pub fn name(self) -> &'static str {
2120 LoopSource::Loop => "loop",
2121 LoopSource::While => "while",
2122 LoopSource::ForLoop => "for",
2127 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2128 pub enum LoopIdError {
2130 UnlabeledCfInWhileCondition,
2134 impl fmt::Display for LoopIdError {
2135 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2136 f.write_str(match self {
2137 LoopIdError::OutsideLoopScope => "not inside loop scope",
2138 LoopIdError::UnlabeledCfInWhileCondition => {
2139 "unlabeled control flow (break or continue) in while condition"
2141 LoopIdError::UnresolvedLabel => "label not found",
2146 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2147 pub struct Destination {
2148 // This is `Some(_)` iff there is an explicit user-specified `label
2149 pub label: Option<Label>,
2151 // These errors are caught and then reported during the diagnostics pass in
2152 // librustc_passes/loops.rs
2153 pub target_id: Result<HirId, LoopIdError>,
2156 /// The yield kind that caused an `ExprKind::Yield`.
2157 #[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
2158 pub enum YieldSource {
2159 /// An `<expr>.await`.
2160 Await { expr: Option<HirId> },
2161 /// A plain `yield`.
2166 pub fn is_await(&self) -> bool {
2167 matches!(self, YieldSource::Await { .. })
2171 impl fmt::Display for YieldSource {
2172 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2173 f.write_str(match self {
2174 YieldSource::Await { .. } => "`await`",
2175 YieldSource::Yield => "`yield`",
2180 impl From<GeneratorKind> for YieldSource {
2181 fn from(kind: GeneratorKind) -> Self {
2183 // Guess based on the kind of the current generator.
2184 GeneratorKind::Gen => Self::Yield,
2185 GeneratorKind::Async(_) => Self::Await { expr: None },
2190 // N.B., if you change this, you'll probably want to change the corresponding
2191 // type structure in middle/ty.rs as well.
2192 #[derive(Debug, HashStable_Generic)]
2193 pub struct MutTy<'hir> {
2194 pub ty: &'hir Ty<'hir>,
2195 pub mutbl: Mutability,
2198 /// Represents a function's signature in a trait declaration,
2199 /// trait implementation, or a free function.
2200 #[derive(Debug, HashStable_Generic)]
2201 pub struct FnSig<'hir> {
2202 pub header: FnHeader,
2203 pub decl: &'hir FnDecl<'hir>,
2207 // The bodies for items are stored "out of line", in a separate
2208 // hashmap in the `Crate`. Here we just record the hir-id of the item
2209 // so it can fetched later.
2210 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2211 pub struct TraitItemId {
2212 pub owner_id: OwnerId,
2217 pub fn hir_id(&self) -> HirId {
2218 // Items are always HIR owners.
2219 HirId::make_owner(self.owner_id.def_id)
2223 /// Represents an item declaration within a trait declaration,
2224 /// possibly including a default implementation. A trait item is
2225 /// either required (meaning it doesn't have an implementation, just a
2226 /// signature) or provided (meaning it has a default implementation).
2227 #[derive(Debug, HashStable_Generic)]
2228 pub struct TraitItem<'hir> {
2230 pub owner_id: OwnerId,
2231 pub generics: &'hir Generics<'hir>,
2232 pub kind: TraitItemKind<'hir>,
2234 pub defaultness: Defaultness,
2237 impl TraitItem<'_> {
2239 pub fn hir_id(&self) -> HirId {
2240 // Items are always HIR owners.
2241 HirId::make_owner(self.owner_id.def_id)
2244 pub fn trait_item_id(&self) -> TraitItemId {
2245 TraitItemId { owner_id: self.owner_id }
2249 /// Represents a trait method's body (or just argument names).
2250 #[derive(Encodable, Debug, HashStable_Generic)]
2251 pub enum TraitFn<'hir> {
2252 /// No default body in the trait, just a signature.
2253 Required(&'hir [Ident]),
2255 /// Both signature and body are provided in the trait.
2259 /// Represents a trait method or associated constant or type
2260 #[derive(Debug, HashStable_Generic)]
2261 pub enum TraitItemKind<'hir> {
2262 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
2263 Const(&'hir Ty<'hir>, Option<BodyId>),
2264 /// An associated function with an optional body.
2265 Fn(FnSig<'hir>, TraitFn<'hir>),
2266 /// An associated type with (possibly empty) bounds and optional concrete
2268 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
2271 // The bodies for items are stored "out of line", in a separate
2272 // hashmap in the `Crate`. Here we just record the hir-id of the item
2273 // so it can fetched later.
2274 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2275 pub struct ImplItemId {
2276 pub owner_id: OwnerId,
2281 pub fn hir_id(&self) -> HirId {
2282 // Items are always HIR owners.
2283 HirId::make_owner(self.owner_id.def_id)
2287 /// Represents anything within an `impl` block.
2288 #[derive(Debug, HashStable_Generic)]
2289 pub struct ImplItem<'hir> {
2291 pub owner_id: OwnerId,
2292 pub generics: &'hir Generics<'hir>,
2293 pub kind: ImplItemKind<'hir>,
2294 pub defaultness: Defaultness,
2301 pub fn hir_id(&self) -> HirId {
2302 // Items are always HIR owners.
2303 HirId::make_owner(self.owner_id.def_id)
2306 pub fn impl_item_id(&self) -> ImplItemId {
2307 ImplItemId { owner_id: self.owner_id }
2311 /// Represents various kinds of content within an `impl`.
2312 #[derive(Debug, HashStable_Generic)]
2313 pub enum ImplItemKind<'hir> {
2314 /// An associated constant of the given type, set to the constant result
2315 /// of the expression.
2316 Const(&'hir Ty<'hir>, BodyId),
2317 /// An associated function implementation with the given signature and body.
2318 Fn(FnSig<'hir>, BodyId),
2319 /// An associated type.
2320 Type(&'hir Ty<'hir>),
2323 // The name of the associated type for `Fn` return types.
2324 pub const FN_OUTPUT_NAME: Symbol = sym::Output;
2326 /// Bind a type to an associated type (i.e., `A = Foo`).
2328 /// Bindings like `A: Debug` are represented as a special type `A =
2329 /// $::Debug` that is understood by the astconv code.
2331 /// FIXME(alexreg): why have a separate type for the binding case,
2332 /// wouldn't it be better to make the `ty` field an enum like the
2335 /// ```ignore (pseudo-rust)
2336 /// enum TypeBindingKind {
2341 #[derive(Debug, HashStable_Generic)]
2342 pub struct TypeBinding<'hir> {
2345 pub gen_args: &'hir GenericArgs<'hir>,
2346 pub kind: TypeBindingKind<'hir>,
2350 #[derive(Debug, HashStable_Generic)]
2351 pub enum Term<'hir> {
2356 impl<'hir> From<&'hir Ty<'hir>> for Term<'hir> {
2357 fn from(ty: &'hir Ty<'hir>) -> Self {
2362 impl<'hir> From<AnonConst> for Term<'hir> {
2363 fn from(c: AnonConst) -> Self {
2368 // Represents the two kinds of type bindings.
2369 #[derive(Debug, HashStable_Generic)]
2370 pub enum TypeBindingKind<'hir> {
2371 /// E.g., `Foo<Bar: Send>`.
2372 Constraint { bounds: &'hir [GenericBound<'hir>] },
2373 /// E.g., `Foo<Bar = ()>`, `Foo<Bar = ()>`
2374 Equality { term: Term<'hir> },
2377 impl TypeBinding<'_> {
2378 pub fn ty(&self) -> &Ty<'_> {
2380 TypeBindingKind::Equality { term: Term::Ty(ref ty) } => ty,
2381 _ => panic!("expected equality type binding for parenthesized generic args"),
2384 pub fn opt_const(&self) -> Option<&'_ AnonConst> {
2386 TypeBindingKind::Equality { term: Term::Const(ref c) } => Some(c),
2392 #[derive(Debug, HashStable_Generic)]
2393 pub struct Ty<'hir> {
2395 pub kind: TyKind<'hir>,
2399 impl<'hir> Ty<'hir> {
2400 /// Returns `true` if `param_def_id` matches the `bounded_ty` of this predicate.
2401 pub fn as_generic_param(&self) -> Option<(DefId, Ident)> {
2402 let TyKind::Path(QPath::Resolved(None, path)) = self.kind else {
2405 let [segment] = &path.segments else {
2409 Res::Def(DefKind::TyParam, def_id) | Res::SelfTyParam { trait_: def_id } => {
2410 Some((def_id, segment.ident))
2416 pub fn peel_refs(&self) -> &Self {
2417 let mut final_ty = self;
2418 while let TyKind::Rptr(_, MutTy { ty, .. }) = &final_ty.kind {
2424 pub fn find_self_aliases(&self) -> Vec<Span> {
2425 use crate::intravisit::Visitor;
2426 struct MyVisitor(Vec<Span>);
2427 impl<'v> Visitor<'v> for MyVisitor {
2428 fn visit_ty(&mut self, t: &'v Ty<'v>) {
2431 TyKind::Path(QPath::Resolved(
2433 Path { res: crate::def::Res::SelfTyAlias { .. }, .. },
2436 self.0.push(t.span);
2439 crate::intravisit::walk_ty(self, t);
2443 let mut my_visitor = MyVisitor(vec![]);
2444 my_visitor.visit_ty(self);
2449 /// Not represented directly in the AST; referred to by name through a `ty_path`.
2450 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
2451 #[derive(HashStable_Generic)]
2462 /// All of the primitive types
2463 pub const ALL: [Self; 17] = [
2464 // any changes here should also be reflected in `PrimTy::from_name`
2465 Self::Int(IntTy::I8),
2466 Self::Int(IntTy::I16),
2467 Self::Int(IntTy::I32),
2468 Self::Int(IntTy::I64),
2469 Self::Int(IntTy::I128),
2470 Self::Int(IntTy::Isize),
2471 Self::Uint(UintTy::U8),
2472 Self::Uint(UintTy::U16),
2473 Self::Uint(UintTy::U32),
2474 Self::Uint(UintTy::U64),
2475 Self::Uint(UintTy::U128),
2476 Self::Uint(UintTy::Usize),
2477 Self::Float(FloatTy::F32),
2478 Self::Float(FloatTy::F64),
2484 /// Like [`PrimTy::name`], but returns a &str instead of a symbol.
2487 pub fn name_str(self) -> &'static str {
2489 PrimTy::Int(i) => i.name_str(),
2490 PrimTy::Uint(u) => u.name_str(),
2491 PrimTy::Float(f) => f.name_str(),
2492 PrimTy::Str => "str",
2493 PrimTy::Bool => "bool",
2494 PrimTy::Char => "char",
2498 pub fn name(self) -> Symbol {
2500 PrimTy::Int(i) => i.name(),
2501 PrimTy::Uint(u) => u.name(),
2502 PrimTy::Float(f) => f.name(),
2503 PrimTy::Str => sym::str,
2504 PrimTy::Bool => sym::bool,
2505 PrimTy::Char => sym::char,
2509 /// Returns the matching `PrimTy` for a `Symbol` such as "str" or "i32".
2510 /// Returns `None` if no matching type is found.
2511 pub fn from_name(name: Symbol) -> Option<Self> {
2512 let ty = match name {
2513 // any changes here should also be reflected in `PrimTy::ALL`
2514 sym::i8 => Self::Int(IntTy::I8),
2515 sym::i16 => Self::Int(IntTy::I16),
2516 sym::i32 => Self::Int(IntTy::I32),
2517 sym::i64 => Self::Int(IntTy::I64),
2518 sym::i128 => Self::Int(IntTy::I128),
2519 sym::isize => Self::Int(IntTy::Isize),
2520 sym::u8 => Self::Uint(UintTy::U8),
2521 sym::u16 => Self::Uint(UintTy::U16),
2522 sym::u32 => Self::Uint(UintTy::U32),
2523 sym::u64 => Self::Uint(UintTy::U64),
2524 sym::u128 => Self::Uint(UintTy::U128),
2525 sym::usize => Self::Uint(UintTy::Usize),
2526 sym::f32 => Self::Float(FloatTy::F32),
2527 sym::f64 => Self::Float(FloatTy::F64),
2528 sym::bool => Self::Bool,
2529 sym::char => Self::Char,
2530 sym::str => Self::Str,
2537 #[derive(Debug, HashStable_Generic)]
2538 pub struct BareFnTy<'hir> {
2539 pub unsafety: Unsafety,
2541 pub generic_params: &'hir [GenericParam<'hir>],
2542 pub decl: &'hir FnDecl<'hir>,
2543 pub param_names: &'hir [Ident],
2546 #[derive(Debug, HashStable_Generic)]
2547 pub struct OpaqueTy<'hir> {
2548 pub generics: &'hir Generics<'hir>,
2549 pub bounds: GenericBounds<'hir>,
2550 pub origin: OpaqueTyOrigin,
2554 /// From whence the opaque type came.
2555 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2556 pub enum OpaqueTyOrigin {
2558 FnReturn(LocalDefId),
2560 AsyncFn(LocalDefId),
2561 /// type aliases: `type Foo = impl Trait;`
2565 /// The various kinds of types recognized by the compiler.
2566 #[derive(Debug, HashStable_Generic)]
2567 pub enum TyKind<'hir> {
2568 /// A variable length slice (i.e., `[T]`).
2569 Slice(&'hir Ty<'hir>),
2570 /// A fixed length array (i.e., `[T; n]`).
2571 Array(&'hir Ty<'hir>, ArrayLen),
2572 /// A raw pointer (i.e., `*const T` or `*mut T`).
2574 /// A reference (i.e., `&'a T` or `&'a mut T`).
2575 Rptr(&'hir Lifetime, MutTy<'hir>),
2576 /// A bare function (e.g., `fn(usize) -> bool`).
2577 BareFn(&'hir BareFnTy<'hir>),
2578 /// The never type (`!`).
2580 /// A tuple (`(A, B, C, D, ...)`).
2581 Tup(&'hir [Ty<'hir>]),
2582 /// A path to a type definition (`module::module::...::Type`), or an
2583 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2585 /// Type parameters may be stored in each `PathSegment`.
2587 /// An opaque type definition itself. This is only used for `impl Trait`.
2589 /// The generic argument list contains the lifetimes (and in the future
2590 /// possibly parameters) that are actually bound on the `impl Trait`.
2592 /// The last parameter specifies whether this opaque appears in a trait definition.
2593 OpaqueDef(ItemId, &'hir [GenericArg<'hir>], bool),
2594 /// A trait object type `Bound1 + Bound2 + Bound3`
2595 /// where `Bound` is a trait or a lifetime.
2596 TraitObject(&'hir [PolyTraitRef<'hir>], &'hir Lifetime, TraitObjectSyntax),
2599 /// `TyKind::Infer` means the type should be inferred instead of it having been
2600 /// specified. This can appear anywhere in a type.
2602 /// Placeholder for a type that has failed to be defined.
2606 #[derive(Debug, HashStable_Generic)]
2607 pub enum InlineAsmOperand<'hir> {
2609 reg: InlineAsmRegOrRegClass,
2610 expr: &'hir Expr<'hir>,
2613 reg: InlineAsmRegOrRegClass,
2615 expr: Option<&'hir Expr<'hir>>,
2618 reg: InlineAsmRegOrRegClass,
2620 expr: &'hir Expr<'hir>,
2623 reg: InlineAsmRegOrRegClass,
2625 in_expr: &'hir Expr<'hir>,
2626 out_expr: Option<&'hir Expr<'hir>>,
2629 anon_const: AnonConst,
2632 anon_const: AnonConst,
2640 impl<'hir> InlineAsmOperand<'hir> {
2641 pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
2643 Self::In { reg, .. }
2644 | Self::Out { reg, .. }
2645 | Self::InOut { reg, .. }
2646 | Self::SplitInOut { reg, .. } => Some(reg),
2647 Self::Const { .. } | Self::SymFn { .. } | Self::SymStatic { .. } => None,
2651 pub fn is_clobber(&self) -> bool {
2654 InlineAsmOperand::Out { reg: InlineAsmRegOrRegClass::Reg(_), late: _, expr: None }
2659 #[derive(Debug, HashStable_Generic)]
2660 pub struct InlineAsm<'hir> {
2661 pub template: &'hir [InlineAsmTemplatePiece],
2662 pub template_strs: &'hir [(Symbol, Option<Symbol>, Span)],
2663 pub operands: &'hir [(InlineAsmOperand<'hir>, Span)],
2664 pub options: InlineAsmOptions,
2665 pub line_spans: &'hir [Span],
2668 /// Represents a parameter in a function header.
2669 #[derive(Debug, HashStable_Generic)]
2670 pub struct Param<'hir> {
2672 pub pat: &'hir Pat<'hir>,
2677 /// Represents the header (not the body) of a function declaration.
2678 #[derive(Debug, HashStable_Generic)]
2679 pub struct FnDecl<'hir> {
2680 /// The types of the function's parameters.
2682 /// Additional argument data is stored in the function's [body](Body::params).
2683 pub inputs: &'hir [Ty<'hir>],
2684 pub output: FnRetTy<'hir>,
2685 pub c_variadic: bool,
2686 /// Does the function have an implicit self?
2687 pub implicit_self: ImplicitSelfKind,
2690 /// Represents what type of implicit self a function has, if any.
2691 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2692 pub enum ImplicitSelfKind {
2693 /// Represents a `fn x(self);`.
2695 /// Represents a `fn x(mut self);`.
2697 /// Represents a `fn x(&self);`.
2699 /// Represents a `fn x(&mut self);`.
2701 /// Represents when a function does not have a self argument or
2702 /// when a function has a `self: X` argument.
2706 impl ImplicitSelfKind {
2707 /// Does this represent an implicit self?
2708 pub fn has_implicit_self(&self) -> bool {
2709 !matches!(*self, ImplicitSelfKind::None)
2713 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable, Debug)]
2714 #[derive(HashStable_Generic)]
2720 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable, HashStable_Generic)]
2721 pub enum Defaultness {
2722 Default { has_value: bool },
2727 pub fn has_value(&self) -> bool {
2729 Defaultness::Default { has_value } => has_value,
2730 Defaultness::Final => true,
2734 pub fn is_final(&self) -> bool {
2735 *self == Defaultness::Final
2738 pub fn is_default(&self) -> bool {
2739 matches!(*self, Defaultness::Default { .. })
2743 #[derive(Debug, HashStable_Generic)]
2744 pub enum FnRetTy<'hir> {
2745 /// Return type is not specified.
2747 /// Functions default to `()` and
2748 /// closures default to inference. Span points to where return
2749 /// type would be inserted.
2750 DefaultReturn(Span),
2751 /// Everything else.
2752 Return(&'hir Ty<'hir>),
2757 pub fn span(&self) -> Span {
2759 Self::DefaultReturn(span) => span,
2760 Self::Return(ref ty) => ty.span,
2765 /// Represents `for<...>` binder before a closure
2766 #[derive(Copy, Clone, Debug, HashStable_Generic)]
2767 pub enum ClosureBinder {
2768 /// Binder is not specified.
2770 /// Binder is specified.
2772 /// Span points to the whole `for<...>`.
2776 #[derive(Encodable, Debug, HashStable_Generic)]
2777 pub struct Mod<'hir> {
2778 pub spans: ModSpans,
2779 pub item_ids: &'hir [ItemId],
2782 #[derive(Copy, Clone, Debug, HashStable_Generic, Encodable)]
2783 pub struct ModSpans {
2784 /// A span from the first token past `{` to the last token until `}`.
2785 /// For `mod foo;`, the inner span ranges from the first token
2786 /// to the last token in the external file.
2787 pub inner_span: Span,
2788 pub inject_use_span: Span,
2791 #[derive(Debug, HashStable_Generic)]
2792 pub struct EnumDef<'hir> {
2793 pub variants: &'hir [Variant<'hir>],
2796 #[derive(Debug, HashStable_Generic)]
2797 pub struct Variant<'hir> {
2798 /// Name of the variant.
2800 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2802 /// Fields and constructor id of the variant.
2803 pub data: VariantData<'hir>,
2804 /// Explicit discriminant (e.g., `Foo = 1`).
2805 pub disr_expr: Option<AnonConst>,
2810 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2812 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2813 /// Also produced for each element of a list `use`, e.g.
2814 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2817 /// Glob import, e.g., `use foo::*`.
2820 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2821 /// an additional `use foo::{}` for performing checks such as
2822 /// unstable feature gating. May be removed in the future.
2826 /// References to traits in impls.
2828 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2829 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2830 /// trait being referred to but just a unique `HirId` that serves as a key
2831 /// within the resolution map.
2832 #[derive(Clone, Debug, HashStable_Generic)]
2833 pub struct TraitRef<'hir> {
2834 pub path: &'hir Path<'hir>,
2835 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2836 #[stable_hasher(ignore)]
2837 pub hir_ref_id: HirId,
2841 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2842 pub fn trait_def_id(&self) -> Option<DefId> {
2843 match self.path.res {
2844 Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
2846 _ => unreachable!(),
2851 #[derive(Clone, Debug, HashStable_Generic)]
2852 pub struct PolyTraitRef<'hir> {
2853 /// The `'a` in `for<'a> Foo<&'a T>`.
2854 pub bound_generic_params: &'hir [GenericParam<'hir>],
2856 /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
2857 pub trait_ref: TraitRef<'hir>,
2862 #[derive(Debug, HashStable_Generic)]
2863 pub struct FieldDef<'hir> {
2868 pub ty: &'hir Ty<'hir>,
2872 // Still necessary in couple of places
2873 pub fn is_positional(&self) -> bool {
2874 let first = self.ident.as_str().as_bytes()[0];
2875 (b'0'..=b'9').contains(&first)
2879 /// Fields and constructor IDs of enum variants and structs.
2880 #[derive(Debug, HashStable_Generic)]
2881 pub enum VariantData<'hir> {
2882 /// A struct variant.
2884 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2885 Struct(&'hir [FieldDef<'hir>], /* recovered */ bool),
2886 /// A tuple variant.
2888 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2889 Tuple(&'hir [FieldDef<'hir>], HirId),
2892 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2896 impl<'hir> VariantData<'hir> {
2897 /// Return the fields of this variant.
2898 pub fn fields(&self) -> &'hir [FieldDef<'hir>] {
2900 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2905 /// Return the `HirId` of this variant's constructor, if it has one.
2906 pub fn ctor_hir_id(&self) -> Option<HirId> {
2908 VariantData::Struct(_, _) => None,
2909 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2914 // The bodies for items are stored "out of line", in a separate
2915 // hashmap in the `Crate`. Here we just record the hir-id of the item
2916 // so it can fetched later.
2917 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
2919 pub owner_id: OwnerId,
2924 pub fn hir_id(&self) -> HirId {
2925 // Items are always HIR owners.
2926 HirId::make_owner(self.owner_id.def_id)
2932 /// The name might be a dummy name in case of anonymous items
2933 #[derive(Debug, HashStable_Generic)]
2934 pub struct Item<'hir> {
2936 pub owner_id: OwnerId,
2937 pub kind: ItemKind<'hir>,
2944 pub fn hir_id(&self) -> HirId {
2945 // Items are always HIR owners.
2946 HirId::make_owner(self.owner_id.def_id)
2949 pub fn item_id(&self) -> ItemId {
2950 ItemId { owner_id: self.owner_id }
2954 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2955 #[derive(Encodable, Decodable, HashStable_Generic)]
2962 pub fn prefix_str(&self) -> &'static str {
2964 Self::Unsafe => "unsafe ",
2970 impl fmt::Display for Unsafety {
2971 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2972 f.write_str(match *self {
2973 Self::Unsafe => "unsafe",
2974 Self::Normal => "normal",
2979 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2980 #[derive(Encodable, Decodable, HashStable_Generic)]
2981 pub enum Constness {
2986 impl fmt::Display for Constness {
2987 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2988 f.write_str(match *self {
2989 Self::Const => "const",
2990 Self::NotConst => "non-const",
2995 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2996 pub struct FnHeader {
2997 pub unsafety: Unsafety,
2998 pub constness: Constness,
2999 pub asyncness: IsAsync,
3004 pub fn is_async(&self) -> bool {
3005 matches!(&self.asyncness, IsAsync::Async)
3008 pub fn is_const(&self) -> bool {
3009 matches!(&self.constness, Constness::Const)
3012 pub fn is_unsafe(&self) -> bool {
3013 matches!(&self.unsafety, Unsafety::Unsafe)
3017 #[derive(Debug, HashStable_Generic)]
3018 pub enum ItemKind<'hir> {
3019 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
3021 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
3022 ExternCrate(Option<Symbol>),
3024 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
3028 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
3029 Use(&'hir Path<'hir>, UseKind),
3031 /// A `static` item.
3032 Static(&'hir Ty<'hir>, Mutability, BodyId),
3034 Const(&'hir Ty<'hir>, BodyId),
3035 /// A function declaration.
3036 Fn(FnSig<'hir>, &'hir Generics<'hir>, BodyId),
3037 /// A MBE macro definition (`macro_rules!` or `macro`).
3038 Macro(ast::MacroDef, MacroKind),
3040 Mod(&'hir Mod<'hir>),
3041 /// An external module, e.g. `extern { .. }`.
3042 ForeignMod { abi: Abi, items: &'hir [ForeignItemRef] },
3043 /// Module-level inline assembly (from `global_asm!`).
3044 GlobalAsm(&'hir InlineAsm<'hir>),
3045 /// A type alias, e.g., `type Foo = Bar<u8>`.
3046 TyAlias(&'hir Ty<'hir>, &'hir Generics<'hir>),
3047 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
3048 OpaqueTy(OpaqueTy<'hir>),
3049 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
3050 Enum(EnumDef<'hir>, &'hir Generics<'hir>),
3051 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
3052 Struct(VariantData<'hir>, &'hir Generics<'hir>),
3053 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
3054 Union(VariantData<'hir>, &'hir Generics<'hir>),
3055 /// A trait definition.
3056 Trait(IsAuto, Unsafety, &'hir Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
3058 TraitAlias(&'hir Generics<'hir>, GenericBounds<'hir>),
3060 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
3061 Impl(&'hir Impl<'hir>),
3064 #[derive(Debug, HashStable_Generic)]
3065 pub struct Impl<'hir> {
3066 pub unsafety: Unsafety,
3067 pub polarity: ImplPolarity,
3068 pub defaultness: Defaultness,
3069 // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata
3070 // decoding as `Span`s cannot be decoded when a `Session` is not available.
3071 pub defaultness_span: Option<Span>,
3072 pub constness: Constness,
3073 pub generics: &'hir Generics<'hir>,
3075 /// The trait being implemented, if any.
3076 pub of_trait: Option<TraitRef<'hir>>,
3078 pub self_ty: &'hir Ty<'hir>,
3079 pub items: &'hir [ImplItemRef],
3083 pub fn generics(&self) -> Option<&Generics<'_>> {
3085 ItemKind::Fn(_, ref generics, _)
3086 | ItemKind::TyAlias(_, ref generics)
3087 | ItemKind::OpaqueTy(OpaqueTy { ref generics, .. })
3088 | ItemKind::Enum(_, ref generics)
3089 | ItemKind::Struct(_, ref generics)
3090 | ItemKind::Union(_, ref generics)
3091 | ItemKind::Trait(_, _, ref generics, _, _)
3092 | ItemKind::TraitAlias(ref generics, _)
3093 | ItemKind::Impl(Impl { ref generics, .. }) => generics,
3098 pub fn descr(&self) -> &'static str {
3100 ItemKind::ExternCrate(..) => "extern crate",
3101 ItemKind::Use(..) => "`use` import",
3102 ItemKind::Static(..) => "static item",
3103 ItemKind::Const(..) => "constant item",
3104 ItemKind::Fn(..) => "function",
3105 ItemKind::Macro(..) => "macro",
3106 ItemKind::Mod(..) => "module",
3107 ItemKind::ForeignMod { .. } => "extern block",
3108 ItemKind::GlobalAsm(..) => "global asm item",
3109 ItemKind::TyAlias(..) => "type alias",
3110 ItemKind::OpaqueTy(..) => "opaque type",
3111 ItemKind::Enum(..) => "enum",
3112 ItemKind::Struct(..) => "struct",
3113 ItemKind::Union(..) => "union",
3114 ItemKind::Trait(..) => "trait",
3115 ItemKind::TraitAlias(..) => "trait alias",
3116 ItemKind::Impl(..) => "implementation",
3121 /// A reference from an trait to one of its associated items. This
3122 /// contains the item's id, naturally, but also the item's name and
3123 /// some other high-level details (like whether it is an associated
3124 /// type or method, and whether it is public). This allows other
3125 /// passes to find the impl they want without loading the ID (which
3126 /// means fewer edges in the incremental compilation graph).
3127 #[derive(Encodable, Debug, HashStable_Generic)]
3128 pub struct TraitItemRef {
3129 pub id: TraitItemId,
3131 pub kind: AssocItemKind,
3135 /// A reference from an impl to one of its associated items. This
3136 /// contains the item's ID, naturally, but also the item's name and
3137 /// some other high-level details (like whether it is an associated
3138 /// type or method, and whether it is public). This allows other
3139 /// passes to find the impl they want without loading the ID (which
3140 /// means fewer edges in the incremental compilation graph).
3141 #[derive(Debug, HashStable_Generic)]
3142 pub struct ImplItemRef {
3145 pub kind: AssocItemKind,
3147 /// When we are in a trait impl, link to the trait-item's id.
3148 pub trait_item_def_id: Option<DefId>,
3151 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
3152 pub enum AssocItemKind {
3154 Fn { has_self: bool },
3158 // The bodies for items are stored "out of line", in a separate
3159 // hashmap in the `Crate`. Here we just record the hir-id of the item
3160 // so it can fetched later.
3161 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3162 pub struct ForeignItemId {
3163 pub owner_id: OwnerId,
3166 impl ForeignItemId {
3168 pub fn hir_id(&self) -> HirId {
3169 // Items are always HIR owners.
3170 HirId::make_owner(self.owner_id.def_id)
3174 /// A reference from a foreign block to one of its items. This
3175 /// contains the item's ID, naturally, but also the item's name and
3176 /// some other high-level details (like whether it is an associated
3177 /// type or method, and whether it is public). This allows other
3178 /// passes to find the impl they want without loading the ID (which
3179 /// means fewer edges in the incremental compilation graph).
3180 #[derive(Debug, HashStable_Generic)]
3181 pub struct ForeignItemRef {
3182 pub id: ForeignItemId,
3187 #[derive(Debug, HashStable_Generic)]
3188 pub struct ForeignItem<'hir> {
3190 pub kind: ForeignItemKind<'hir>,
3191 pub owner_id: OwnerId,
3196 impl ForeignItem<'_> {
3198 pub fn hir_id(&self) -> HirId {
3199 // Items are always HIR owners.
3200 HirId::make_owner(self.owner_id.def_id)
3203 pub fn foreign_item_id(&self) -> ForeignItemId {
3204 ForeignItemId { owner_id: self.owner_id }
3208 /// An item within an `extern` block.
3209 #[derive(Debug, HashStable_Generic)]
3210 pub enum ForeignItemKind<'hir> {
3211 /// A foreign function.
3212 Fn(&'hir FnDecl<'hir>, &'hir [Ident], &'hir Generics<'hir>),
3213 /// A foreign static item (`static ext: u8`).
3214 Static(&'hir Ty<'hir>, Mutability),
3219 /// A variable captured by a closure.
3220 #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)]
3222 // First span where it is accessed (there can be multiple).
3226 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
3227 // has length > 0 if the trait is found through an chain of imports, starting with the
3228 // import/use statement in the scope where the trait is used.
3229 #[derive(Encodable, Decodable, Clone, Debug, HashStable_Generic)]
3230 pub struct TraitCandidate {
3232 pub import_ids: SmallVec<[LocalDefId; 1]>,
3235 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3236 pub enum OwnerNode<'hir> {
3237 Item(&'hir Item<'hir>),
3238 ForeignItem(&'hir ForeignItem<'hir>),
3239 TraitItem(&'hir TraitItem<'hir>),
3240 ImplItem(&'hir ImplItem<'hir>),
3241 Crate(&'hir Mod<'hir>),
3244 impl<'hir> OwnerNode<'hir> {
3245 pub fn ident(&self) -> Option<Ident> {
3247 OwnerNode::Item(Item { ident, .. })
3248 | OwnerNode::ForeignItem(ForeignItem { ident, .. })
3249 | OwnerNode::ImplItem(ImplItem { ident, .. })
3250 | OwnerNode::TraitItem(TraitItem { ident, .. }) => Some(*ident),
3251 OwnerNode::Crate(..) => None,
3255 pub fn span(&self) -> Span {
3257 OwnerNode::Item(Item { span, .. })
3258 | OwnerNode::ForeignItem(ForeignItem { span, .. })
3259 | OwnerNode::ImplItem(ImplItem { span, .. })
3260 | OwnerNode::TraitItem(TraitItem { span, .. }) => *span,
3261 OwnerNode::Crate(Mod { spans: ModSpans { inner_span, .. }, .. }) => *inner_span,
3265 pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
3267 OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3268 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3269 | OwnerNode::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3270 OwnerNode::ForeignItem(ForeignItem {
3271 kind: ForeignItemKind::Fn(fn_decl, _, _),
3273 }) => Some(fn_decl),
3278 pub fn body_id(&self) -> Option<BodyId> {
3280 OwnerNode::TraitItem(TraitItem {
3281 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3284 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3285 | OwnerNode::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3290 pub fn generics(self) -> Option<&'hir Generics<'hir>> {
3291 Node::generics(self.into())
3294 pub fn def_id(self) -> OwnerId {
3296 OwnerNode::Item(Item { owner_id, .. })
3297 | OwnerNode::TraitItem(TraitItem { owner_id, .. })
3298 | OwnerNode::ImplItem(ImplItem { owner_id, .. })
3299 | OwnerNode::ForeignItem(ForeignItem { owner_id, .. }) => *owner_id,
3300 OwnerNode::Crate(..) => crate::CRATE_HIR_ID.owner,
3304 pub fn expect_item(self) -> &'hir Item<'hir> {
3306 OwnerNode::Item(n) => n,
3311 pub fn expect_foreign_item(self) -> &'hir ForeignItem<'hir> {
3313 OwnerNode::ForeignItem(n) => n,
3318 pub fn expect_impl_item(self) -> &'hir ImplItem<'hir> {
3320 OwnerNode::ImplItem(n) => n,
3325 pub fn expect_trait_item(self) -> &'hir TraitItem<'hir> {
3327 OwnerNode::TraitItem(n) => n,
3333 impl<'hir> Into<OwnerNode<'hir>> for &'hir Item<'hir> {
3334 fn into(self) -> OwnerNode<'hir> {
3335 OwnerNode::Item(self)
3339 impl<'hir> Into<OwnerNode<'hir>> for &'hir ForeignItem<'hir> {
3340 fn into(self) -> OwnerNode<'hir> {
3341 OwnerNode::ForeignItem(self)
3345 impl<'hir> Into<OwnerNode<'hir>> for &'hir ImplItem<'hir> {
3346 fn into(self) -> OwnerNode<'hir> {
3347 OwnerNode::ImplItem(self)
3351 impl<'hir> Into<OwnerNode<'hir>> for &'hir TraitItem<'hir> {
3352 fn into(self) -> OwnerNode<'hir> {
3353 OwnerNode::TraitItem(self)
3357 impl<'hir> Into<Node<'hir>> for OwnerNode<'hir> {
3358 fn into(self) -> Node<'hir> {
3360 OwnerNode::Item(n) => Node::Item(n),
3361 OwnerNode::ForeignItem(n) => Node::ForeignItem(n),
3362 OwnerNode::ImplItem(n) => Node::ImplItem(n),
3363 OwnerNode::TraitItem(n) => Node::TraitItem(n),
3364 OwnerNode::Crate(n) => Node::Crate(n),
3369 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3370 pub enum Node<'hir> {
3371 Param(&'hir Param<'hir>),
3372 Item(&'hir Item<'hir>),
3373 ForeignItem(&'hir ForeignItem<'hir>),
3374 TraitItem(&'hir TraitItem<'hir>),
3375 ImplItem(&'hir ImplItem<'hir>),
3376 Variant(&'hir Variant<'hir>),
3377 Field(&'hir FieldDef<'hir>),
3378 AnonConst(&'hir AnonConst),
3379 Expr(&'hir Expr<'hir>),
3380 ExprField(&'hir ExprField<'hir>),
3381 Stmt(&'hir Stmt<'hir>),
3382 PathSegment(&'hir PathSegment<'hir>),
3384 TypeBinding(&'hir TypeBinding<'hir>),
3385 TraitRef(&'hir TraitRef<'hir>),
3386 Pat(&'hir Pat<'hir>),
3387 PatField(&'hir PatField<'hir>),
3388 Arm(&'hir Arm<'hir>),
3389 Block(&'hir Block<'hir>),
3390 Local(&'hir Local<'hir>),
3392 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
3393 /// with synthesized constructors.
3394 Ctor(&'hir VariantData<'hir>),
3396 Lifetime(&'hir Lifetime),
3397 GenericParam(&'hir GenericParam<'hir>),
3399 Crate(&'hir Mod<'hir>),
3401 Infer(&'hir InferArg),
3404 impl<'hir> Node<'hir> {
3405 /// Get the identifier of this `Node`, if applicable.
3409 /// Calling `.ident()` on a [`Node::Ctor`] will return `None`
3410 /// because `Ctor`s do not have identifiers themselves.
3411 /// Instead, call `.ident()` on the parent struct/variant, like so:
3413 /// ```ignore (illustrative)
3416 /// .and_then(|ctor_id| tcx.hir().find(tcx.hir().get_parent_node(ctor_id)))
3417 /// .and_then(|parent| parent.ident())
3419 pub fn ident(&self) -> Option<Ident> {
3421 Node::TraitItem(TraitItem { ident, .. })
3422 | Node::ImplItem(ImplItem { ident, .. })
3423 | Node::ForeignItem(ForeignItem { ident, .. })
3424 | Node::Field(FieldDef { ident, .. })
3425 | Node::Variant(Variant { ident, .. })
3426 | Node::Item(Item { ident, .. })
3427 | Node::PathSegment(PathSegment { ident, .. }) => Some(*ident),
3428 Node::Lifetime(lt) => Some(lt.name.ident()),
3429 Node::GenericParam(p) => Some(p.name.ident()),
3430 Node::TypeBinding(b) => Some(b.ident),
3432 | Node::AnonConst(..)
3438 | Node::PatField(..)
3439 | Node::ExprField(..)
3444 | Node::TraitRef(..)
3445 | Node::Infer(..) => None,
3449 pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
3451 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3452 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3453 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3454 Node::Expr(Expr { kind: ExprKind::Closure(Closure { fn_decl, .. }), .. })
3455 | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
3462 pub fn fn_sig(self) -> Option<&'hir FnSig<'hir>> {
3464 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3465 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3466 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig),
3471 pub fn body_id(&self) -> Option<BodyId> {
3473 Node::TraitItem(TraitItem {
3474 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3477 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3478 | Node::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3483 pub fn generics(self) -> Option<&'hir Generics<'hir>> {
3485 Node::ForeignItem(ForeignItem {
3486 kind: ForeignItemKind::Fn(_, _, generics), ..
3488 | Node::TraitItem(TraitItem { generics, .. })
3489 | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
3490 Node::Item(item) => item.kind.generics(),
3495 pub fn as_owner(self) -> Option<OwnerNode<'hir>> {
3497 Node::Item(i) => Some(OwnerNode::Item(i)),
3498 Node::ForeignItem(i) => Some(OwnerNode::ForeignItem(i)),
3499 Node::TraitItem(i) => Some(OwnerNode::TraitItem(i)),
3500 Node::ImplItem(i) => Some(OwnerNode::ImplItem(i)),
3501 Node::Crate(i) => Some(OwnerNode::Crate(i)),
3506 pub fn fn_kind(self) -> Option<FnKind<'hir>> {
3508 Node::Item(i) => match i.kind {
3509 ItemKind::Fn(ref sig, ref generics, _) => {
3510 Some(FnKind::ItemFn(i.ident, generics, sig.header))
3514 Node::TraitItem(ti) => match ti.kind {
3515 TraitItemKind::Fn(ref sig, TraitFn::Provided(_)) => {
3516 Some(FnKind::Method(ti.ident, sig))
3520 Node::ImplItem(ii) => match ii.kind {
3521 ImplItemKind::Fn(ref sig, _) => Some(FnKind::Method(ii.ident, sig)),
3524 Node::Expr(e) => match e.kind {
3525 ExprKind::Closure { .. } => Some(FnKind::Closure),
3532 /// Get the fields for the tuple-constructor,
3533 /// if this node is a tuple constructor, otherwise None
3534 pub fn tuple_fields(&self) -> Option<&'hir [FieldDef<'hir>]> {
3535 if let Node::Ctor(&VariantData::Tuple(fields, _)) = self { Some(fields) } else { None }
3539 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3540 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
3543 // tidy-alphabetical-start
3544 static_assert_size!(Block<'_>, 48);
3545 static_assert_size!(Body<'_>, 32);
3546 static_assert_size!(Expr<'_>, 64);
3547 static_assert_size!(ExprKind<'_>, 48);
3548 static_assert_size!(FnDecl<'_>, 40);
3549 static_assert_size!(ForeignItem<'_>, 72);
3550 static_assert_size!(ForeignItemKind<'_>, 40);
3551 static_assert_size!(GenericArg<'_>, 24);
3552 static_assert_size!(GenericBound<'_>, 48);
3553 static_assert_size!(Generics<'_>, 56);
3554 static_assert_size!(Impl<'_>, 80);
3555 static_assert_size!(ImplItem<'_>, 80);
3556 static_assert_size!(ImplItemKind<'_>, 32);
3557 static_assert_size!(Item<'_>, 80);
3558 static_assert_size!(ItemKind<'_>, 48);
3559 static_assert_size!(Local<'_>, 64);
3560 static_assert_size!(Param<'_>, 32);
3561 static_assert_size!(Pat<'_>, 72);
3562 static_assert_size!(Path<'_>, 40);
3563 static_assert_size!(PathSegment<'_>, 48);
3564 static_assert_size!(PatKind<'_>, 48);
3565 static_assert_size!(QPath<'_>, 24);
3566 static_assert_size!(Res, 12);
3567 static_assert_size!(Stmt<'_>, 32);
3568 static_assert_size!(StmtKind<'_>, 16);
3569 static_assert_size!(TraitItem<'_>, 88);
3570 static_assert_size!(TraitItemKind<'_>, 48);
3571 static_assert_size!(Ty<'_>, 48);
3572 static_assert_size!(TyKind<'_>, 32);
3573 // tidy-alphabetical-end