1 use crate::def::{CtorKind, DefKind, Res};
2 use crate::def_id::DefId;
3 pub(crate) use crate::hir_id::{HirId, ItemLocalId};
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
143 // *not* elided -- but this is because, as far as the code
144 // in the compiler is concerned -- `Fresh` variants act
145 // equivalently to "some fresh name". They correspond to
146 // early-bound regions on an impl, in other words.
147 LifetimeName::Error | LifetimeName::Param(..) | LifetimeName::Static => false,
151 fn is_static(&self) -> bool {
152 self == &LifetimeName::Static
155 pub fn normalize_to_macros_2_0(&self) -> LifetimeName {
157 LifetimeName::Param(def_id, param_name) => {
158 LifetimeName::Param(def_id, param_name.normalize_to_macros_2_0())
160 lifetime_name => lifetime_name,
165 impl fmt::Display for Lifetime {
166 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167 self.name.ident().fmt(f)
172 pub fn is_elided(&self) -> bool {
173 self.name.is_elided()
176 pub fn is_static(&self) -> bool {
177 self.name.is_static()
181 /// A `Path` is essentially Rust's notion of a name; for instance,
182 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
183 /// along with a bunch of supporting information.
184 #[derive(Debug, HashStable_Generic)]
185 pub struct Path<'hir> {
187 /// The resolution for the path.
189 /// The segments in the path: the things separated by `::`.
190 pub segments: &'hir [PathSegment<'hir>],
194 pub fn is_global(&self) -> bool {
195 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
199 /// A segment of a path: an identifier, an optional lifetime, and a set of
201 #[derive(Debug, HashStable_Generic)]
202 pub struct PathSegment<'hir> {
203 /// The identifier portion of this path segment.
208 /// Type/lifetime parameters attached to this path. They come in
209 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
210 /// this is more than just simple syntactic sugar; the use of
211 /// parens affects the region binding rules, so we preserve the
213 pub args: Option<&'hir GenericArgs<'hir>>,
215 /// Whether to infer remaining type parameters, if any.
216 /// This only applies to expression and pattern paths, and
217 /// out of those only the segments with no type parameters
218 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
219 pub infer_args: bool,
222 impl<'hir> PathSegment<'hir> {
223 /// Converts an identifier to the corresponding segment.
224 pub fn new(ident: Ident, hir_id: HirId, res: Res) -> PathSegment<'hir> {
225 PathSegment { ident, hir_id, res, infer_args: true, args: None }
228 pub fn invalid() -> Self {
229 Self::new(Ident::empty(), HirId::INVALID, Res::Err)
232 pub fn args(&self) -> &GenericArgs<'hir> {
233 if let Some(ref args) = self.args {
236 const DUMMY: &GenericArgs<'_> = &GenericArgs::none();
242 #[derive(Encodable, Debug, HashStable_Generic)]
243 pub struct ConstArg {
244 pub value: AnonConst,
248 #[derive(Encodable, Debug, HashStable_Generic)]
249 pub struct InferArg {
255 pub fn to_ty(&self) -> Ty<'_> {
256 Ty { kind: TyKind::Infer, span: self.span, hir_id: self.hir_id }
260 #[derive(Debug, HashStable_Generic)]
261 pub enum GenericArg<'hir> {
263 Type(&'hir Ty<'hir>),
268 impl GenericArg<'_> {
269 pub fn span(&self) -> Span {
271 GenericArg::Lifetime(l) => l.span,
272 GenericArg::Type(t) => t.span,
273 GenericArg::Const(c) => c.span,
274 GenericArg::Infer(i) => i.span,
278 pub fn hir_id(&self) -> HirId {
280 GenericArg::Lifetime(l) => l.hir_id,
281 GenericArg::Type(t) => t.hir_id,
282 GenericArg::Const(c) => c.value.hir_id,
283 GenericArg::Infer(i) => i.hir_id,
287 pub fn is_synthetic(&self) -> bool {
288 matches!(self, GenericArg::Lifetime(lifetime) if lifetime.name.ident() == Ident::empty())
291 pub fn descr(&self) -> &'static str {
293 GenericArg::Lifetime(_) => "lifetime",
294 GenericArg::Type(_) => "type",
295 GenericArg::Const(_) => "constant",
296 GenericArg::Infer(_) => "inferred",
300 pub fn to_ord(&self) -> ast::ParamKindOrd {
302 GenericArg::Lifetime(_) => ast::ParamKindOrd::Lifetime,
303 GenericArg::Type(_) => ast::ParamKindOrd::Type,
304 GenericArg::Const(_) => ast::ParamKindOrd::Const,
305 GenericArg::Infer(_) => ast::ParamKindOrd::Infer,
309 pub fn is_ty_or_const(&self) -> bool {
311 GenericArg::Lifetime(_) => false,
312 GenericArg::Type(_) | GenericArg::Const(_) | GenericArg::Infer(_) => true,
317 #[derive(Debug, HashStable_Generic)]
318 pub struct GenericArgs<'hir> {
319 /// The generic arguments for this path segment.
320 pub args: &'hir [GenericArg<'hir>],
321 /// Bindings (equality constraints) on associated types, if present.
322 /// E.g., `Foo<A = Bar>`.
323 pub bindings: &'hir [TypeBinding<'hir>],
324 /// Were arguments written in parenthesized form `Fn(T) -> U`?
325 /// This is required mostly for pretty-printing and diagnostics,
326 /// but also for changing lifetime elision rules to be "function-like".
327 pub parenthesized: bool,
328 /// The span encompassing arguments and the surrounding brackets `<>` or `()`
329 /// Foo<A, B, AssocTy = D> Fn(T, U, V) -> W
330 /// ^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^
331 /// Note that this may be:
332 /// - empty, if there are no generic brackets (but there may be hidden lifetimes)
333 /// - dummy, if this was generated while desugaring
337 impl<'hir> GenericArgs<'hir> {
338 pub const fn none() -> Self {
339 Self { args: &[], bindings: &[], parenthesized: false, span_ext: DUMMY_SP }
342 pub fn inputs(&self) -> &[Ty<'hir>] {
343 if self.parenthesized {
344 for arg in self.args {
346 GenericArg::Lifetime(_) => {}
347 GenericArg::Type(ref ty) => {
348 if let TyKind::Tup(ref tys) = ty.kind {
353 GenericArg::Const(_) => {}
354 GenericArg::Infer(_) => {}
358 panic!("GenericArgs::inputs: not a `Fn(T) -> U`");
362 pub fn has_type_params(&self) -> bool {
363 self.args.iter().any(|arg| matches!(arg, GenericArg::Type(_)))
366 pub fn has_err(&self) -> bool {
367 self.args.iter().any(|arg| match arg {
368 GenericArg::Type(ty) => matches!(ty.kind, TyKind::Err),
370 }) || self.bindings.iter().any(|arg| match arg.kind {
371 TypeBindingKind::Equality { term: Term::Ty(ty) } => matches!(ty.kind, TyKind::Err),
377 pub fn num_type_params(&self) -> usize {
378 self.args.iter().filter(|arg| matches!(arg, GenericArg::Type(_))).count()
382 pub fn num_lifetime_params(&self) -> usize {
383 self.args.iter().filter(|arg| matches!(arg, GenericArg::Lifetime(_))).count()
387 pub fn has_lifetime_params(&self) -> bool {
388 self.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)))
392 pub fn num_generic_params(&self) -> usize {
393 self.args.iter().filter(|arg| !matches!(arg, GenericArg::Lifetime(_))).count()
396 /// The span encompassing the text inside the surrounding brackets.
397 /// It will also include bindings if they aren't in the form `-> Ret`
398 /// Returns `None` if the span is empty (e.g. no brackets) or dummy
399 pub fn span(&self) -> Option<Span> {
400 let span_ext = self.span_ext()?;
401 Some(span_ext.with_lo(span_ext.lo() + BytePos(1)).with_hi(span_ext.hi() - BytePos(1)))
404 /// Returns span encompassing arguments and their surrounding `<>` or `()`
405 pub fn span_ext(&self) -> Option<Span> {
406 Some(self.span_ext).filter(|span| !span.is_empty())
409 pub fn is_empty(&self) -> bool {
414 /// A modifier on a bound, currently this is only used for `?Sized`, where the
415 /// modifier is `Maybe`. Negative bounds should also be handled here.
416 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
417 #[derive(HashStable_Generic)]
418 pub enum TraitBoundModifier {
424 /// The AST represents all type param bounds as types.
425 /// `typeck::collect::compute_bounds` matches these against
426 /// the "special" built-in traits (see `middle::lang_items`) and
427 /// detects `Copy`, `Send` and `Sync`.
428 #[derive(Clone, Debug, HashStable_Generic)]
429 pub enum GenericBound<'hir> {
430 Trait(PolyTraitRef<'hir>, TraitBoundModifier),
431 // FIXME(davidtwco): Introduce `PolyTraitRef::LangItem`
432 LangItemTrait(LangItem, Span, HirId, &'hir GenericArgs<'hir>),
436 impl GenericBound<'_> {
437 pub fn trait_ref(&self) -> Option<&TraitRef<'_>> {
439 GenericBound::Trait(data, _) => Some(&data.trait_ref),
444 pub fn span(&self) -> Span {
446 GenericBound::Trait(t, ..) => t.span,
447 GenericBound::LangItemTrait(_, span, ..) => *span,
448 GenericBound::Outlives(l) => l.span,
453 pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
455 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
456 pub enum LifetimeParamKind {
457 // Indicates that the lifetime definition was explicitly declared (e.g., in
458 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
461 // Indication that the lifetime was elided (e.g., in both cases in
462 // `fn foo(x: &u8) -> &'_ u8 { x }`).
465 // Indication that the lifetime name was somehow in error.
469 #[derive(Debug, HashStable_Generic)]
470 pub enum GenericParamKind<'hir> {
471 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
473 kind: LifetimeParamKind,
476 default: Option<&'hir Ty<'hir>>,
481 /// Optional default value for the const generic param
482 default: Option<AnonConst>,
486 #[derive(Debug, HashStable_Generic)]
487 pub struct GenericParam<'hir> {
491 pub pure_wrt_drop: bool,
492 pub kind: GenericParamKind<'hir>,
493 pub colon_span: Option<Span>,
496 impl<'hir> GenericParam<'hir> {
497 /// Synthetic type-parameters are inserted after normal ones.
498 /// In order for normal parameters to be able to refer to synthetic ones,
499 /// scans them first.
500 pub fn is_impl_trait(&self) -> bool {
501 matches!(self.kind, GenericParamKind::Type { synthetic: true, .. })
504 /// This can happen for `async fn`, e.g. `async fn f<'_>(&'_ self)`.
506 /// See `lifetime_to_generic_param` in `rustc_ast_lowering` for more information.
507 pub fn is_elided_lifetime(&self) -> bool {
508 matches!(self.kind, GenericParamKind::Lifetime { kind: LifetimeParamKind::Elided })
513 pub struct GenericParamCount {
514 pub lifetimes: usize,
520 /// Represents lifetimes and type parameters attached to a declaration
521 /// of a function, enum, trait, etc.
522 #[derive(Debug, HashStable_Generic)]
523 pub struct Generics<'hir> {
524 pub params: &'hir [GenericParam<'hir>],
525 pub predicates: &'hir [WherePredicate<'hir>],
526 pub has_where_clause_predicates: bool,
527 pub where_clause_span: Span,
531 impl<'hir> Generics<'hir> {
532 pub const fn empty() -> &'hir Generics<'hir> {
533 const NOPE: Generics<'_> = Generics {
536 has_where_clause_predicates: false,
537 where_clause_span: DUMMY_SP,
543 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'hir>> {
544 for param in self.params {
545 if name == param.name.ident().name {
552 pub fn spans(&self) -> MultiSpan {
553 if self.params.is_empty() {
556 self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
560 /// If there are generic parameters, return where to introduce a new one.
561 pub fn span_for_param_suggestion(&self) -> Option<Span> {
562 if self.params.iter().any(|p| self.span.contains(p.span)) {
563 // `fn foo<A>(t: impl Trait)`
564 // ^ suggest `, T: Trait` here
565 let span = self.span.with_lo(self.span.hi() - BytePos(1)).shrink_to_lo();
572 /// `Span` where further predicates would be suggested, accounting for trailing commas, like
573 /// in `fn foo<T>(t: T) where T: Foo,` so we don't suggest two trailing commas.
574 pub fn tail_span_for_predicate_suggestion(&self) -> Span {
575 let end = self.where_clause_span.shrink_to_hi();
576 if self.has_where_clause_predicates {
579 .filter(|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> {
737 /// Origin of the predicate.
738 pub origin: PredicateOrigin,
739 /// Any generics from a `for` binding.
740 pub bound_generic_params: &'hir [GenericParam<'hir>],
741 /// The type being bounded.
742 pub bounded_ty: &'hir Ty<'hir>,
743 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
744 pub bounds: GenericBounds<'hir>,
747 impl<'hir> WhereBoundPredicate<'hir> {
748 /// Returns `true` if `param_def_id` matches the `bounded_ty` of this predicate.
749 pub fn is_param_bound(&self, param_def_id: DefId) -> bool {
750 self.bounded_ty.as_generic_param().map_or(false, |(def_id, _)| def_id == param_def_id)
754 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
755 #[derive(Debug, HashStable_Generic)]
756 pub struct WhereRegionPredicate<'hir> {
758 pub in_where_clause: bool,
759 pub lifetime: Lifetime,
760 pub bounds: GenericBounds<'hir>,
763 impl<'hir> WhereRegionPredicate<'hir> {
764 /// Returns `true` if `param_def_id` matches the `lifetime` of this predicate.
765 pub fn is_param_bound(&self, param_def_id: LocalDefId) -> bool {
766 match self.lifetime.name {
767 LifetimeName::Param(id, _) => id == param_def_id,
773 /// An equality predicate (e.g., `T = int`); currently unsupported.
774 #[derive(Debug, HashStable_Generic)]
775 pub struct WhereEqPredicate<'hir> {
777 pub lhs_ty: &'hir Ty<'hir>,
778 pub rhs_ty: &'hir Ty<'hir>,
781 /// HIR node coupled with its parent's id in the same HIR owner.
783 /// The parent is trash when the node is a HIR owner.
784 #[derive(Clone, Debug)]
785 pub struct ParentedNode<'tcx> {
786 pub parent: ItemLocalId,
787 pub node: Node<'tcx>,
790 /// Attributes owned by a HIR owner.
792 pub struct AttributeMap<'tcx> {
793 pub map: SortedMap<ItemLocalId, &'tcx [Attribute]>,
794 pub hash: Fingerprint,
797 impl<'tcx> AttributeMap<'tcx> {
798 pub const EMPTY: &'static AttributeMap<'static> =
799 &AttributeMap { map: SortedMap::new(), hash: Fingerprint::ZERO };
802 pub fn get(&self, id: ItemLocalId) -> &'tcx [Attribute] {
803 self.map.get(&id).copied().unwrap_or(&[])
807 /// Map of all HIR nodes inside the current owner.
808 /// These nodes are mapped by `ItemLocalId` alongside the index of their parent node.
809 /// The HIR tree, including bodies, is pre-hashed.
810 pub struct OwnerNodes<'tcx> {
811 /// Pre-computed hash of the full HIR.
812 pub hash_including_bodies: Fingerprint,
813 /// Pre-computed hash of the item signature, sithout recursing into the body.
814 pub hash_without_bodies: Fingerprint,
815 /// Full HIR for the current owner.
816 // The zeroth node's parent should never be accessed: the owner's parent is computed by the
817 // hir_owner_parent query. It is set to `ItemLocalId::INVALID` to force an ICE if accidentally
819 pub nodes: IndexVec<ItemLocalId, Option<ParentedNode<'tcx>>>,
820 /// Content of local bodies.
821 pub bodies: SortedMap<ItemLocalId, &'tcx Body<'tcx>>,
822 /// Non-owning definitions contained in this owner.
823 pub local_id_to_def_id: SortedMap<ItemLocalId, LocalDefId>,
826 impl<'tcx> OwnerNodes<'tcx> {
827 pub fn node(&self) -> OwnerNode<'tcx> {
828 use rustc_index::vec::Idx;
829 let node = self.nodes[ItemLocalId::new(0)].as_ref().unwrap().node;
830 let node = node.as_owner().unwrap(); // Indexing must ensure it is an OwnerNode.
835 impl fmt::Debug for OwnerNodes<'_> {
836 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
837 f.debug_struct("OwnerNodes")
838 .field("node", &self.nodes[ItemLocalId::from_u32(0)])
839 .field("bodies", &self.bodies)
840 .field("local_id_to_def_id", &self.local_id_to_def_id)
841 .field("hash_without_bodies", &self.hash_without_bodies)
842 .field("hash_including_bodies", &self.hash_including_bodies)
847 /// Full information resulting from lowering an AST node.
848 #[derive(Debug, HashStable_Generic)]
849 pub struct OwnerInfo<'hir> {
850 /// Contents of the HIR.
851 pub nodes: OwnerNodes<'hir>,
852 /// Map from each nested owner to its parent's local id.
853 pub parenting: FxHashMap<LocalDefId, ItemLocalId>,
854 /// Collected attributes of the HIR nodes.
855 pub attrs: AttributeMap<'hir>,
856 /// Map indicating what traits are in scope for places where this
857 /// is relevant; generated by resolve.
858 pub trait_map: FxHashMap<ItemLocalId, Box<[TraitCandidate]>>,
861 impl<'tcx> OwnerInfo<'tcx> {
863 pub fn node(&self) -> OwnerNode<'tcx> {
868 #[derive(Copy, Clone, Debug, HashStable_Generic)]
869 pub enum MaybeOwner<T> {
872 /// Used as a placeholder for unused LocalDefId.
876 impl<T> MaybeOwner<T> {
877 pub fn as_owner(self) -> Option<T> {
879 MaybeOwner::Owner(i) => Some(i),
880 MaybeOwner::NonOwner(_) | MaybeOwner::Phantom => None,
884 pub fn map<U>(self, f: impl FnOnce(T) -> U) -> MaybeOwner<U> {
886 MaybeOwner::Owner(i) => MaybeOwner::Owner(f(i)),
887 MaybeOwner::NonOwner(hir_id) => MaybeOwner::NonOwner(hir_id),
888 MaybeOwner::Phantom => MaybeOwner::Phantom,
892 pub fn unwrap(self) -> T {
894 MaybeOwner::Owner(i) => i,
895 MaybeOwner::NonOwner(_) | MaybeOwner::Phantom => panic!("Not a HIR owner"),
900 /// The top-level data structure that stores the entire contents of
901 /// the crate currently being compiled.
903 /// For more details, see the [rustc dev guide].
905 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
907 pub struct Crate<'hir> {
908 pub owners: IndexVec<LocalDefId, MaybeOwner<&'hir OwnerInfo<'hir>>>,
909 pub hir_hash: Fingerprint,
912 #[derive(Debug, HashStable_Generic)]
913 pub struct Closure<'hir> {
914 pub binder: ClosureBinder,
915 pub capture_clause: CaptureBy,
916 pub bound_generic_params: &'hir [GenericParam<'hir>],
917 pub fn_decl: &'hir FnDecl<'hir>,
919 pub fn_decl_span: Span,
920 pub movability: Option<Movability>,
923 /// A block of statements `{ .. }`, which may have a label (in this case the
924 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
925 /// the `rules` being anything but `DefaultBlock`.
926 #[derive(Debug, HashStable_Generic)]
927 pub struct Block<'hir> {
928 /// Statements in a block.
929 pub stmts: &'hir [Stmt<'hir>],
930 /// An expression at the end of the block
931 /// without a semicolon, if any.
932 pub expr: Option<&'hir Expr<'hir>>,
933 #[stable_hasher(ignore)]
935 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
936 pub rules: BlockCheckMode,
938 /// If true, then there may exist `break 'a` values that aim to
939 /// break out of this block early.
940 /// Used by `'label: {}` blocks and by `try {}` blocks.
941 pub targeted_by_break: bool,
944 impl<'hir> Block<'hir> {
945 pub fn innermost_block(&self) -> &Block<'hir> {
946 let mut block = self;
947 while let Some(Expr { kind: ExprKind::Block(inner_block, _), .. }) = block.expr {
954 #[derive(Debug, HashStable_Generic)]
955 pub struct Pat<'hir> {
956 #[stable_hasher(ignore)]
958 pub kind: PatKind<'hir>,
960 // Whether to use default binding modes.
961 // At present, this is false only for destructuring assignment.
962 pub default_binding_modes: bool,
965 impl<'hir> Pat<'hir> {
966 // FIXME(#19596) this is a workaround, but there should be a better way
967 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) -> bool {
974 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
975 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
976 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
977 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
978 Slice(before, slice, after) => {
979 before.iter().chain(slice).chain(after.iter()).all(|p| p.walk_short_(it))
984 /// Walk the pattern in left-to-right order,
985 /// short circuiting (with `.all(..)`) if `false` is returned.
987 /// Note that when visiting e.g. `Tuple(ps)`,
988 /// if visiting `ps[0]` returns `false`,
989 /// then `ps[1]` will not be visited.
990 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) -> bool {
991 self.walk_short_(&mut it)
994 // FIXME(#19596) this is a workaround, but there should be a better way
995 fn walk_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) {
1002 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
1003 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
1004 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
1005 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
1006 Slice(before, slice, after) => {
1007 before.iter().chain(slice).chain(after.iter()).for_each(|p| p.walk_(it))
1012 /// Walk the pattern in left-to-right order.
1014 /// If `it(pat)` returns `false`, the children are not visited.
1015 pub fn walk(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) {
1019 /// Walk the pattern in left-to-right order.
1021 /// If you always want to recurse, prefer this method over `walk`.
1022 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
1030 /// A single field in a struct pattern.
1032 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
1033 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
1034 /// except `is_shorthand` is true.
1035 #[derive(Debug, HashStable_Generic)]
1036 pub struct PatField<'hir> {
1037 #[stable_hasher(ignore)]
1039 /// The identifier for the field.
1041 /// The pattern the field is destructured to.
1042 pub pat: &'hir Pat<'hir>,
1043 pub is_shorthand: bool,
1047 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1053 impl fmt::Display for RangeEnd {
1054 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1055 f.write_str(match self {
1056 RangeEnd::Included => "..=",
1057 RangeEnd::Excluded => "..",
1062 #[derive(Debug, HashStable_Generic)]
1063 pub enum PatKind<'hir> {
1064 /// Represents a wildcard pattern (i.e., `_`).
1067 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
1068 /// The `HirId` is the canonical ID for the variable being bound,
1069 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
1070 /// which is the pattern ID of the first `x`.
1071 Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
1073 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
1074 /// The `bool` is `true` in the presence of a `..`.
1075 Struct(QPath<'hir>, &'hir [PatField<'hir>], bool),
1077 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
1078 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
1079 /// `0 <= position <= subpats.len()`
1080 TupleStruct(QPath<'hir>, &'hir [Pat<'hir>], Option<usize>),
1082 /// An or-pattern `A | B | C`.
1083 /// Invariant: `pats.len() >= 2`.
1084 Or(&'hir [Pat<'hir>]),
1086 /// A path pattern for a unit struct/variant or a (maybe-associated) constant.
1089 /// A tuple pattern (e.g., `(a, b)`).
1090 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
1091 /// `0 <= position <= subpats.len()`
1092 Tuple(&'hir [Pat<'hir>], Option<usize>),
1094 /// A `box` pattern.
1095 Box(&'hir Pat<'hir>),
1097 /// A reference pattern (e.g., `&mut (a, b)`).
1098 Ref(&'hir Pat<'hir>, Mutability),
1101 Lit(&'hir Expr<'hir>),
1103 /// A range pattern (e.g., `1..=2` or `1..2`).
1104 Range(Option<&'hir Expr<'hir>>, Option<&'hir Expr<'hir>>, RangeEnd),
1106 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
1108 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
1109 /// If `slice` exists, then `after` can be non-empty.
1111 /// The representation for e.g., `[a, b, .., c, d]` is:
1112 /// ```ignore (illustrative)
1113 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
1115 Slice(&'hir [Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [Pat<'hir>]),
1118 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1119 pub enum BinOpKind {
1120 /// The `+` operator (addition).
1122 /// The `-` operator (subtraction).
1124 /// The `*` operator (multiplication).
1126 /// The `/` operator (division).
1128 /// The `%` operator (modulus).
1130 /// The `&&` operator (logical and).
1132 /// The `||` operator (logical or).
1134 /// The `^` operator (bitwise xor).
1136 /// The `&` operator (bitwise and).
1138 /// The `|` operator (bitwise or).
1140 /// The `<<` operator (shift left).
1142 /// The `>>` operator (shift right).
1144 /// The `==` operator (equality).
1146 /// The `<` operator (less than).
1148 /// The `<=` operator (less than or equal to).
1150 /// The `!=` operator (not equal to).
1152 /// The `>=` operator (greater than or equal to).
1154 /// The `>` operator (greater than).
1159 pub fn as_str(self) -> &'static str {
1161 BinOpKind::Add => "+",
1162 BinOpKind::Sub => "-",
1163 BinOpKind::Mul => "*",
1164 BinOpKind::Div => "/",
1165 BinOpKind::Rem => "%",
1166 BinOpKind::And => "&&",
1167 BinOpKind::Or => "||",
1168 BinOpKind::BitXor => "^",
1169 BinOpKind::BitAnd => "&",
1170 BinOpKind::BitOr => "|",
1171 BinOpKind::Shl => "<<",
1172 BinOpKind::Shr => ">>",
1173 BinOpKind::Eq => "==",
1174 BinOpKind::Lt => "<",
1175 BinOpKind::Le => "<=",
1176 BinOpKind::Ne => "!=",
1177 BinOpKind::Ge => ">=",
1178 BinOpKind::Gt => ">",
1182 pub fn is_lazy(self) -> bool {
1183 matches!(self, BinOpKind::And | BinOpKind::Or)
1186 pub fn is_shift(self) -> bool {
1187 matches!(self, BinOpKind::Shl | BinOpKind::Shr)
1190 pub fn is_comparison(self) -> bool {
1197 | BinOpKind::Ge => true,
1209 | BinOpKind::Shr => false,
1213 /// Returns `true` if the binary operator takes its arguments by value.
1214 pub fn is_by_value(self) -> bool {
1215 !self.is_comparison()
1219 impl Into<ast::BinOpKind> for BinOpKind {
1220 fn into(self) -> ast::BinOpKind {
1222 BinOpKind::Add => ast::BinOpKind::Add,
1223 BinOpKind::Sub => ast::BinOpKind::Sub,
1224 BinOpKind::Mul => ast::BinOpKind::Mul,
1225 BinOpKind::Div => ast::BinOpKind::Div,
1226 BinOpKind::Rem => ast::BinOpKind::Rem,
1227 BinOpKind::And => ast::BinOpKind::And,
1228 BinOpKind::Or => ast::BinOpKind::Or,
1229 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1230 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1231 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1232 BinOpKind::Shl => ast::BinOpKind::Shl,
1233 BinOpKind::Shr => ast::BinOpKind::Shr,
1234 BinOpKind::Eq => ast::BinOpKind::Eq,
1235 BinOpKind::Lt => ast::BinOpKind::Lt,
1236 BinOpKind::Le => ast::BinOpKind::Le,
1237 BinOpKind::Ne => ast::BinOpKind::Ne,
1238 BinOpKind::Ge => ast::BinOpKind::Ge,
1239 BinOpKind::Gt => ast::BinOpKind::Gt,
1244 pub type BinOp = Spanned<BinOpKind>;
1246 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1248 /// The `*` operator (dereferencing).
1250 /// The `!` operator (logical negation).
1252 /// The `-` operator (negation).
1257 pub fn as_str(self) -> &'static str {
1265 /// Returns `true` if the unary operator takes its argument by value.
1266 pub fn is_by_value(self) -> bool {
1267 matches!(self, Self::Neg | Self::Not)
1272 #[derive(Debug, HashStable_Generic)]
1273 pub struct Stmt<'hir> {
1275 pub kind: StmtKind<'hir>,
1279 /// The contents of a statement.
1280 #[derive(Debug, HashStable_Generic)]
1281 pub enum StmtKind<'hir> {
1282 /// A local (`let`) binding.
1283 Local(&'hir Local<'hir>),
1285 /// An item binding.
1288 /// An expression without a trailing semi-colon (must have unit type).
1289 Expr(&'hir Expr<'hir>),
1291 /// An expression with a trailing semi-colon (may have any type).
1292 Semi(&'hir Expr<'hir>),
1295 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <init>;`).
1296 #[derive(Debug, HashStable_Generic)]
1297 pub struct Local<'hir> {
1298 pub pat: &'hir Pat<'hir>,
1299 /// Type annotation, if any (otherwise the type will be inferred).
1300 pub ty: Option<&'hir Ty<'hir>>,
1301 /// Initializer expression to set the value, if any.
1302 pub init: Option<&'hir Expr<'hir>>,
1303 /// Else block for a `let...else` binding.
1304 pub els: Option<&'hir Block<'hir>>,
1307 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1308 /// desugaring. Otherwise will be `Normal`.
1309 pub source: LocalSource,
1312 /// Represents a single arm of a `match` expression, e.g.
1313 /// `<pat> (if <guard>) => <body>`.
1314 #[derive(Debug, HashStable_Generic)]
1315 pub struct Arm<'hir> {
1316 #[stable_hasher(ignore)]
1319 /// If this pattern and the optional guard matches, then `body` is evaluated.
1320 pub pat: &'hir Pat<'hir>,
1321 /// Optional guard clause.
1322 pub guard: Option<Guard<'hir>>,
1323 /// The expression the arm evaluates to if this arm matches.
1324 pub body: &'hir Expr<'hir>,
1327 /// Represents a `let <pat>[: <ty>] = <expr>` expression (not a Local), occurring in an `if-let` or
1328 /// `let-else`, evaluating to a boolean. Typically the pattern is refutable.
1330 /// In an if-let, imagine it as `if (let <pat> = <expr>) { ... }`; in a let-else, it is part of the
1331 /// desugaring to if-let. Only let-else supports the type annotation at present.
1332 #[derive(Debug, HashStable_Generic)]
1333 pub struct Let<'hir> {
1336 pub pat: &'hir Pat<'hir>,
1337 pub ty: Option<&'hir Ty<'hir>>,
1338 pub init: &'hir Expr<'hir>,
1341 #[derive(Debug, HashStable_Generic)]
1342 pub enum Guard<'hir> {
1343 If(&'hir Expr<'hir>),
1344 IfLet(&'hir Let<'hir>),
1347 impl<'hir> Guard<'hir> {
1348 /// Returns the body of the guard
1350 /// In other words, returns the e in either of the following:
1353 /// - `if let x = e`
1354 pub fn body(&self) -> &'hir Expr<'hir> {
1356 Guard::If(e) | Guard::IfLet(Let { init: e, .. }) => e,
1361 #[derive(Debug, HashStable_Generic)]
1362 pub struct ExprField<'hir> {
1363 #[stable_hasher(ignore)]
1366 pub expr: &'hir Expr<'hir>,
1368 pub is_shorthand: bool,
1371 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1372 pub enum BlockCheckMode {
1374 UnsafeBlock(UnsafeSource),
1377 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1378 pub enum UnsafeSource {
1383 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
1388 /// The body of a function, closure, or constant value. In the case of
1389 /// a function, the body contains not only the function body itself
1390 /// (which is an expression), but also the argument patterns, since
1391 /// those are something that the caller doesn't really care about.
1396 /// fn foo((x, y): (u32, u32)) -> u32 {
1401 /// Here, the `Body` associated with `foo()` would contain:
1403 /// - an `params` array containing the `(x, y)` pattern
1404 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1405 /// - `generator_kind` would be `None`
1407 /// All bodies have an **owner**, which can be accessed via the HIR
1408 /// map using `body_owner_def_id()`.
1409 #[derive(Debug, HashStable_Generic)]
1410 pub struct Body<'hir> {
1411 pub params: &'hir [Param<'hir>],
1412 pub value: &'hir Expr<'hir>,
1413 pub generator_kind: Option<GeneratorKind>,
1416 impl<'hir> Body<'hir> {
1417 pub fn id(&self) -> BodyId {
1418 BodyId { hir_id: self.value.hir_id }
1421 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1426 /// The type of source expression that caused this generator to be created.
1427 #[derive(Clone, PartialEq, PartialOrd, Eq, Hash, Debug, Copy)]
1428 #[derive(HashStable_Generic, Encodable, Decodable)]
1429 pub enum GeneratorKind {
1430 /// An explicit `async` block or the body of an async function.
1431 Async(AsyncGeneratorKind),
1433 /// A generator literal created via a `yield` inside a closure.
1437 impl fmt::Display for GeneratorKind {
1438 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1440 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1441 GeneratorKind::Gen => f.write_str("generator"),
1446 impl GeneratorKind {
1447 pub fn descr(&self) -> &'static str {
1449 GeneratorKind::Async(ask) => ask.descr(),
1450 GeneratorKind::Gen => "generator",
1455 /// In the case of a generator created as part of an async construct,
1456 /// which kind of async construct caused it to be created?
1458 /// This helps error messages but is also used to drive coercions in
1459 /// type-checking (see #60424).
1460 #[derive(Clone, PartialEq, PartialOrd, Eq, Hash, Debug, Copy)]
1461 #[derive(HashStable_Generic, Encodable, Decodable)]
1462 pub enum AsyncGeneratorKind {
1463 /// An explicit `async` block written by the user.
1466 /// An explicit `async` closure written by the user.
1469 /// The `async` block generated as the body of an async function.
1473 impl fmt::Display for AsyncGeneratorKind {
1474 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1475 f.write_str(match self {
1476 AsyncGeneratorKind::Block => "`async` block",
1477 AsyncGeneratorKind::Closure => "`async` closure body",
1478 AsyncGeneratorKind::Fn => "`async fn` body",
1483 impl AsyncGeneratorKind {
1484 pub fn descr(&self) -> &'static str {
1486 AsyncGeneratorKind::Block => "`async` block",
1487 AsyncGeneratorKind::Closure => "`async` closure body",
1488 AsyncGeneratorKind::Fn => "`async fn` body",
1493 #[derive(Copy, Clone, Debug)]
1494 pub enum BodyOwnerKind {
1495 /// Functions and methods.
1501 /// Constants and associated constants.
1504 /// Initializer of a `static` item.
1508 impl BodyOwnerKind {
1509 pub fn is_fn_or_closure(self) -> bool {
1511 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1512 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1517 /// The kind of an item that requires const-checking.
1518 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1519 pub enum ConstContext {
1523 /// A `static` or `static mut`.
1526 /// A `const`, associated `const`, or other const context.
1528 /// Other contexts include:
1529 /// - Array length expressions
1530 /// - Enum discriminants
1531 /// - Const generics
1533 /// For the most part, other contexts are treated just like a regular `const`, so they are
1534 /// lumped into the same category.
1539 /// A description of this const context that can appear between backticks in an error message.
1541 /// E.g. `const` or `static mut`.
1542 pub fn keyword_name(self) -> &'static str {
1544 Self::Const => "const",
1545 Self::Static(Mutability::Not) => "static",
1546 Self::Static(Mutability::Mut) => "static mut",
1547 Self::ConstFn => "const fn",
1552 /// A colloquial, trivially pluralizable description of this const context for use in error
1554 impl fmt::Display for ConstContext {
1555 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1557 Self::Const => write!(f, "constant"),
1558 Self::Static(_) => write!(f, "static"),
1559 Self::ConstFn => write!(f, "constant function"),
1564 // NOTE: `IntoDiagnosticArg` impl for `ConstContext` lives in `rustc_errors`
1565 // due to a cyclical dependency between hir that crate.
1568 pub type Lit = Spanned<LitKind>;
1570 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1577 pub fn hir_id(&self) -> HirId {
1579 &ArrayLen::Infer(hir_id, _) | &ArrayLen::Body(AnonConst { hir_id, body: _ }) => hir_id,
1584 /// A constant (expression) that's not an item or associated item,
1585 /// but needs its own `DefId` for type-checking, const-eval, etc.
1586 /// These are usually found nested inside types (e.g., array lengths)
1587 /// or expressions (e.g., repeat counts), and also used to define
1588 /// explicit discriminant values for enum variants.
1590 /// You can check if this anon const is a default in a const param
1591 /// `const N: usize = { ... }` with `tcx.hir().opt_const_param_default_param_hir_id(..)`
1592 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1593 pub struct AnonConst {
1599 #[derive(Debug, HashStable_Generic)]
1600 pub struct Expr<'hir> {
1602 pub kind: ExprKind<'hir>,
1607 pub fn precedence(&self) -> ExprPrecedence {
1609 ExprKind::Box(_) => ExprPrecedence::Box,
1610 ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1611 ExprKind::Array(_) => ExprPrecedence::Array,
1612 ExprKind::Call(..) => ExprPrecedence::Call,
1613 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1614 ExprKind::Tup(_) => ExprPrecedence::Tup,
1615 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1616 ExprKind::Unary(..) => ExprPrecedence::Unary,
1617 ExprKind::Lit(_) => ExprPrecedence::Lit,
1618 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1619 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1620 ExprKind::If(..) => ExprPrecedence::If,
1621 ExprKind::Let(..) => ExprPrecedence::Let,
1622 ExprKind::Loop(..) => ExprPrecedence::Loop,
1623 ExprKind::Match(..) => ExprPrecedence::Match,
1624 ExprKind::Closure { .. } => ExprPrecedence::Closure,
1625 ExprKind::Block(..) => ExprPrecedence::Block,
1626 ExprKind::Assign(..) => ExprPrecedence::Assign,
1627 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1628 ExprKind::Field(..) => ExprPrecedence::Field,
1629 ExprKind::Index(..) => ExprPrecedence::Index,
1630 ExprKind::Path(..) => ExprPrecedence::Path,
1631 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1632 ExprKind::Break(..) => ExprPrecedence::Break,
1633 ExprKind::Continue(..) => ExprPrecedence::Continue,
1634 ExprKind::Ret(..) => ExprPrecedence::Ret,
1635 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1636 ExprKind::Struct(..) => ExprPrecedence::Struct,
1637 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1638 ExprKind::Yield(..) => ExprPrecedence::Yield,
1639 ExprKind::Err => ExprPrecedence::Err,
1643 // Whether this looks like a place expr, without checking for deref
1645 // This will return `true` in some potentially surprising cases such as
1646 // `CONSTANT.field`.
1647 pub fn is_syntactic_place_expr(&self) -> bool {
1648 self.is_place_expr(|_| true)
1651 /// Whether this is a place expression.
1653 /// `allow_projections_from` should return `true` if indexing a field or index expression based
1654 /// on the given expression should be considered a place expression.
1655 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1657 ExprKind::Path(QPath::Resolved(_, ref path)) => {
1658 matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static(_), _) | Res::Err)
1661 // Type ascription inherits its place expression kind from its
1663 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1664 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1666 ExprKind::Unary(UnOp::Deref, _) => true,
1668 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1669 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1672 // Lang item paths cannot currently be local variables or statics.
1673 ExprKind::Path(QPath::LangItem(..)) => false,
1675 // Partially qualified paths in expressions can only legally
1676 // refer to associated items which are always rvalues.
1677 ExprKind::Path(QPath::TypeRelative(..))
1678 | ExprKind::Call(..)
1679 | ExprKind::MethodCall(..)
1680 | ExprKind::Struct(..)
1683 | ExprKind::Match(..)
1684 | ExprKind::Closure { .. }
1685 | ExprKind::Block(..)
1686 | ExprKind::Repeat(..)
1687 | ExprKind::Array(..)
1688 | ExprKind::Break(..)
1689 | ExprKind::Continue(..)
1692 | ExprKind::Loop(..)
1693 | ExprKind::Assign(..)
1694 | ExprKind::InlineAsm(..)
1695 | ExprKind::AssignOp(..)
1697 | ExprKind::ConstBlock(..)
1698 | ExprKind::Unary(..)
1700 | ExprKind::AddrOf(..)
1701 | ExprKind::Binary(..)
1702 | ExprKind::Yield(..)
1703 | ExprKind::Cast(..)
1704 | ExprKind::DropTemps(..)
1705 | ExprKind::Err => false,
1709 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1710 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1711 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1712 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1713 /// beyond remembering to call this function before doing analysis on it.
1714 pub fn peel_drop_temps(&self) -> &Self {
1715 let mut expr = self;
1716 while let ExprKind::DropTemps(inner) = &expr.kind {
1722 pub fn peel_blocks(&self) -> &Self {
1723 let mut expr = self;
1724 while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind {
1730 pub fn can_have_side_effects(&self) -> bool {
1731 match self.peel_drop_temps().kind {
1732 ExprKind::Path(_) | ExprKind::Lit(_) => false,
1733 ExprKind::Type(base, _)
1734 | ExprKind::Unary(_, base)
1735 | ExprKind::Field(base, _)
1736 | ExprKind::Index(base, _)
1737 | ExprKind::AddrOf(.., base)
1738 | ExprKind::Cast(base, _) => {
1739 // This isn't exactly true for `Index` and all `Unary`, but we are using this
1740 // method exclusively for diagnostics and there's a *cultural* pressure against
1741 // them being used only for its side-effects.
1742 base.can_have_side_effects()
1744 ExprKind::Struct(_, fields, init) => fields
1746 .map(|field| field.expr)
1747 .chain(init.into_iter())
1748 .all(|e| e.can_have_side_effects()),
1750 ExprKind::Array(args)
1751 | ExprKind::Tup(args)
1755 ExprKind::Path(QPath::Resolved(
1757 Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. },
1762 ) => args.iter().all(|arg| arg.can_have_side_effects()),
1764 | ExprKind::Match(..)
1765 | ExprKind::MethodCall(..)
1766 | ExprKind::Call(..)
1767 | ExprKind::Closure { .. }
1768 | ExprKind::Block(..)
1769 | ExprKind::Repeat(..)
1770 | ExprKind::Break(..)
1771 | ExprKind::Continue(..)
1774 | ExprKind::Loop(..)
1775 | ExprKind::Assign(..)
1776 | ExprKind::InlineAsm(..)
1777 | ExprKind::AssignOp(..)
1778 | ExprKind::ConstBlock(..)
1780 | ExprKind::Binary(..)
1781 | ExprKind::Yield(..)
1782 | ExprKind::DropTemps(..)
1783 | ExprKind::Err => true,
1787 // To a first-order approximation, is this a pattern
1788 pub fn is_approximately_pattern(&self) -> bool {
1791 | ExprKind::Array(_)
1792 | ExprKind::Call(..)
1796 | ExprKind::Struct(..) => true,
1801 pub fn method_ident(&self) -> Option<Ident> {
1803 ExprKind::MethodCall(receiver_method, ..) => Some(receiver_method.ident),
1804 ExprKind::Unary(_, expr) | ExprKind::AddrOf(.., expr) => expr.method_ident(),
1810 /// Checks if the specified expression is a built-in range literal.
1811 /// (See: `LoweringContext::lower_expr()`).
1812 pub fn is_range_literal(expr: &Expr<'_>) -> bool {
1814 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1815 ExprKind::Struct(ref qpath, _, _) => matches!(
1820 | LangItem::RangeFrom
1821 | LangItem::RangeFull
1822 | LangItem::RangeToInclusive,
1827 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1828 ExprKind::Call(ref func, _) => {
1829 matches!(func.kind, ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, ..)))
1836 #[derive(Debug, HashStable_Generic)]
1837 pub enum ExprKind<'hir> {
1838 /// A `box x` expression.
1839 Box(&'hir Expr<'hir>),
1840 /// Allow anonymous constants from an inline `const` block
1841 ConstBlock(AnonConst),
1842 /// An array (e.g., `[a, b, c, d]`).
1843 Array(&'hir [Expr<'hir>]),
1844 /// A function call.
1846 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1847 /// and the second field is the list of arguments.
1848 /// This also represents calling the constructor of
1849 /// tuple-like ADTs such as tuple structs and enum variants.
1850 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1851 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1853 /// The `PathSegment` represents the method name and its generic arguments
1854 /// (within the angle brackets).
1855 /// The `&Expr` is the expression that evaluates
1856 /// to the object on which the method is being called on (the receiver),
1857 /// and the `&[Expr]` is the rest of the arguments.
1858 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1859 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, x, [a, b, c, d], span)`.
1860 /// The final `Span` represents the span of the function and arguments
1861 /// (e.g. `foo::<Bar, Baz>(a, b, c, d)` in `x.foo::<Bar, Baz>(a, b, c, d)`
1863 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1864 /// the `hir_id` of the `MethodCall` node itself.
1866 /// [`type_dependent_def_id`]: ../../rustc_middle/ty/struct.TypeckResults.html#method.type_dependent_def_id
1867 MethodCall(&'hir PathSegment<'hir>, &'hir Expr<'hir>, &'hir [Expr<'hir>], Span),
1868 /// A tuple (e.g., `(a, b, c, d)`).
1869 Tup(&'hir [Expr<'hir>]),
1870 /// A binary operation (e.g., `a + b`, `a * b`).
1871 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1872 /// A unary operation (e.g., `!x`, `*x`).
1873 Unary(UnOp, &'hir Expr<'hir>),
1874 /// A literal (e.g., `1`, `"foo"`).
1876 /// A cast (e.g., `foo as f64`).
1877 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1878 /// A type reference (e.g., `Foo`).
1879 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1880 /// Wraps the expression in a terminating scope.
1881 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1883 /// This construct only exists to tweak the drop order in HIR lowering.
1884 /// An example of that is the desugaring of `for` loops.
1885 DropTemps(&'hir Expr<'hir>),
1886 /// A `let $pat = $expr` expression.
1888 /// These are not `Local` and only occur as expressions.
1889 /// The `let Some(x) = foo()` in `if let Some(x) = foo()` is an example of `Let(..)`.
1890 Let(&'hir Let<'hir>),
1891 /// An `if` block, with an optional else block.
1893 /// I.e., `if <expr> { <expr> } else { <expr> }`.
1894 If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
1895 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1897 /// I.e., `'label: loop { <block> }`.
1899 /// The `Span` is the loop header (`for x in y`/`while let pat = expr`).
1900 Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span),
1901 /// A `match` block, with a source that indicates whether or not it is
1902 /// the result of a desugaring, and if so, which kind.
1903 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1904 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1906 /// The `Span` is the argument block `|...|`.
1908 /// This may also be a generator literal or an `async block` as indicated by the
1909 /// `Option<Movability>`.
1910 Closure(&'hir Closure<'hir>),
1911 /// A block (e.g., `'label: { ... }`).
1912 Block(&'hir Block<'hir>, Option<Label>),
1914 /// An assignment (e.g., `a = foo()`).
1915 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1916 /// An assignment with an operator.
1919 AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1920 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1921 Field(&'hir Expr<'hir>, Ident),
1922 /// An indexing operation (`foo[2]`).
1923 Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1925 /// Path to a definition, possibly containing lifetime or type parameters.
1928 /// A referencing operation (i.e., `&a` or `&mut a`).
1929 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1930 /// A `break`, with an optional label to break.
1931 Break(Destination, Option<&'hir Expr<'hir>>),
1932 /// A `continue`, with an optional label.
1933 Continue(Destination),
1934 /// A `return`, with an optional value to be returned.
1935 Ret(Option<&'hir Expr<'hir>>),
1937 /// Inline assembly (from `asm!`), with its outputs and inputs.
1938 InlineAsm(&'hir InlineAsm<'hir>),
1940 /// A struct or struct-like variant literal expression.
1942 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1943 /// where `base` is the `Option<Expr>`.
1944 Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], Option<&'hir Expr<'hir>>),
1946 /// An array literal constructed from one repeated element.
1948 /// E.g., `[1; 5]`. The first expression is the element
1949 /// to be repeated; the second is the number of times to repeat it.
1950 Repeat(&'hir Expr<'hir>, ArrayLen),
1952 /// A suspension point for generators (i.e., `yield <expr>`).
1953 Yield(&'hir Expr<'hir>, YieldSource),
1955 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1959 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1961 /// To resolve the path to a `DefId`, call [`qpath_res`].
1963 /// [`qpath_res`]: ../../rustc_middle/ty/struct.TypeckResults.html#method.qpath_res
1964 #[derive(Debug, HashStable_Generic)]
1965 pub enum QPath<'hir> {
1966 /// Path to a definition, optionally "fully-qualified" with a `Self`
1967 /// type, if the path points to an associated item in a trait.
1969 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1970 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1971 /// even though they both have the same two-segment `Clone::clone` `Path`.
1972 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
1974 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1975 /// Will be resolved by type-checking to an associated item.
1977 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1978 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1979 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1980 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
1982 /// Reference to a `#[lang = "foo"]` item. `HirId` of the inner expr.
1983 LangItem(LangItem, Span, Option<HirId>),
1986 impl<'hir> QPath<'hir> {
1987 /// Returns the span of this `QPath`.
1988 pub fn span(&self) -> Span {
1990 QPath::Resolved(_, path) => path.span,
1991 QPath::TypeRelative(qself, ps) => qself.span.to(ps.ident.span),
1992 QPath::LangItem(_, span, _) => span,
1996 /// Returns the span of the qself of this `QPath`. For example, `()` in
1997 /// `<() as Trait>::method`.
1998 pub fn qself_span(&self) -> Span {
2000 QPath::Resolved(_, path) => path.span,
2001 QPath::TypeRelative(qself, _) => qself.span,
2002 QPath::LangItem(_, span, _) => span,
2006 /// Returns the span of the last segment of this `QPath`. For example, `method` in
2007 /// `<() as Trait>::method`.
2008 pub fn last_segment_span(&self) -> Span {
2010 QPath::Resolved(_, path) => path.segments.last().unwrap().ident.span,
2011 QPath::TypeRelative(_, segment) => segment.ident.span,
2012 QPath::LangItem(_, span, _) => span,
2017 /// Hints at the original code for a let statement.
2018 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2019 pub enum LocalSource {
2020 /// A `match _ { .. }`.
2022 /// When lowering async functions, we create locals within the `async move` so that
2023 /// all parameters are dropped after the future is polled.
2025 /// ```ignore (pseudo-Rust)
2026 /// async fn foo(<pattern> @ x: Type) {
2028 /// let <pattern> = x;
2033 /// A desugared `<expr>.await`.
2035 /// A desugared `expr = expr`, where the LHS is a tuple, struct or array.
2036 /// The span is that of the `=` sign.
2037 AssignDesugar(Span),
2040 /// Hints at the original code for a `match _ { .. }`.
2041 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
2042 #[derive(HashStable_Generic)]
2043 pub enum MatchSource {
2044 /// A `match _ { .. }`.
2046 /// A desugared `for _ in _ { .. }` loop.
2048 /// A desugared `?` operator.
2050 /// A desugared `<expr>.await`.
2056 pub const fn name(self) -> &'static str {
2060 ForLoopDesugar => "for",
2062 AwaitDesugar => ".await",
2067 /// The loop type that yielded an `ExprKind::Loop`.
2068 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2069 pub enum LoopSource {
2070 /// A `loop { .. }` loop.
2072 /// A `while _ { .. }` loop.
2074 /// A `for _ in _ { .. }` loop.
2079 pub fn name(self) -> &'static str {
2081 LoopSource::Loop => "loop",
2082 LoopSource::While => "while",
2083 LoopSource::ForLoop => "for",
2088 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2089 pub enum LoopIdError {
2091 UnlabeledCfInWhileCondition,
2095 impl fmt::Display for LoopIdError {
2096 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2097 f.write_str(match self {
2098 LoopIdError::OutsideLoopScope => "not inside loop scope",
2099 LoopIdError::UnlabeledCfInWhileCondition => {
2100 "unlabeled control flow (break or continue) in while condition"
2102 LoopIdError::UnresolvedLabel => "label not found",
2107 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2108 pub struct Destination {
2109 // This is `Some(_)` iff there is an explicit user-specified `label
2110 pub label: Option<Label>,
2112 // These errors are caught and then reported during the diagnostics pass in
2113 // librustc_passes/loops.rs
2114 pub target_id: Result<HirId, LoopIdError>,
2117 /// The yield kind that caused an `ExprKind::Yield`.
2118 #[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
2119 pub enum YieldSource {
2120 /// An `<expr>.await`.
2121 Await { expr: Option<HirId> },
2122 /// A plain `yield`.
2127 pub fn is_await(&self) -> bool {
2128 matches!(self, YieldSource::Await { .. })
2132 impl fmt::Display for YieldSource {
2133 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2134 f.write_str(match self {
2135 YieldSource::Await { .. } => "`await`",
2136 YieldSource::Yield => "`yield`",
2141 impl From<GeneratorKind> for YieldSource {
2142 fn from(kind: GeneratorKind) -> Self {
2144 // Guess based on the kind of the current generator.
2145 GeneratorKind::Gen => Self::Yield,
2146 GeneratorKind::Async(_) => Self::Await { expr: None },
2151 // N.B., if you change this, you'll probably want to change the corresponding
2152 // type structure in middle/ty.rs as well.
2153 #[derive(Debug, HashStable_Generic)]
2154 pub struct MutTy<'hir> {
2155 pub ty: &'hir Ty<'hir>,
2156 pub mutbl: Mutability,
2159 /// Represents a function's signature in a trait declaration,
2160 /// trait implementation, or a free function.
2161 #[derive(Debug, HashStable_Generic)]
2162 pub struct FnSig<'hir> {
2163 pub header: FnHeader,
2164 pub decl: &'hir FnDecl<'hir>,
2168 // The bodies for items are stored "out of line", in a separate
2169 // hashmap in the `Crate`. Here we just record the hir-id of the item
2170 // so it can fetched later.
2171 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2172 pub struct TraitItemId {
2173 pub def_id: LocalDefId,
2178 pub fn hir_id(&self) -> HirId {
2179 // Items are always HIR owners.
2180 HirId::make_owner(self.def_id)
2184 /// Represents an item declaration within a trait declaration,
2185 /// possibly including a default implementation. A trait item is
2186 /// either required (meaning it doesn't have an implementation, just a
2187 /// signature) or provided (meaning it has a default implementation).
2188 #[derive(Debug, HashStable_Generic)]
2189 pub struct TraitItem<'hir> {
2191 pub def_id: LocalDefId,
2192 pub generics: &'hir Generics<'hir>,
2193 pub kind: TraitItemKind<'hir>,
2195 pub defaultness: Defaultness,
2198 impl TraitItem<'_> {
2200 pub fn hir_id(&self) -> HirId {
2201 // Items are always HIR owners.
2202 HirId::make_owner(self.def_id)
2205 pub fn trait_item_id(&self) -> TraitItemId {
2206 TraitItemId { def_id: self.def_id }
2210 /// Represents a trait method's body (or just argument names).
2211 #[derive(Encodable, Debug, HashStable_Generic)]
2212 pub enum TraitFn<'hir> {
2213 /// No default body in the trait, just a signature.
2214 Required(&'hir [Ident]),
2216 /// Both signature and body are provided in the trait.
2220 /// Represents a trait method or associated constant or type
2221 #[derive(Debug, HashStable_Generic)]
2222 pub enum TraitItemKind<'hir> {
2223 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
2224 Const(&'hir Ty<'hir>, Option<BodyId>),
2225 /// An associated function with an optional body.
2226 Fn(FnSig<'hir>, TraitFn<'hir>),
2227 /// An associated type with (possibly empty) bounds and optional concrete
2229 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
2232 // The bodies for items are stored "out of line", in a separate
2233 // hashmap in the `Crate`. Here we just record the hir-id of the item
2234 // so it can fetched later.
2235 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2236 pub struct ImplItemId {
2237 pub def_id: LocalDefId,
2242 pub fn hir_id(&self) -> HirId {
2243 // Items are always HIR owners.
2244 HirId::make_owner(self.def_id)
2248 /// Represents anything within an `impl` block.
2249 #[derive(Debug, HashStable_Generic)]
2250 pub struct ImplItem<'hir> {
2252 pub def_id: LocalDefId,
2253 pub generics: &'hir Generics<'hir>,
2254 pub kind: ImplItemKind<'hir>,
2255 pub defaultness: Defaultness,
2262 pub fn hir_id(&self) -> HirId {
2263 // Items are always HIR owners.
2264 HirId::make_owner(self.def_id)
2267 pub fn impl_item_id(&self) -> ImplItemId {
2268 ImplItemId { def_id: self.def_id }
2272 /// Represents various kinds of content within an `impl`.
2273 #[derive(Debug, HashStable_Generic)]
2274 pub enum ImplItemKind<'hir> {
2275 /// An associated constant of the given type, set to the constant result
2276 /// of the expression.
2277 Const(&'hir Ty<'hir>, BodyId),
2278 /// An associated function implementation with the given signature and body.
2279 Fn(FnSig<'hir>, BodyId),
2280 /// An associated type.
2281 TyAlias(&'hir Ty<'hir>),
2284 // The name of the associated type for `Fn` return types.
2285 pub const FN_OUTPUT_NAME: Symbol = sym::Output;
2287 /// Bind a type to an associated type (i.e., `A = Foo`).
2289 /// Bindings like `A: Debug` are represented as a special type `A =
2290 /// $::Debug` that is understood by the astconv code.
2292 /// FIXME(alexreg): why have a separate type for the binding case,
2293 /// wouldn't it be better to make the `ty` field an enum like the
2296 /// ```ignore (pseudo-rust)
2297 /// enum TypeBindingKind {
2302 #[derive(Debug, HashStable_Generic)]
2303 pub struct TypeBinding<'hir> {
2306 pub gen_args: &'hir GenericArgs<'hir>,
2307 pub kind: TypeBindingKind<'hir>,
2311 #[derive(Debug, HashStable_Generic)]
2312 pub enum Term<'hir> {
2317 impl<'hir> From<&'hir Ty<'hir>> for Term<'hir> {
2318 fn from(ty: &'hir Ty<'hir>) -> Self {
2323 impl<'hir> From<AnonConst> for Term<'hir> {
2324 fn from(c: AnonConst) -> Self {
2329 // Represents the two kinds of type bindings.
2330 #[derive(Debug, HashStable_Generic)]
2331 pub enum TypeBindingKind<'hir> {
2332 /// E.g., `Foo<Bar: Send>`.
2333 Constraint { bounds: &'hir [GenericBound<'hir>] },
2334 /// E.g., `Foo<Bar = ()>`, `Foo<Bar = ()>`
2335 Equality { term: Term<'hir> },
2338 impl TypeBinding<'_> {
2339 pub fn ty(&self) -> &Ty<'_> {
2341 TypeBindingKind::Equality { term: Term::Ty(ref ty) } => ty,
2342 _ => panic!("expected equality type binding for parenthesized generic args"),
2345 pub fn opt_const(&self) -> Option<&'_ AnonConst> {
2347 TypeBindingKind::Equality { term: Term::Const(ref c) } => Some(c),
2353 #[derive(Debug, HashStable_Generic)]
2354 pub struct Ty<'hir> {
2356 pub kind: TyKind<'hir>,
2360 impl<'hir> Ty<'hir> {
2361 /// Returns `true` if `param_def_id` matches the `bounded_ty` of this predicate.
2362 pub fn as_generic_param(&self) -> Option<(DefId, Ident)> {
2363 let TyKind::Path(QPath::Resolved(None, path)) = self.kind else {
2366 let [segment] = &path.segments else {
2370 Res::Def(DefKind::TyParam, def_id)
2371 | Res::SelfTy { trait_: Some(def_id), alias_to: None } => Some((def_id, segment.ident)),
2377 /// Not represented directly in the AST; referred to by name through a `ty_path`.
2378 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
2379 #[derive(HashStable_Generic)]
2390 /// All of the primitive types
2391 pub const ALL: [Self; 17] = [
2392 // any changes here should also be reflected in `PrimTy::from_name`
2393 Self::Int(IntTy::I8),
2394 Self::Int(IntTy::I16),
2395 Self::Int(IntTy::I32),
2396 Self::Int(IntTy::I64),
2397 Self::Int(IntTy::I128),
2398 Self::Int(IntTy::Isize),
2399 Self::Uint(UintTy::U8),
2400 Self::Uint(UintTy::U16),
2401 Self::Uint(UintTy::U32),
2402 Self::Uint(UintTy::U64),
2403 Self::Uint(UintTy::U128),
2404 Self::Uint(UintTy::Usize),
2405 Self::Float(FloatTy::F32),
2406 Self::Float(FloatTy::F64),
2412 /// Like [`PrimTy::name`], but returns a &str instead of a symbol.
2415 pub fn name_str(self) -> &'static str {
2417 PrimTy::Int(i) => i.name_str(),
2418 PrimTy::Uint(u) => u.name_str(),
2419 PrimTy::Float(f) => f.name_str(),
2420 PrimTy::Str => "str",
2421 PrimTy::Bool => "bool",
2422 PrimTy::Char => "char",
2426 pub fn name(self) -> Symbol {
2428 PrimTy::Int(i) => i.name(),
2429 PrimTy::Uint(u) => u.name(),
2430 PrimTy::Float(f) => f.name(),
2431 PrimTy::Str => sym::str,
2432 PrimTy::Bool => sym::bool,
2433 PrimTy::Char => sym::char,
2437 /// Returns the matching `PrimTy` for a `Symbol` such as "str" or "i32".
2438 /// Returns `None` if no matching type is found.
2439 pub fn from_name(name: Symbol) -> Option<Self> {
2440 let ty = match name {
2441 // any changes here should also be reflected in `PrimTy::ALL`
2442 sym::i8 => Self::Int(IntTy::I8),
2443 sym::i16 => Self::Int(IntTy::I16),
2444 sym::i32 => Self::Int(IntTy::I32),
2445 sym::i64 => Self::Int(IntTy::I64),
2446 sym::i128 => Self::Int(IntTy::I128),
2447 sym::isize => Self::Int(IntTy::Isize),
2448 sym::u8 => Self::Uint(UintTy::U8),
2449 sym::u16 => Self::Uint(UintTy::U16),
2450 sym::u32 => Self::Uint(UintTy::U32),
2451 sym::u64 => Self::Uint(UintTy::U64),
2452 sym::u128 => Self::Uint(UintTy::U128),
2453 sym::usize => Self::Uint(UintTy::Usize),
2454 sym::f32 => Self::Float(FloatTy::F32),
2455 sym::f64 => Self::Float(FloatTy::F64),
2456 sym::bool => Self::Bool,
2457 sym::char => Self::Char,
2458 sym::str => Self::Str,
2465 #[derive(Debug, HashStable_Generic)]
2466 pub struct BareFnTy<'hir> {
2467 pub unsafety: Unsafety,
2469 pub generic_params: &'hir [GenericParam<'hir>],
2470 pub decl: &'hir FnDecl<'hir>,
2471 pub param_names: &'hir [Ident],
2474 #[derive(Debug, HashStable_Generic)]
2475 pub struct OpaqueTy<'hir> {
2476 pub generics: &'hir Generics<'hir>,
2477 pub bounds: GenericBounds<'hir>,
2478 pub origin: OpaqueTyOrigin,
2481 /// From whence the opaque type came.
2482 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2483 pub enum OpaqueTyOrigin {
2485 FnReturn(LocalDefId),
2487 AsyncFn(LocalDefId),
2488 /// type aliases: `type Foo = impl Trait;`
2492 /// The various kinds of types recognized by the compiler.
2493 #[derive(Debug, HashStable_Generic)]
2494 pub enum TyKind<'hir> {
2495 /// A variable length slice (i.e., `[T]`).
2496 Slice(&'hir Ty<'hir>),
2497 /// A fixed length array (i.e., `[T; n]`).
2498 Array(&'hir Ty<'hir>, ArrayLen),
2499 /// A raw pointer (i.e., `*const T` or `*mut T`).
2501 /// A reference (i.e., `&'a T` or `&'a mut T`).
2502 Rptr(Lifetime, MutTy<'hir>),
2503 /// A bare function (e.g., `fn(usize) -> bool`).
2504 BareFn(&'hir BareFnTy<'hir>),
2505 /// The never type (`!`).
2507 /// A tuple (`(A, B, C, D, ...)`).
2508 Tup(&'hir [Ty<'hir>]),
2509 /// A path to a type definition (`module::module::...::Type`), or an
2510 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2512 /// Type parameters may be stored in each `PathSegment`.
2514 /// An opaque type definition itself. This is only used for `impl Trait`.
2516 /// The generic argument list contains the lifetimes (and in the future
2517 /// possibly parameters) that are actually bound on the `impl Trait`.
2518 OpaqueDef(ItemId, &'hir [GenericArg<'hir>]),
2519 /// A trait object type `Bound1 + Bound2 + Bound3`
2520 /// where `Bound` is a trait or a lifetime.
2521 TraitObject(&'hir [PolyTraitRef<'hir>], Lifetime, TraitObjectSyntax),
2524 /// `TyKind::Infer` means the type should be inferred instead of it having been
2525 /// specified. This can appear anywhere in a type.
2527 /// Placeholder for a type that has failed to be defined.
2531 #[derive(Debug, HashStable_Generic)]
2532 pub enum InlineAsmOperand<'hir> {
2534 reg: InlineAsmRegOrRegClass,
2535 expr: &'hir Expr<'hir>,
2538 reg: InlineAsmRegOrRegClass,
2540 expr: Option<&'hir Expr<'hir>>,
2543 reg: InlineAsmRegOrRegClass,
2545 expr: &'hir Expr<'hir>,
2548 reg: InlineAsmRegOrRegClass,
2550 in_expr: &'hir Expr<'hir>,
2551 out_expr: Option<&'hir Expr<'hir>>,
2554 anon_const: AnonConst,
2557 anon_const: AnonConst,
2565 impl<'hir> InlineAsmOperand<'hir> {
2566 pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
2568 Self::In { reg, .. }
2569 | Self::Out { reg, .. }
2570 | Self::InOut { reg, .. }
2571 | Self::SplitInOut { reg, .. } => Some(reg),
2572 Self::Const { .. } | Self::SymFn { .. } | Self::SymStatic { .. } => None,
2576 pub fn is_clobber(&self) -> bool {
2579 InlineAsmOperand::Out { reg: InlineAsmRegOrRegClass::Reg(_), late: _, expr: None }
2584 #[derive(Debug, HashStable_Generic)]
2585 pub struct InlineAsm<'hir> {
2586 pub template: &'hir [InlineAsmTemplatePiece],
2587 pub template_strs: &'hir [(Symbol, Option<Symbol>, Span)],
2588 pub operands: &'hir [(InlineAsmOperand<'hir>, Span)],
2589 pub options: InlineAsmOptions,
2590 pub line_spans: &'hir [Span],
2593 /// Represents a parameter in a function header.
2594 #[derive(Debug, HashStable_Generic)]
2595 pub struct Param<'hir> {
2597 pub pat: &'hir Pat<'hir>,
2602 /// Represents the header (not the body) of a function declaration.
2603 #[derive(Debug, HashStable_Generic)]
2604 pub struct FnDecl<'hir> {
2605 /// The types of the function's parameters.
2607 /// Additional argument data is stored in the function's [body](Body::params).
2608 pub inputs: &'hir [Ty<'hir>],
2609 pub output: FnRetTy<'hir>,
2610 pub c_variadic: bool,
2611 /// Does the function have an implicit self?
2612 pub implicit_self: ImplicitSelfKind,
2615 /// Represents what type of implicit self a function has, if any.
2616 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2617 pub enum ImplicitSelfKind {
2618 /// Represents a `fn x(self);`.
2620 /// Represents a `fn x(mut self);`.
2622 /// Represents a `fn x(&self);`.
2624 /// Represents a `fn x(&mut self);`.
2626 /// Represents when a function does not have a self argument or
2627 /// when a function has a `self: X` argument.
2631 impl ImplicitSelfKind {
2632 /// Does this represent an implicit self?
2633 pub fn has_implicit_self(&self) -> bool {
2634 !matches!(*self, ImplicitSelfKind::None)
2638 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable, Debug)]
2639 #[derive(HashStable_Generic)]
2645 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable, HashStable_Generic)]
2646 pub enum Defaultness {
2647 Default { has_value: bool },
2652 pub fn has_value(&self) -> bool {
2654 Defaultness::Default { has_value } => has_value,
2655 Defaultness::Final => true,
2659 pub fn is_final(&self) -> bool {
2660 *self == Defaultness::Final
2663 pub fn is_default(&self) -> bool {
2664 matches!(*self, Defaultness::Default { .. })
2668 #[derive(Debug, HashStable_Generic)]
2669 pub enum FnRetTy<'hir> {
2670 /// Return type is not specified.
2672 /// Functions default to `()` and
2673 /// closures default to inference. Span points to where return
2674 /// type would be inserted.
2675 DefaultReturn(Span),
2676 /// Everything else.
2677 Return(&'hir Ty<'hir>),
2682 pub fn span(&self) -> Span {
2684 Self::DefaultReturn(span) => span,
2685 Self::Return(ref ty) => ty.span,
2690 /// Represents `for<...>` binder before a closure
2691 #[derive(Copy, Clone, Debug, HashStable_Generic)]
2692 pub enum ClosureBinder {
2693 /// Binder is not specified.
2695 /// Binder is specified.
2697 /// Span points to the whole `for<...>`.
2701 #[derive(Encodable, Debug, HashStable_Generic)]
2702 pub struct Mod<'hir> {
2703 pub spans: ModSpans,
2704 pub item_ids: &'hir [ItemId],
2707 #[derive(Copy, Clone, Debug, HashStable_Generic, Encodable)]
2708 pub struct ModSpans {
2709 /// A span from the first token past `{` to the last token until `}`.
2710 /// For `mod foo;`, the inner span ranges from the first token
2711 /// to the last token in the external file.
2712 pub inner_span: Span,
2713 pub inject_use_span: Span,
2716 #[derive(Debug, HashStable_Generic)]
2717 pub struct EnumDef<'hir> {
2718 pub variants: &'hir [Variant<'hir>],
2721 #[derive(Debug, HashStable_Generic)]
2722 pub struct Variant<'hir> {
2723 /// Name of the variant.
2725 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2727 /// Fields and constructor id of the variant.
2728 pub data: VariantData<'hir>,
2729 /// Explicit discriminant (e.g., `Foo = 1`).
2730 pub disr_expr: Option<AnonConst>,
2735 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2737 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2738 /// Also produced for each element of a list `use`, e.g.
2739 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2742 /// Glob import, e.g., `use foo::*`.
2745 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2746 /// an additional `use foo::{}` for performing checks such as
2747 /// unstable feature gating. May be removed in the future.
2751 /// References to traits in impls.
2753 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2754 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2755 /// trait being referred to but just a unique `HirId` that serves as a key
2756 /// within the resolution map.
2757 #[derive(Clone, Debug, HashStable_Generic)]
2758 pub struct TraitRef<'hir> {
2759 pub path: &'hir Path<'hir>,
2760 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2761 #[stable_hasher(ignore)]
2762 pub hir_ref_id: HirId,
2766 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2767 pub fn trait_def_id(&self) -> Option<DefId> {
2768 match self.path.res {
2769 Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
2771 _ => unreachable!(),
2776 #[derive(Clone, Debug, HashStable_Generic)]
2777 pub struct PolyTraitRef<'hir> {
2778 /// The `'a` in `for<'a> Foo<&'a T>`.
2779 pub bound_generic_params: &'hir [GenericParam<'hir>],
2781 /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
2782 pub trait_ref: TraitRef<'hir>,
2787 #[derive(Debug, HashStable_Generic)]
2788 pub struct FieldDef<'hir> {
2793 pub ty: &'hir Ty<'hir>,
2797 // Still necessary in couple of places
2798 pub fn is_positional(&self) -> bool {
2799 let first = self.ident.as_str().as_bytes()[0];
2800 (b'0'..=b'9').contains(&first)
2804 /// Fields and constructor IDs of enum variants and structs.
2805 #[derive(Debug, HashStable_Generic)]
2806 pub enum VariantData<'hir> {
2807 /// A struct variant.
2809 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2810 Struct(&'hir [FieldDef<'hir>], /* recovered */ bool),
2811 /// A tuple variant.
2813 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2814 Tuple(&'hir [FieldDef<'hir>], HirId),
2817 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2821 impl<'hir> VariantData<'hir> {
2822 /// Return the fields of this variant.
2823 pub fn fields(&self) -> &'hir [FieldDef<'hir>] {
2825 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2830 /// Return the `HirId` of this variant's constructor, if it has one.
2831 pub fn ctor_hir_id(&self) -> Option<HirId> {
2833 VariantData::Struct(_, _) => None,
2834 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2839 // The bodies for items are stored "out of line", in a separate
2840 // hashmap in the `Crate`. Here we just record the hir-id of the item
2841 // so it can fetched later.
2842 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
2844 pub def_id: LocalDefId,
2849 pub fn hir_id(&self) -> HirId {
2850 // Items are always HIR owners.
2851 HirId::make_owner(self.def_id)
2857 /// The name might be a dummy name in case of anonymous items
2858 #[derive(Debug, HashStable_Generic)]
2859 pub struct Item<'hir> {
2861 pub def_id: LocalDefId,
2862 pub kind: ItemKind<'hir>,
2869 pub fn hir_id(&self) -> HirId {
2870 // Items are always HIR owners.
2871 HirId::make_owner(self.def_id)
2874 pub fn item_id(&self) -> ItemId {
2875 ItemId { def_id: self.def_id }
2879 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2880 #[derive(Encodable, Decodable, HashStable_Generic)]
2887 pub fn prefix_str(&self) -> &'static str {
2889 Self::Unsafe => "unsafe ",
2895 impl fmt::Display for Unsafety {
2896 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2897 f.write_str(match *self {
2898 Self::Unsafe => "unsafe",
2899 Self::Normal => "normal",
2904 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2905 #[derive(Encodable, Decodable, HashStable_Generic)]
2906 pub enum Constness {
2911 impl fmt::Display for Constness {
2912 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2913 f.write_str(match *self {
2914 Self::Const => "const",
2915 Self::NotConst => "non-const",
2920 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2921 pub struct FnHeader {
2922 pub unsafety: Unsafety,
2923 pub constness: Constness,
2924 pub asyncness: IsAsync,
2929 pub fn is_async(&self) -> bool {
2930 matches!(&self.asyncness, IsAsync::Async)
2933 pub fn is_const(&self) -> bool {
2934 matches!(&self.constness, Constness::Const)
2937 pub fn is_unsafe(&self) -> bool {
2938 matches!(&self.unsafety, Unsafety::Unsafe)
2942 #[derive(Debug, HashStable_Generic)]
2943 pub enum ItemKind<'hir> {
2944 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2946 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2947 ExternCrate(Option<Symbol>),
2949 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2953 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2954 Use(&'hir Path<'hir>, UseKind),
2956 /// A `static` item.
2957 Static(&'hir Ty<'hir>, Mutability, BodyId),
2959 Const(&'hir Ty<'hir>, BodyId),
2960 /// A function declaration.
2961 Fn(FnSig<'hir>, &'hir Generics<'hir>, BodyId),
2962 /// A MBE macro definition (`macro_rules!` or `macro`).
2963 Macro(ast::MacroDef, MacroKind),
2965 Mod(&'hir Mod<'hir>),
2966 /// An external module, e.g. `extern { .. }`.
2967 ForeignMod { abi: Abi, items: &'hir [ForeignItemRef] },
2968 /// Module-level inline assembly (from `global_asm!`).
2969 GlobalAsm(&'hir InlineAsm<'hir>),
2970 /// A type alias, e.g., `type Foo = Bar<u8>`.
2971 TyAlias(&'hir Ty<'hir>, &'hir Generics<'hir>),
2972 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2973 OpaqueTy(OpaqueTy<'hir>),
2974 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2975 Enum(EnumDef<'hir>, &'hir Generics<'hir>),
2976 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2977 Struct(VariantData<'hir>, &'hir Generics<'hir>),
2978 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2979 Union(VariantData<'hir>, &'hir Generics<'hir>),
2980 /// A trait definition.
2981 Trait(IsAuto, Unsafety, &'hir Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
2983 TraitAlias(&'hir Generics<'hir>, GenericBounds<'hir>),
2985 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2986 Impl(&'hir Impl<'hir>),
2989 #[derive(Debug, HashStable_Generic)]
2990 pub struct Impl<'hir> {
2991 pub unsafety: Unsafety,
2992 pub polarity: ImplPolarity,
2993 pub defaultness: Defaultness,
2994 // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata
2995 // decoding as `Span`s cannot be decoded when a `Session` is not available.
2996 pub defaultness_span: Option<Span>,
2997 pub constness: Constness,
2998 pub generics: &'hir Generics<'hir>,
3000 /// The trait being implemented, if any.
3001 pub of_trait: Option<TraitRef<'hir>>,
3003 pub self_ty: &'hir Ty<'hir>,
3004 pub items: &'hir [ImplItemRef],
3008 pub fn generics(&self) -> Option<&Generics<'_>> {
3010 ItemKind::Fn(_, ref generics, _)
3011 | ItemKind::TyAlias(_, ref generics)
3012 | ItemKind::OpaqueTy(OpaqueTy { ref generics, .. })
3013 | ItemKind::Enum(_, ref generics)
3014 | ItemKind::Struct(_, ref generics)
3015 | ItemKind::Union(_, ref generics)
3016 | ItemKind::Trait(_, _, ref generics, _, _)
3017 | ItemKind::TraitAlias(ref generics, _)
3018 | ItemKind::Impl(Impl { ref generics, .. }) => generics,
3023 pub fn descr(&self) -> &'static str {
3025 ItemKind::ExternCrate(..) => "extern crate",
3026 ItemKind::Use(..) => "`use` import",
3027 ItemKind::Static(..) => "static item",
3028 ItemKind::Const(..) => "constant item",
3029 ItemKind::Fn(..) => "function",
3030 ItemKind::Macro(..) => "macro",
3031 ItemKind::Mod(..) => "module",
3032 ItemKind::ForeignMod { .. } => "extern block",
3033 ItemKind::GlobalAsm(..) => "global asm item",
3034 ItemKind::TyAlias(..) => "type alias",
3035 ItemKind::OpaqueTy(..) => "opaque type",
3036 ItemKind::Enum(..) => "enum",
3037 ItemKind::Struct(..) => "struct",
3038 ItemKind::Union(..) => "union",
3039 ItemKind::Trait(..) => "trait",
3040 ItemKind::TraitAlias(..) => "trait alias",
3041 ItemKind::Impl(..) => "implementation",
3046 /// A reference from an trait to one of its associated items. This
3047 /// contains the item's id, naturally, but also the item's name and
3048 /// some other high-level details (like whether it is an associated
3049 /// type or method, and whether it is public). This allows other
3050 /// passes to find the impl they want without loading the ID (which
3051 /// means fewer edges in the incremental compilation graph).
3052 #[derive(Encodable, Debug, HashStable_Generic)]
3053 pub struct TraitItemRef {
3054 pub id: TraitItemId,
3056 pub kind: AssocItemKind,
3060 /// A reference from an impl to one of its associated items. This
3061 /// contains the item's ID, naturally, but also the item's name and
3062 /// some other high-level details (like whether it is an associated
3063 /// type or method, and whether it is public). This allows other
3064 /// passes to find the impl they want without loading the ID (which
3065 /// means fewer edges in the incremental compilation graph).
3066 #[derive(Debug, HashStable_Generic)]
3067 pub struct ImplItemRef {
3070 pub kind: AssocItemKind,
3072 /// When we are in a trait impl, link to the trait-item's id.
3073 pub trait_item_def_id: Option<DefId>,
3076 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
3077 pub enum AssocItemKind {
3079 Fn { has_self: bool },
3083 // The bodies for items are stored "out of line", in a separate
3084 // hashmap in the `Crate`. Here we just record the hir-id of the item
3085 // so it can fetched later.
3086 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3087 pub struct ForeignItemId {
3088 pub def_id: LocalDefId,
3091 impl ForeignItemId {
3093 pub fn hir_id(&self) -> HirId {
3094 // Items are always HIR owners.
3095 HirId::make_owner(self.def_id)
3099 /// A reference from a foreign block to one of its items. This
3100 /// contains the item's ID, naturally, but also the item's name and
3101 /// some other high-level details (like whether it is an associated
3102 /// type or method, and whether it is public). This allows other
3103 /// passes to find the impl they want without loading the ID (which
3104 /// means fewer edges in the incremental compilation graph).
3105 #[derive(Debug, HashStable_Generic)]
3106 pub struct ForeignItemRef {
3107 pub id: ForeignItemId,
3112 #[derive(Debug, HashStable_Generic)]
3113 pub struct ForeignItem<'hir> {
3115 pub kind: ForeignItemKind<'hir>,
3116 pub def_id: LocalDefId,
3121 impl ForeignItem<'_> {
3123 pub fn hir_id(&self) -> HirId {
3124 // Items are always HIR owners.
3125 HirId::make_owner(self.def_id)
3128 pub fn foreign_item_id(&self) -> ForeignItemId {
3129 ForeignItemId { def_id: self.def_id }
3133 /// An item within an `extern` block.
3134 #[derive(Debug, HashStable_Generic)]
3135 pub enum ForeignItemKind<'hir> {
3136 /// A foreign function.
3137 Fn(&'hir FnDecl<'hir>, &'hir [Ident], &'hir Generics<'hir>),
3138 /// A foreign static item (`static ext: u8`).
3139 Static(&'hir Ty<'hir>, Mutability),
3144 /// A variable captured by a closure.
3145 #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)]
3147 // First span where it is accessed (there can be multiple).
3151 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
3152 // has length > 0 if the trait is found through an chain of imports, starting with the
3153 // import/use statement in the scope where the trait is used.
3154 #[derive(Encodable, Decodable, Clone, Debug, HashStable_Generic)]
3155 pub struct TraitCandidate {
3157 pub import_ids: SmallVec<[LocalDefId; 1]>,
3160 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3161 pub enum OwnerNode<'hir> {
3162 Item(&'hir Item<'hir>),
3163 ForeignItem(&'hir ForeignItem<'hir>),
3164 TraitItem(&'hir TraitItem<'hir>),
3165 ImplItem(&'hir ImplItem<'hir>),
3166 Crate(&'hir Mod<'hir>),
3169 impl<'hir> OwnerNode<'hir> {
3170 pub fn ident(&self) -> Option<Ident> {
3172 OwnerNode::Item(Item { ident, .. })
3173 | OwnerNode::ForeignItem(ForeignItem { ident, .. })
3174 | OwnerNode::ImplItem(ImplItem { ident, .. })
3175 | OwnerNode::TraitItem(TraitItem { ident, .. }) => Some(*ident),
3176 OwnerNode::Crate(..) => None,
3180 pub fn span(&self) -> Span {
3182 OwnerNode::Item(Item { span, .. })
3183 | OwnerNode::ForeignItem(ForeignItem { span, .. })
3184 | OwnerNode::ImplItem(ImplItem { span, .. })
3185 | OwnerNode::TraitItem(TraitItem { span, .. }) => *span,
3186 OwnerNode::Crate(Mod { spans: ModSpans { inner_span, .. }, .. }) => *inner_span,
3190 pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
3192 OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3193 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3194 | OwnerNode::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3195 OwnerNode::ForeignItem(ForeignItem {
3196 kind: ForeignItemKind::Fn(fn_decl, _, _),
3198 }) => Some(fn_decl),
3203 pub fn body_id(&self) -> Option<BodyId> {
3205 OwnerNode::TraitItem(TraitItem {
3206 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3209 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3210 | OwnerNode::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3215 pub fn generics(self) -> Option<&'hir Generics<'hir>> {
3216 Node::generics(self.into())
3219 pub fn def_id(self) -> LocalDefId {
3221 OwnerNode::Item(Item { def_id, .. })
3222 | OwnerNode::TraitItem(TraitItem { def_id, .. })
3223 | OwnerNode::ImplItem(ImplItem { def_id, .. })
3224 | OwnerNode::ForeignItem(ForeignItem { def_id, .. }) => *def_id,
3225 OwnerNode::Crate(..) => crate::CRATE_HIR_ID.owner,
3229 pub fn expect_item(self) -> &'hir Item<'hir> {
3231 OwnerNode::Item(n) => n,
3236 pub fn expect_foreign_item(self) -> &'hir ForeignItem<'hir> {
3238 OwnerNode::ForeignItem(n) => n,
3243 pub fn expect_impl_item(self) -> &'hir ImplItem<'hir> {
3245 OwnerNode::ImplItem(n) => n,
3250 pub fn expect_trait_item(self) -> &'hir TraitItem<'hir> {
3252 OwnerNode::TraitItem(n) => n,
3258 impl<'hir> Into<OwnerNode<'hir>> for &'hir Item<'hir> {
3259 fn into(self) -> OwnerNode<'hir> {
3260 OwnerNode::Item(self)
3264 impl<'hir> Into<OwnerNode<'hir>> for &'hir ForeignItem<'hir> {
3265 fn into(self) -> OwnerNode<'hir> {
3266 OwnerNode::ForeignItem(self)
3270 impl<'hir> Into<OwnerNode<'hir>> for &'hir ImplItem<'hir> {
3271 fn into(self) -> OwnerNode<'hir> {
3272 OwnerNode::ImplItem(self)
3276 impl<'hir> Into<OwnerNode<'hir>> for &'hir TraitItem<'hir> {
3277 fn into(self) -> OwnerNode<'hir> {
3278 OwnerNode::TraitItem(self)
3282 impl<'hir> Into<Node<'hir>> for OwnerNode<'hir> {
3283 fn into(self) -> Node<'hir> {
3285 OwnerNode::Item(n) => Node::Item(n),
3286 OwnerNode::ForeignItem(n) => Node::ForeignItem(n),
3287 OwnerNode::ImplItem(n) => Node::ImplItem(n),
3288 OwnerNode::TraitItem(n) => Node::TraitItem(n),
3289 OwnerNode::Crate(n) => Node::Crate(n),
3294 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3295 pub enum Node<'hir> {
3296 Param(&'hir Param<'hir>),
3297 Item(&'hir Item<'hir>),
3298 ForeignItem(&'hir ForeignItem<'hir>),
3299 TraitItem(&'hir TraitItem<'hir>),
3300 ImplItem(&'hir ImplItem<'hir>),
3301 Variant(&'hir Variant<'hir>),
3302 Field(&'hir FieldDef<'hir>),
3303 AnonConst(&'hir AnonConst),
3304 Expr(&'hir Expr<'hir>),
3305 ExprField(&'hir ExprField<'hir>),
3306 Stmt(&'hir Stmt<'hir>),
3307 PathSegment(&'hir PathSegment<'hir>),
3309 TypeBinding(&'hir TypeBinding<'hir>),
3310 TraitRef(&'hir TraitRef<'hir>),
3311 Pat(&'hir Pat<'hir>),
3312 PatField(&'hir PatField<'hir>),
3313 Arm(&'hir Arm<'hir>),
3314 Block(&'hir Block<'hir>),
3315 Local(&'hir Local<'hir>),
3317 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
3318 /// with synthesized constructors.
3319 Ctor(&'hir VariantData<'hir>),
3321 Lifetime(&'hir Lifetime),
3322 GenericParam(&'hir GenericParam<'hir>),
3324 Crate(&'hir Mod<'hir>),
3326 Infer(&'hir InferArg),
3329 impl<'hir> Node<'hir> {
3330 /// Get the identifier of this `Node`, if applicable.
3334 /// Calling `.ident()` on a [`Node::Ctor`] will return `None`
3335 /// because `Ctor`s do not have identifiers themselves.
3336 /// Instead, call `.ident()` on the parent struct/variant, like so:
3338 /// ```ignore (illustrative)
3341 /// .and_then(|ctor_id| tcx.hir().find(tcx.hir().get_parent_node(ctor_id)))
3342 /// .and_then(|parent| parent.ident())
3344 pub fn ident(&self) -> Option<Ident> {
3346 Node::TraitItem(TraitItem { ident, .. })
3347 | Node::ImplItem(ImplItem { ident, .. })
3348 | Node::ForeignItem(ForeignItem { ident, .. })
3349 | Node::Field(FieldDef { ident, .. })
3350 | Node::Variant(Variant { ident, .. })
3351 | Node::Item(Item { ident, .. })
3352 | Node::PathSegment(PathSegment { ident, .. }) => Some(*ident),
3353 Node::Lifetime(lt) => Some(lt.name.ident()),
3354 Node::GenericParam(p) => Some(p.name.ident()),
3355 Node::TypeBinding(b) => Some(b.ident),
3357 | Node::AnonConst(..)
3363 | Node::PatField(..)
3364 | Node::ExprField(..)
3369 | Node::TraitRef(..)
3370 | Node::Infer(..) => None,
3374 pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
3376 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3377 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3378 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3379 Node::Expr(Expr { kind: ExprKind::Closure(Closure { fn_decl, .. }), .. })
3380 | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
3387 pub fn fn_sig(self) -> Option<&'hir FnSig<'hir>> {
3389 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3390 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3391 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig),
3396 pub fn body_id(&self) -> Option<BodyId> {
3398 Node::TraitItem(TraitItem {
3399 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3402 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3403 | Node::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3408 pub fn generics(self) -> Option<&'hir Generics<'hir>> {
3410 Node::ForeignItem(ForeignItem {
3411 kind: ForeignItemKind::Fn(_, _, generics), ..
3413 | Node::TraitItem(TraitItem { generics, .. })
3414 | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
3415 Node::Item(item) => item.kind.generics(),
3420 pub fn as_owner(self) -> Option<OwnerNode<'hir>> {
3422 Node::Item(i) => Some(OwnerNode::Item(i)),
3423 Node::ForeignItem(i) => Some(OwnerNode::ForeignItem(i)),
3424 Node::TraitItem(i) => Some(OwnerNode::TraitItem(i)),
3425 Node::ImplItem(i) => Some(OwnerNode::ImplItem(i)),
3426 Node::Crate(i) => Some(OwnerNode::Crate(i)),
3431 pub fn fn_kind(self) -> Option<FnKind<'hir>> {
3433 Node::Item(i) => match i.kind {
3434 ItemKind::Fn(ref sig, ref generics, _) => {
3435 Some(FnKind::ItemFn(i.ident, generics, sig.header))
3439 Node::TraitItem(ti) => match ti.kind {
3440 TraitItemKind::Fn(ref sig, TraitFn::Provided(_)) => {
3441 Some(FnKind::Method(ti.ident, sig))
3445 Node::ImplItem(ii) => match ii.kind {
3446 ImplItemKind::Fn(ref sig, _) => Some(FnKind::Method(ii.ident, sig)),
3449 Node::Expr(e) => match e.kind {
3450 ExprKind::Closure { .. } => Some(FnKind::Closure),
3457 /// Get the fields for the tuple-constructor,
3458 /// if this node is a tuple constructor, otherwise None
3459 pub fn tuple_fields(&self) -> Option<&'hir [FieldDef<'hir>]> {
3460 if let Node::Ctor(&VariantData::Tuple(fields, _)) = self { Some(fields) } else { None }
3464 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3465 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
3468 // These are in alphabetical order, which is easy to maintain.
3469 static_assert_size!(Block<'_>, 48);
3470 static_assert_size!(Body<'_>, 32);
3471 static_assert_size!(Expr<'_>, 64);
3472 static_assert_size!(ExprKind<'_>, 48);
3473 static_assert_size!(FnDecl<'_>, 40);
3474 static_assert_size!(ForeignItem<'_>, 72);
3475 static_assert_size!(ForeignItemKind<'_>, 40);
3476 #[cfg(not(bootstrap))]
3477 static_assert_size!(GenericArg<'_>, 32);
3478 static_assert_size!(GenericBound<'_>, 48);
3479 static_assert_size!(Generics<'_>, 56);
3480 static_assert_size!(Impl<'_>, 80);
3481 #[cfg(not(bootstrap))]
3482 static_assert_size!(ImplItem<'_>, 80);
3483 #[cfg(not(bootstrap))]
3484 static_assert_size!(ImplItemKind<'_>, 32);
3485 static_assert_size!(Item<'_>, 80);
3486 static_assert_size!(ItemKind<'_>, 48);
3487 static_assert_size!(Local<'_>, 64);
3488 static_assert_size!(Param<'_>, 32);
3489 static_assert_size!(Pat<'_>, 88);
3490 static_assert_size!(PatKind<'_>, 64);
3491 static_assert_size!(Path<'_>, 48);
3492 static_assert_size!(PathSegment<'_>, 56);
3493 static_assert_size!(QPath<'_>, 24);
3494 static_assert_size!(Stmt<'_>, 32);
3495 static_assert_size!(StmtKind<'_>, 16);
3496 #[cfg(not(bootstrap))]
3497 static_assert_size!(TraitItem<'static>, 88);
3498 #[cfg(not(bootstrap))]
3499 static_assert_size!(TraitItemKind<'_>, 48);
3500 static_assert_size!(Ty<'_>, 72);
3501 static_assert_size!(TyKind<'_>, 56);