1 use crate::def::{CtorKind, DefKind, Res};
2 use crate::def_id::DefId;
3 pub(crate) use crate::hir_id::{HirId, ItemLocalId, OwnerId};
4 use crate::intravisit::FnKind;
8 use rustc_ast::util::parser::ExprPrecedence;
9 use rustc_ast::{Attribute, FloatTy, IntTy, Label, LitKind, TraitObjectSyntax, UintTy};
10 pub use rustc_ast::{BindingAnnotation, BorrowKind, ByRef, ImplPolarity, IsAuto};
11 pub use rustc_ast::{CaptureBy, Movability, Mutability};
12 use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
13 use rustc_data_structures::fingerprint::Fingerprint;
14 use rustc_data_structures::fx::FxHashMap;
15 use rustc_data_structures::sorted_map::SortedMap;
16 use rustc_error_messages::MultiSpan;
17 use rustc_index::vec::IndexVec;
18 use rustc_macros::HashStable_Generic;
19 use rustc_span::hygiene::MacroKind;
20 use rustc_span::source_map::Spanned;
21 use rustc_span::symbol::{kw, sym, Ident, Symbol};
22 use rustc_span::{def_id::LocalDefId, BytePos, Span, DUMMY_SP};
23 use rustc_target::asm::InlineAsmRegOrRegClass;
24 use rustc_target::spec::abi::Abi;
26 use smallvec::SmallVec;
29 #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)]
34 /// Either "`'a`", referring to a named lifetime definition,
35 /// or "``" (i.e., `kw::Empty`), for elision placeholders.
37 /// HIR lowering inserts these placeholders in type paths that
38 /// refer to type definitions needing lifetime parameters,
39 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
40 pub name: LifetimeName,
43 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
44 #[derive(HashStable_Generic)]
46 /// Some user-given name like `T` or `'x`.
49 /// Synthetic name generated when user elided a lifetime in an impl header.
51 /// E.g., the lifetimes in cases like these:
52 /// ```ignore (fragment)
54 /// impl Foo<'_> for u32
56 /// in that case, we rewrite to
57 /// ```ignore (fragment)
58 /// impl<'f> Foo for &'f u32
59 /// impl<'f> Foo<'f> for u32
61 /// where `'f` is something like `Fresh(0)`. The indices are
62 /// unique per impl, but not necessarily continuous.
65 /// Indicates an illegal name was given and an error has been
66 /// reported (so we should squelch other derived errors). Occurs
67 /// when, e.g., `'_` is used in the wrong place.
72 pub fn ident(&self) -> Ident {
74 ParamName::Plain(ident) => ident,
75 ParamName::Fresh | ParamName::Error => Ident::with_dummy_span(kw::UnderscoreLifetime),
79 pub fn normalize_to_macros_2_0(&self) -> ParamName {
81 ParamName::Plain(ident) => ParamName::Plain(ident.normalize_to_macros_2_0()),
82 param_name => param_name,
87 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
88 #[derive(HashStable_Generic)]
89 pub enum LifetimeName {
90 /// User-given names or fresh (synthetic) names.
91 Param(LocalDefId, ParamName),
93 /// Implicit lifetime in a context like `dyn Foo`. This is
94 /// distinguished from implicit lifetimes elsewhere because the
95 /// lifetime that they default to must appear elsewhere within the
96 /// enclosing type. This means that, in an `impl Trait` context, we
97 /// don't have to create a parameter for them. That is, `impl
98 /// Trait<Item = &u32>` expands to an opaque type like `type
99 /// Foo<'a> = impl Trait<Item = &'a u32>`, but `impl Trait<item =
100 /// dyn Bar>` expands to `type Foo = impl Trait<Item = dyn Bar +
101 /// 'static>`. The latter uses `ImplicitObjectLifetimeDefault` so
102 /// that surrounding code knows not to create a lifetime
104 ImplicitObjectLifetimeDefault,
106 /// Indicates an error during lowering (usually `'_` in wrong place)
107 /// that was already reported.
110 /// User wrote an anonymous lifetime, either `'_` or nothing.
111 /// The semantics of this lifetime should be inferred by typechecking code.
114 /// User wrote `'static`.
119 pub fn ident(&self) -> Ident {
121 LifetimeName::ImplicitObjectLifetimeDefault | LifetimeName::Error => Ident::empty(),
122 LifetimeName::Infer => Ident::with_dummy_span(kw::UnderscoreLifetime),
123 LifetimeName::Static => Ident::with_dummy_span(kw::StaticLifetime),
124 LifetimeName::Param(_, param_name) => param_name.ident(),
128 pub fn is_anonymous(&self) -> bool {
130 LifetimeName::ImplicitObjectLifetimeDefault
131 | LifetimeName::Infer
132 | LifetimeName::Param(_, ParamName::Fresh)
133 | LifetimeName::Error => true,
134 LifetimeName::Static | LifetimeName::Param(..) => false,
138 pub fn is_elided(&self) -> bool {
140 LifetimeName::ImplicitObjectLifetimeDefault | LifetimeName::Infer => true,
142 // It might seem surprising that `Fresh` counts as not *elided*
143 // -- but this is because, as far as the code in the compiler is
144 // concerned -- `Fresh` variants act equivalently to "some fresh name".
145 // They correspond to early-bound regions on an impl, in other words.
146 LifetimeName::Error | LifetimeName::Param(..) | LifetimeName::Static => false,
150 fn is_static(&self) -> bool {
151 self == &LifetimeName::Static
154 pub fn normalize_to_macros_2_0(&self) -> LifetimeName {
156 LifetimeName::Param(def_id, param_name) => {
157 LifetimeName::Param(def_id, param_name.normalize_to_macros_2_0())
159 lifetime_name => lifetime_name,
164 impl fmt::Display for Lifetime {
165 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166 self.name.ident().fmt(f)
171 pub fn is_elided(&self) -> bool {
172 self.name.is_elided()
175 pub fn is_static(&self) -> bool {
176 self.name.is_static()
180 /// A `Path` is essentially Rust's notion of a name; for instance,
181 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
182 /// along with a bunch of supporting information.
183 #[derive(Debug, HashStable_Generic)]
184 pub struct Path<'hir> {
186 /// The resolution for the path.
188 /// The segments in the path: the things separated by `::`.
189 pub segments: &'hir [PathSegment<'hir>],
193 pub fn is_global(&self) -> bool {
194 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
198 /// A segment of a path: an identifier, an optional lifetime, and a set of
200 #[derive(Debug, HashStable_Generic)]
201 pub struct PathSegment<'hir> {
202 /// The identifier portion of this path segment.
207 /// Type/lifetime parameters attached to this path. They come in
208 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
209 /// this is more than just simple syntactic sugar; the use of
210 /// parens affects the region binding rules, so we preserve the
212 pub args: Option<&'hir GenericArgs<'hir>>,
214 /// Whether to infer remaining type parameters, if any.
215 /// This only applies to expression and pattern paths, and
216 /// out of those only the segments with no type parameters
217 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
218 pub infer_args: bool,
221 impl<'hir> PathSegment<'hir> {
222 /// Converts an identifier to the corresponding segment.
223 pub fn new(ident: Ident, hir_id: HirId, res: Res) -> PathSegment<'hir> {
224 PathSegment { ident, hir_id, res, infer_args: true, args: None }
227 pub fn invalid() -> Self {
228 Self::new(Ident::empty(), HirId::INVALID, Res::Err)
231 pub fn args(&self) -> &GenericArgs<'hir> {
232 if let Some(ref args) = self.args {
235 const DUMMY: &GenericArgs<'_> = &GenericArgs::none();
241 #[derive(Encodable, Debug, HashStable_Generic)]
242 pub struct ConstArg {
243 pub value: AnonConst,
247 #[derive(Encodable, Debug, HashStable_Generic)]
248 pub struct InferArg {
254 pub fn to_ty(&self) -> Ty<'_> {
255 Ty { kind: TyKind::Infer, span: self.span, hir_id: self.hir_id }
259 #[derive(Debug, HashStable_Generic)]
260 pub enum GenericArg<'hir> {
261 Lifetime(&'hir Lifetime),
262 Type(&'hir Ty<'hir>),
267 impl GenericArg<'_> {
268 pub fn span(&self) -> Span {
270 GenericArg::Lifetime(l) => l.span,
271 GenericArg::Type(t) => t.span,
272 GenericArg::Const(c) => c.span,
273 GenericArg::Infer(i) => i.span,
277 pub fn hir_id(&self) -> HirId {
279 GenericArg::Lifetime(l) => l.hir_id,
280 GenericArg::Type(t) => t.hir_id,
281 GenericArg::Const(c) => c.value.hir_id,
282 GenericArg::Infer(i) => i.hir_id,
286 pub fn is_synthetic(&self) -> bool {
287 matches!(self, GenericArg::Lifetime(lifetime) if lifetime.name.ident() == Ident::empty())
290 pub fn descr(&self) -> &'static str {
292 GenericArg::Lifetime(_) => "lifetime",
293 GenericArg::Type(_) => "type",
294 GenericArg::Const(_) => "constant",
295 GenericArg::Infer(_) => "inferred",
299 pub fn to_ord(&self) -> ast::ParamKindOrd {
301 GenericArg::Lifetime(_) => ast::ParamKindOrd::Lifetime,
302 GenericArg::Type(_) | GenericArg::Const(_) | GenericArg::Infer(_) => {
303 ast::ParamKindOrd::TypeOrConst
308 pub fn is_ty_or_const(&self) -> bool {
310 GenericArg::Lifetime(_) => false,
311 GenericArg::Type(_) | GenericArg::Const(_) | GenericArg::Infer(_) => true,
316 #[derive(Debug, HashStable_Generic)]
317 pub struct GenericArgs<'hir> {
318 /// The generic arguments for this path segment.
319 pub args: &'hir [GenericArg<'hir>],
320 /// Bindings (equality constraints) on associated types, if present.
321 /// E.g., `Foo<A = Bar>`.
322 pub bindings: &'hir [TypeBinding<'hir>],
323 /// Were arguments written in parenthesized form `Fn(T) -> U`?
324 /// This is required mostly for pretty-printing and diagnostics,
325 /// but also for changing lifetime elision rules to be "function-like".
326 pub parenthesized: bool,
327 /// The span encompassing arguments and the surrounding brackets `<>` or `()`
328 /// Foo<A, B, AssocTy = D> Fn(T, U, V) -> W
329 /// ^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^
330 /// Note that this may be:
331 /// - empty, if there are no generic brackets (but there may be hidden lifetimes)
332 /// - dummy, if this was generated while desugaring
336 impl<'hir> GenericArgs<'hir> {
337 pub const fn none() -> Self {
338 Self { args: &[], bindings: &[], parenthesized: false, span_ext: DUMMY_SP }
341 pub fn inputs(&self) -> &[Ty<'hir>] {
342 if self.parenthesized {
343 for arg in self.args {
345 GenericArg::Lifetime(_) => {}
346 GenericArg::Type(ref ty) => {
347 if let TyKind::Tup(ref tys) = ty.kind {
352 GenericArg::Const(_) => {}
353 GenericArg::Infer(_) => {}
357 panic!("GenericArgs::inputs: not a `Fn(T) -> U`");
361 pub fn has_type_params(&self) -> bool {
362 self.args.iter().any(|arg| matches!(arg, GenericArg::Type(_)))
365 pub fn has_err(&self) -> bool {
366 self.args.iter().any(|arg| match arg {
367 GenericArg::Type(ty) => matches!(ty.kind, TyKind::Err),
369 }) || self.bindings.iter().any(|arg| match arg.kind {
370 TypeBindingKind::Equality { term: Term::Ty(ty) } => matches!(ty.kind, TyKind::Err),
376 pub fn num_type_params(&self) -> usize {
377 self.args.iter().filter(|arg| matches!(arg, GenericArg::Type(_))).count()
381 pub fn num_lifetime_params(&self) -> usize {
382 self.args.iter().filter(|arg| matches!(arg, GenericArg::Lifetime(_))).count()
386 pub fn has_lifetime_params(&self) -> bool {
387 self.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)))
391 pub fn num_generic_params(&self) -> usize {
392 self.args.iter().filter(|arg| !matches!(arg, GenericArg::Lifetime(_))).count()
395 /// The span encompassing the text inside the surrounding brackets.
396 /// It will also include bindings if they aren't in the form `-> Ret`
397 /// Returns `None` if the span is empty (e.g. no brackets) or dummy
398 pub fn span(&self) -> Option<Span> {
399 let span_ext = self.span_ext()?;
400 Some(span_ext.with_lo(span_ext.lo() + BytePos(1)).with_hi(span_ext.hi() - BytePos(1)))
403 /// Returns span encompassing arguments and their surrounding `<>` or `()`
404 pub fn span_ext(&self) -> Option<Span> {
405 Some(self.span_ext).filter(|span| !span.is_empty())
408 pub fn is_empty(&self) -> bool {
413 /// A modifier on a bound, currently this is only used for `?Sized`, where the
414 /// modifier is `Maybe`. Negative bounds should also be handled here.
415 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
416 #[derive(HashStable_Generic)]
417 pub enum TraitBoundModifier {
423 /// The AST represents all type param bounds as types.
424 /// `typeck::collect::compute_bounds` matches these against
425 /// the "special" built-in traits (see `middle::lang_items`) and
426 /// detects `Copy`, `Send` and `Sync`.
427 #[derive(Clone, Debug, HashStable_Generic)]
428 pub enum GenericBound<'hir> {
429 Trait(PolyTraitRef<'hir>, TraitBoundModifier),
430 // FIXME(davidtwco): Introduce `PolyTraitRef::LangItem`
431 LangItemTrait(LangItem, Span, HirId, &'hir GenericArgs<'hir>),
432 Outlives(&'hir Lifetime),
435 impl GenericBound<'_> {
436 pub fn trait_ref(&self) -> Option<&TraitRef<'_>> {
438 GenericBound::Trait(data, _) => Some(&data.trait_ref),
443 pub fn span(&self) -> Span {
445 GenericBound::Trait(t, ..) => t.span,
446 GenericBound::LangItemTrait(_, span, ..) => *span,
447 GenericBound::Outlives(l) => l.span,
452 pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
454 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
455 pub enum LifetimeParamKind {
456 // Indicates that the lifetime definition was explicitly declared (e.g., in
457 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
460 // Indication that the lifetime was elided (e.g., in both cases in
461 // `fn foo(x: &u8) -> &'_ u8 { x }`).
464 // Indication that the lifetime name was somehow in error.
468 #[derive(Debug, HashStable_Generic)]
469 pub enum GenericParamKind<'hir> {
470 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
472 kind: LifetimeParamKind,
475 default: Option<&'hir Ty<'hir>>,
480 /// Optional default value for the const generic param
481 default: Option<AnonConst>,
485 #[derive(Debug, HashStable_Generic)]
486 pub struct GenericParam<'hir> {
490 pub pure_wrt_drop: bool,
491 pub kind: GenericParamKind<'hir>,
492 pub colon_span: Option<Span>,
495 impl<'hir> GenericParam<'hir> {
496 /// Synthetic type-parameters are inserted after normal ones.
497 /// In order for normal parameters to be able to refer to synthetic ones,
498 /// scans them first.
499 pub fn is_impl_trait(&self) -> bool {
500 matches!(self.kind, GenericParamKind::Type { synthetic: true, .. })
503 /// This can happen for `async fn`, e.g. `async fn f<'_>(&'_ self)`.
505 /// See `lifetime_to_generic_param` in `rustc_ast_lowering` for more information.
506 pub fn is_elided_lifetime(&self) -> bool {
507 matches!(self.kind, GenericParamKind::Lifetime { kind: LifetimeParamKind::Elided })
512 pub struct GenericParamCount {
513 pub lifetimes: usize,
519 /// Represents lifetimes and type parameters attached to a declaration
520 /// of a function, enum, trait, etc.
521 #[derive(Debug, HashStable_Generic)]
522 pub struct Generics<'hir> {
523 pub params: &'hir [GenericParam<'hir>],
524 pub predicates: &'hir [WherePredicate<'hir>],
525 pub has_where_clause_predicates: bool,
526 pub where_clause_span: Span,
530 impl<'hir> Generics<'hir> {
531 pub const fn empty() -> &'hir Generics<'hir> {
532 const NOPE: Generics<'_> = Generics {
535 has_where_clause_predicates: false,
536 where_clause_span: DUMMY_SP,
542 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'hir>> {
543 for param in self.params {
544 if name == param.name.ident().name {
551 pub fn spans(&self) -> MultiSpan {
552 if self.params.is_empty() {
555 self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
559 /// If there are generic parameters, return where to introduce a new one.
560 pub fn span_for_param_suggestion(&self) -> Option<Span> {
561 if self.params.iter().any(|p| self.span.contains(p.span)) {
562 // `fn foo<A>(t: impl Trait)`
563 // ^ suggest `, T: Trait` here
564 let span = self.span.with_lo(self.span.hi() - BytePos(1)).shrink_to_lo();
571 /// `Span` where further predicates would be suggested, accounting for trailing commas, like
572 /// in `fn foo<T>(t: T) where T: Foo,` so we don't suggest two trailing commas.
573 pub fn tail_span_for_predicate_suggestion(&self) -> Span {
574 let end = self.where_clause_span.shrink_to_hi();
575 if self.has_where_clause_predicates {
578 .rfind(|&p| p.in_where_clause())
579 .map_or(end, |p| p.span())
587 pub fn add_where_or_trailing_comma(&self) -> &'static str {
588 if self.has_where_clause_predicates {
590 } else if self.where_clause_span.is_empty() {
593 // No where clause predicates, but we have `where` token
598 pub fn bounds_for_param(
600 param_def_id: LocalDefId,
601 ) -> impl Iterator<Item = &WhereBoundPredicate<'hir>> {
602 self.predicates.iter().filter_map(move |pred| match pred {
603 WherePredicate::BoundPredicate(bp) if bp.is_param_bound(param_def_id.to_def_id()) => {
610 pub fn outlives_for_param(
612 param_def_id: LocalDefId,
613 ) -> impl Iterator<Item = &WhereRegionPredicate<'_>> {
614 self.predicates.iter().filter_map(move |pred| match pred {
615 WherePredicate::RegionPredicate(rp) if rp.is_param_bound(param_def_id) => Some(rp),
620 pub fn bounds_span_for_suggestions(&self, param_def_id: LocalDefId) -> Option<Span> {
621 self.bounds_for_param(param_def_id).flat_map(|bp| bp.bounds.iter().rev()).find_map(
623 // We include bounds that come from a `#[derive(_)]` but point at the user's code,
624 // as we use this method to get a span appropriate for suggestions.
625 let bs = bound.span();
626 if bs.can_be_used_for_suggestions() { Some(bs.shrink_to_hi()) } else { None }
631 pub fn span_for_predicate_removal(&self, pos: usize) -> Span {
632 let predicate = &self.predicates[pos];
633 let span = predicate.span();
635 if !predicate.in_where_clause() {
641 // We need to find out which comma to remove.
642 if pos < self.predicates.len() - 1 {
643 let next_pred = &self.predicates[pos + 1];
644 if next_pred.in_where_clause() {
645 // where T: ?Sized, Foo: Bar,
647 return span.until(next_pred.span());
652 let prev_pred = &self.predicates[pos - 1];
653 if prev_pred.in_where_clause() {
654 // where Foo: Bar, T: ?Sized,
656 return prev_pred.span().shrink_to_hi().to(span);
660 // This is the only predicate in the where clause.
663 self.where_clause_span
666 pub fn span_for_bound_removal(&self, predicate_pos: usize, bound_pos: usize) -> Span {
667 let predicate = &self.predicates[predicate_pos];
668 let bounds = predicate.bounds();
670 if bounds.len() == 1 {
671 return self.span_for_predicate_removal(predicate_pos);
674 let span = bounds[bound_pos].span();
676 // where T: ?Sized + Bar, Foo: Bar,
678 span.to(bounds[1].span().shrink_to_lo())
680 // where T: Bar + ?Sized, Foo: Bar,
682 bounds[bound_pos - 1].span().shrink_to_hi().to(span)
687 /// A single predicate in a where-clause.
688 #[derive(Debug, HashStable_Generic)]
689 pub enum WherePredicate<'hir> {
690 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
691 BoundPredicate(WhereBoundPredicate<'hir>),
692 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
693 RegionPredicate(WhereRegionPredicate<'hir>),
694 /// An equality predicate (unsupported).
695 EqPredicate(WhereEqPredicate<'hir>),
698 impl<'hir> WherePredicate<'hir> {
699 pub fn span(&self) -> Span {
701 WherePredicate::BoundPredicate(p) => p.span,
702 WherePredicate::RegionPredicate(p) => p.span,
703 WherePredicate::EqPredicate(p) => p.span,
707 pub fn in_where_clause(&self) -> bool {
709 WherePredicate::BoundPredicate(p) => p.origin == PredicateOrigin::WhereClause,
710 WherePredicate::RegionPredicate(p) => p.in_where_clause,
711 WherePredicate::EqPredicate(_) => false,
715 pub fn bounds(&self) -> GenericBounds<'hir> {
717 WherePredicate::BoundPredicate(p) => p.bounds,
718 WherePredicate::RegionPredicate(p) => p.bounds,
719 WherePredicate::EqPredicate(_) => &[],
724 #[derive(Copy, Clone, Debug, HashStable_Generic, PartialEq, Eq)]
725 pub enum PredicateOrigin {
731 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
732 #[derive(Debug, HashStable_Generic)]
733 pub struct WhereBoundPredicate<'hir> {
736 /// Origin of the predicate.
737 pub origin: PredicateOrigin,
738 /// Any generics from a `for` binding.
739 pub bound_generic_params: &'hir [GenericParam<'hir>],
740 /// The type being bounded.
741 pub bounded_ty: &'hir Ty<'hir>,
742 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
743 pub bounds: GenericBounds<'hir>,
746 impl<'hir> WhereBoundPredicate<'hir> {
747 /// Returns `true` if `param_def_id` matches the `bounded_ty` of this predicate.
748 pub fn is_param_bound(&self, param_def_id: DefId) -> bool {
749 self.bounded_ty.as_generic_param().map_or(false, |(def_id, _)| def_id == param_def_id)
753 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
754 #[derive(Debug, HashStable_Generic)]
755 pub struct WhereRegionPredicate<'hir> {
757 pub in_where_clause: bool,
758 pub lifetime: &'hir Lifetime,
759 pub bounds: GenericBounds<'hir>,
762 impl<'hir> WhereRegionPredicate<'hir> {
763 /// Returns `true` if `param_def_id` matches the `lifetime` of this predicate.
764 pub fn is_param_bound(&self, param_def_id: LocalDefId) -> bool {
765 match self.lifetime.name {
766 LifetimeName::Param(id, _) => id == param_def_id,
772 /// An equality predicate (e.g., `T = int`); currently unsupported.
773 #[derive(Debug, HashStable_Generic)]
774 pub struct WhereEqPredicate<'hir> {
776 pub lhs_ty: &'hir Ty<'hir>,
777 pub rhs_ty: &'hir Ty<'hir>,
780 /// HIR node coupled with its parent's id in the same HIR owner.
782 /// The parent is trash when the node is a HIR owner.
783 #[derive(Clone, Debug)]
784 pub struct ParentedNode<'tcx> {
785 pub parent: ItemLocalId,
786 pub node: Node<'tcx>,
789 /// Attributes owned by a HIR owner.
791 pub struct AttributeMap<'tcx> {
792 pub map: SortedMap<ItemLocalId, &'tcx [Attribute]>,
793 pub hash: Fingerprint,
796 impl<'tcx> AttributeMap<'tcx> {
797 pub const EMPTY: &'static AttributeMap<'static> =
798 &AttributeMap { map: SortedMap::new(), hash: Fingerprint::ZERO };
801 pub fn get(&self, id: ItemLocalId) -> &'tcx [Attribute] {
802 self.map.get(&id).copied().unwrap_or(&[])
806 /// Map of all HIR nodes inside the current owner.
807 /// These nodes are mapped by `ItemLocalId` alongside the index of their parent node.
808 /// The HIR tree, including bodies, is pre-hashed.
809 pub struct OwnerNodes<'tcx> {
810 /// Pre-computed hash of the full HIR.
811 pub hash_including_bodies: Fingerprint,
812 /// Pre-computed hash of the item signature, sithout recursing into the body.
813 pub hash_without_bodies: Fingerprint,
814 /// Full HIR for the current owner.
815 // The zeroth node's parent should never be accessed: the owner's parent is computed by the
816 // hir_owner_parent query. It is set to `ItemLocalId::INVALID` to force an ICE if accidentally
818 pub nodes: IndexVec<ItemLocalId, Option<ParentedNode<'tcx>>>,
819 /// Content of local bodies.
820 pub bodies: SortedMap<ItemLocalId, &'tcx Body<'tcx>>,
821 /// Non-owning definitions contained in this owner.
822 pub local_id_to_def_id: SortedMap<ItemLocalId, LocalDefId>,
825 impl<'tcx> OwnerNodes<'tcx> {
826 pub fn node(&self) -> OwnerNode<'tcx> {
827 use rustc_index::vec::Idx;
828 let node = self.nodes[ItemLocalId::new(0)].as_ref().unwrap().node;
829 let node = node.as_owner().unwrap(); // Indexing must ensure it is an OwnerNode.
834 impl fmt::Debug for OwnerNodes<'_> {
835 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
836 f.debug_struct("OwnerNodes")
837 // Do not print all the pointers to all the nodes, as it would be unreadable.
838 .field("node", &self.nodes[ItemLocalId::from_u32(0)])
844 .map(|(id, parented_node)| (id, parented_node.as_ref().map(|node| node.parent)))
845 .collect::<Vec<_>>(),
847 .field("bodies", &self.bodies)
848 .field("local_id_to_def_id", &self.local_id_to_def_id)
849 .field("hash_without_bodies", &self.hash_without_bodies)
850 .field("hash_including_bodies", &self.hash_including_bodies)
855 /// Full information resulting from lowering an AST node.
856 #[derive(Debug, HashStable_Generic)]
857 pub struct OwnerInfo<'hir> {
858 /// Contents of the HIR.
859 pub nodes: OwnerNodes<'hir>,
860 /// Map from each nested owner to its parent's local id.
861 pub parenting: FxHashMap<LocalDefId, ItemLocalId>,
862 /// Collected attributes of the HIR nodes.
863 pub attrs: AttributeMap<'hir>,
864 /// Map indicating what traits are in scope for places where this
865 /// is relevant; generated by resolve.
866 pub trait_map: FxHashMap<ItemLocalId, Box<[TraitCandidate]>>,
869 impl<'tcx> OwnerInfo<'tcx> {
871 pub fn node(&self) -> OwnerNode<'tcx> {
876 #[derive(Copy, Clone, Debug, HashStable_Generic)]
877 pub enum MaybeOwner<T> {
880 /// Used as a placeholder for unused LocalDefId.
884 impl<T> MaybeOwner<T> {
885 pub fn as_owner(self) -> Option<T> {
887 MaybeOwner::Owner(i) => Some(i),
888 MaybeOwner::NonOwner(_) | MaybeOwner::Phantom => None,
892 pub fn map<U>(self, f: impl FnOnce(T) -> U) -> MaybeOwner<U> {
894 MaybeOwner::Owner(i) => MaybeOwner::Owner(f(i)),
895 MaybeOwner::NonOwner(hir_id) => MaybeOwner::NonOwner(hir_id),
896 MaybeOwner::Phantom => MaybeOwner::Phantom,
900 pub fn unwrap(self) -> T {
902 MaybeOwner::Owner(i) => i,
903 MaybeOwner::NonOwner(_) | MaybeOwner::Phantom => panic!("Not a HIR owner"),
908 /// The top-level data structure that stores the entire contents of
909 /// the crate currently being compiled.
911 /// For more details, see the [rustc dev guide].
913 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
915 pub struct Crate<'hir> {
916 pub owners: IndexVec<LocalDefId, MaybeOwner<&'hir OwnerInfo<'hir>>>,
917 pub hir_hash: Fingerprint,
920 #[derive(Debug, HashStable_Generic)]
921 pub struct Closure<'hir> {
922 pub binder: ClosureBinder,
923 pub capture_clause: CaptureBy,
924 pub bound_generic_params: &'hir [GenericParam<'hir>],
925 pub fn_decl: &'hir FnDecl<'hir>,
927 pub fn_decl_span: Span,
928 pub movability: Option<Movability>,
931 /// A block of statements `{ .. }`, which may have a label (in this case the
932 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
933 /// the `rules` being anything but `DefaultBlock`.
934 #[derive(Debug, HashStable_Generic)]
935 pub struct Block<'hir> {
936 /// Statements in a block.
937 pub stmts: &'hir [Stmt<'hir>],
938 /// An expression at the end of the block
939 /// without a semicolon, if any.
940 pub expr: Option<&'hir Expr<'hir>>,
941 #[stable_hasher(ignore)]
943 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
944 pub rules: BlockCheckMode,
946 /// If true, then there may exist `break 'a` values that aim to
947 /// break out of this block early.
948 /// Used by `'label: {}` blocks and by `try {}` blocks.
949 pub targeted_by_break: bool,
952 impl<'hir> Block<'hir> {
953 pub fn innermost_block(&self) -> &Block<'hir> {
954 let mut block = self;
955 while let Some(Expr { kind: ExprKind::Block(inner_block, _), .. }) = block.expr {
962 #[derive(Debug, HashStable_Generic)]
963 pub struct Pat<'hir> {
964 #[stable_hasher(ignore)]
966 pub kind: PatKind<'hir>,
968 // Whether to use default binding modes.
969 // At present, this is false only for destructuring assignment.
970 pub default_binding_modes: bool,
973 impl<'hir> Pat<'hir> {
974 // FIXME(#19596) this is a workaround, but there should be a better way
975 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) -> bool {
982 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
983 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
984 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
985 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
986 Slice(before, slice, after) => {
987 before.iter().chain(slice).chain(after.iter()).all(|p| p.walk_short_(it))
992 /// Walk the pattern in left-to-right order,
993 /// short circuiting (with `.all(..)`) if `false` is returned.
995 /// Note that when visiting e.g. `Tuple(ps)`,
996 /// if visiting `ps[0]` returns `false`,
997 /// then `ps[1]` will not be visited.
998 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) -> bool {
999 self.walk_short_(&mut it)
1002 // FIXME(#19596) this is a workaround, but there should be a better way
1003 fn walk_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) {
1010 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
1011 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
1012 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
1013 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
1014 Slice(before, slice, after) => {
1015 before.iter().chain(slice).chain(after.iter()).for_each(|p| p.walk_(it))
1020 /// Walk the pattern in left-to-right order.
1022 /// If `it(pat)` returns `false`, the children are not visited.
1023 pub fn walk(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) {
1027 /// Walk the pattern in left-to-right order.
1029 /// If you always want to recurse, prefer this method over `walk`.
1030 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
1038 /// A single field in a struct pattern.
1040 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
1041 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
1042 /// except `is_shorthand` is true.
1043 #[derive(Debug, HashStable_Generic)]
1044 pub struct PatField<'hir> {
1045 #[stable_hasher(ignore)]
1047 /// The identifier for the field.
1049 /// The pattern the field is destructured to.
1050 pub pat: &'hir Pat<'hir>,
1051 pub is_shorthand: bool,
1055 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1061 impl fmt::Display for RangeEnd {
1062 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1063 f.write_str(match self {
1064 RangeEnd::Included => "..=",
1065 RangeEnd::Excluded => "..",
1070 // Equivalent to `Option<usize>`. That type takes up 16 bytes on 64-bit, but
1071 // this type only takes up 4 bytes, at the cost of being restricted to a
1072 // maximum value of `u32::MAX - 1`. In practice, this is more than enough.
1073 #[derive(Clone, Copy, PartialEq, Eq, Hash, HashStable_Generic)]
1074 pub struct DotDotPos(u32);
1077 // Panics if n >= u32::MAX.
1078 pub fn new(n: Option<usize>) -> Self {
1081 assert!(n < u32::MAX as usize);
1084 None => Self(u32::MAX),
1088 pub fn as_opt_usize(&self) -> Option<usize> {
1089 if self.0 == u32::MAX { None } else { Some(self.0 as usize) }
1093 impl fmt::Debug for DotDotPos {
1094 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1095 self.as_opt_usize().fmt(f)
1099 #[derive(Debug, HashStable_Generic)]
1100 pub enum PatKind<'hir> {
1101 /// Represents a wildcard pattern (i.e., `_`).
1104 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
1105 /// The `HirId` is the canonical ID for the variable being bound,
1106 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
1107 /// which is the pattern ID of the first `x`.
1108 Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
1110 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
1111 /// The `bool` is `true` in the presence of a `..`.
1112 Struct(QPath<'hir>, &'hir [PatField<'hir>], bool),
1114 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
1115 /// If the `..` pattern fragment is present, then `DotDotPos` denotes its position.
1116 /// `0 <= position <= subpats.len()`
1117 TupleStruct(QPath<'hir>, &'hir [Pat<'hir>], DotDotPos),
1119 /// An or-pattern `A | B | C`.
1120 /// Invariant: `pats.len() >= 2`.
1121 Or(&'hir [Pat<'hir>]),
1123 /// A path pattern for a unit struct/variant or a (maybe-associated) constant.
1126 /// A tuple pattern (e.g., `(a, b)`).
1127 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
1128 /// `0 <= position <= subpats.len()`
1129 Tuple(&'hir [Pat<'hir>], DotDotPos),
1131 /// A `box` pattern.
1132 Box(&'hir Pat<'hir>),
1134 /// A reference pattern (e.g., `&mut (a, b)`).
1135 Ref(&'hir Pat<'hir>, Mutability),
1138 Lit(&'hir Expr<'hir>),
1140 /// A range pattern (e.g., `1..=2` or `1..2`).
1141 Range(Option<&'hir Expr<'hir>>, Option<&'hir Expr<'hir>>, RangeEnd),
1143 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
1145 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
1146 /// If `slice` exists, then `after` can be non-empty.
1148 /// The representation for e.g., `[a, b, .., c, d]` is:
1149 /// ```ignore (illustrative)
1150 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
1152 Slice(&'hir [Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [Pat<'hir>]),
1155 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1156 pub enum BinOpKind {
1157 /// The `+` operator (addition).
1159 /// The `-` operator (subtraction).
1161 /// The `*` operator (multiplication).
1163 /// The `/` operator (division).
1165 /// The `%` operator (modulus).
1167 /// The `&&` operator (logical and).
1169 /// The `||` operator (logical or).
1171 /// The `^` operator (bitwise xor).
1173 /// The `&` operator (bitwise and).
1175 /// The `|` operator (bitwise or).
1177 /// The `<<` operator (shift left).
1179 /// The `>>` operator (shift right).
1181 /// The `==` operator (equality).
1183 /// The `<` operator (less than).
1185 /// The `<=` operator (less than or equal to).
1187 /// The `!=` operator (not equal to).
1189 /// The `>=` operator (greater than or equal to).
1191 /// The `>` operator (greater than).
1196 pub fn as_str(self) -> &'static str {
1198 BinOpKind::Add => "+",
1199 BinOpKind::Sub => "-",
1200 BinOpKind::Mul => "*",
1201 BinOpKind::Div => "/",
1202 BinOpKind::Rem => "%",
1203 BinOpKind::And => "&&",
1204 BinOpKind::Or => "||",
1205 BinOpKind::BitXor => "^",
1206 BinOpKind::BitAnd => "&",
1207 BinOpKind::BitOr => "|",
1208 BinOpKind::Shl => "<<",
1209 BinOpKind::Shr => ">>",
1210 BinOpKind::Eq => "==",
1211 BinOpKind::Lt => "<",
1212 BinOpKind::Le => "<=",
1213 BinOpKind::Ne => "!=",
1214 BinOpKind::Ge => ">=",
1215 BinOpKind::Gt => ">",
1219 pub fn is_lazy(self) -> bool {
1220 matches!(self, BinOpKind::And | BinOpKind::Or)
1223 pub fn is_shift(self) -> bool {
1224 matches!(self, BinOpKind::Shl | BinOpKind::Shr)
1227 pub fn is_comparison(self) -> bool {
1234 | BinOpKind::Ge => true,
1246 | BinOpKind::Shr => false,
1250 /// Returns `true` if the binary operator takes its arguments by value.
1251 pub fn is_by_value(self) -> bool {
1252 !self.is_comparison()
1256 impl Into<ast::BinOpKind> for BinOpKind {
1257 fn into(self) -> ast::BinOpKind {
1259 BinOpKind::Add => ast::BinOpKind::Add,
1260 BinOpKind::Sub => ast::BinOpKind::Sub,
1261 BinOpKind::Mul => ast::BinOpKind::Mul,
1262 BinOpKind::Div => ast::BinOpKind::Div,
1263 BinOpKind::Rem => ast::BinOpKind::Rem,
1264 BinOpKind::And => ast::BinOpKind::And,
1265 BinOpKind::Or => ast::BinOpKind::Or,
1266 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1267 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1268 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1269 BinOpKind::Shl => ast::BinOpKind::Shl,
1270 BinOpKind::Shr => ast::BinOpKind::Shr,
1271 BinOpKind::Eq => ast::BinOpKind::Eq,
1272 BinOpKind::Lt => ast::BinOpKind::Lt,
1273 BinOpKind::Le => ast::BinOpKind::Le,
1274 BinOpKind::Ne => ast::BinOpKind::Ne,
1275 BinOpKind::Ge => ast::BinOpKind::Ge,
1276 BinOpKind::Gt => ast::BinOpKind::Gt,
1281 pub type BinOp = Spanned<BinOpKind>;
1283 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1285 /// The `*` operator (dereferencing).
1287 /// The `!` operator (logical negation).
1289 /// The `-` operator (negation).
1294 pub fn as_str(self) -> &'static str {
1302 /// Returns `true` if the unary operator takes its argument by value.
1303 pub fn is_by_value(self) -> bool {
1304 matches!(self, Self::Neg | Self::Not)
1309 #[derive(Debug, HashStable_Generic)]
1310 pub struct Stmt<'hir> {
1312 pub kind: StmtKind<'hir>,
1316 /// The contents of a statement.
1317 #[derive(Debug, HashStable_Generic)]
1318 pub enum StmtKind<'hir> {
1319 /// A local (`let`) binding.
1320 Local(&'hir Local<'hir>),
1322 /// An item binding.
1325 /// An expression without a trailing semi-colon (must have unit type).
1326 Expr(&'hir Expr<'hir>),
1328 /// An expression with a trailing semi-colon (may have any type).
1329 Semi(&'hir Expr<'hir>),
1332 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <init>;`).
1333 #[derive(Debug, HashStable_Generic)]
1334 pub struct Local<'hir> {
1335 pub pat: &'hir Pat<'hir>,
1336 /// Type annotation, if any (otherwise the type will be inferred).
1337 pub ty: Option<&'hir Ty<'hir>>,
1338 /// Initializer expression to set the value, if any.
1339 pub init: Option<&'hir Expr<'hir>>,
1340 /// Else block for a `let...else` binding.
1341 pub els: Option<&'hir Block<'hir>>,
1344 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1345 /// desugaring. Otherwise will be `Normal`.
1346 pub source: LocalSource,
1349 /// Represents a single arm of a `match` expression, e.g.
1350 /// `<pat> (if <guard>) => <body>`.
1351 #[derive(Debug, HashStable_Generic)]
1352 pub struct Arm<'hir> {
1353 #[stable_hasher(ignore)]
1356 /// If this pattern and the optional guard matches, then `body` is evaluated.
1357 pub pat: &'hir Pat<'hir>,
1358 /// Optional guard clause.
1359 pub guard: Option<Guard<'hir>>,
1360 /// The expression the arm evaluates to if this arm matches.
1361 pub body: &'hir Expr<'hir>,
1364 /// Represents a `let <pat>[: <ty>] = <expr>` expression (not a Local), occurring in an `if-let` or
1365 /// `let-else`, evaluating to a boolean. Typically the pattern is refutable.
1367 /// In an if-let, imagine it as `if (let <pat> = <expr>) { ... }`; in a let-else, it is part of the
1368 /// desugaring to if-let. Only let-else supports the type annotation at present.
1369 #[derive(Debug, HashStable_Generic)]
1370 pub struct Let<'hir> {
1373 pub pat: &'hir Pat<'hir>,
1374 pub ty: Option<&'hir Ty<'hir>>,
1375 pub init: &'hir Expr<'hir>,
1378 #[derive(Debug, HashStable_Generic)]
1379 pub enum Guard<'hir> {
1380 If(&'hir Expr<'hir>),
1381 IfLet(&'hir Let<'hir>),
1384 impl<'hir> Guard<'hir> {
1385 /// Returns the body of the guard
1387 /// In other words, returns the e in either of the following:
1390 /// - `if let x = e`
1391 pub fn body(&self) -> &'hir Expr<'hir> {
1393 Guard::If(e) | Guard::IfLet(Let { init: e, .. }) => e,
1398 #[derive(Debug, HashStable_Generic)]
1399 pub struct ExprField<'hir> {
1400 #[stable_hasher(ignore)]
1403 pub expr: &'hir Expr<'hir>,
1405 pub is_shorthand: bool,
1408 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1409 pub enum BlockCheckMode {
1411 UnsafeBlock(UnsafeSource),
1414 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1415 pub enum UnsafeSource {
1420 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
1425 /// The body of a function, closure, or constant value. In the case of
1426 /// a function, the body contains not only the function body itself
1427 /// (which is an expression), but also the argument patterns, since
1428 /// those are something that the caller doesn't really care about.
1433 /// fn foo((x, y): (u32, u32)) -> u32 {
1438 /// Here, the `Body` associated with `foo()` would contain:
1440 /// - an `params` array containing the `(x, y)` pattern
1441 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1442 /// - `generator_kind` would be `None`
1444 /// All bodies have an **owner**, which can be accessed via the HIR
1445 /// map using `body_owner_def_id()`.
1446 #[derive(Debug, HashStable_Generic)]
1447 pub struct Body<'hir> {
1448 pub params: &'hir [Param<'hir>],
1449 pub value: &'hir Expr<'hir>,
1450 pub generator_kind: Option<GeneratorKind>,
1453 impl<'hir> Body<'hir> {
1454 pub fn id(&self) -> BodyId {
1455 BodyId { hir_id: self.value.hir_id }
1458 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1463 /// The type of source expression that caused this generator to be created.
1464 #[derive(Clone, PartialEq, PartialOrd, Eq, Hash, Debug, Copy)]
1465 #[derive(HashStable_Generic, Encodable, Decodable)]
1466 pub enum GeneratorKind {
1467 /// An explicit `async` block or the body of an async function.
1468 Async(AsyncGeneratorKind),
1470 /// A generator literal created via a `yield` inside a closure.
1474 impl fmt::Display for GeneratorKind {
1475 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1477 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1478 GeneratorKind::Gen => f.write_str("generator"),
1483 impl GeneratorKind {
1484 pub fn descr(&self) -> &'static str {
1486 GeneratorKind::Async(ask) => ask.descr(),
1487 GeneratorKind::Gen => "generator",
1492 /// In the case of a generator created as part of an async construct,
1493 /// which kind of async construct caused it to be created?
1495 /// This helps error messages but is also used to drive coercions in
1496 /// type-checking (see #60424).
1497 #[derive(Clone, PartialEq, PartialOrd, Eq, Hash, Debug, Copy)]
1498 #[derive(HashStable_Generic, Encodable, Decodable)]
1499 pub enum AsyncGeneratorKind {
1500 /// An explicit `async` block written by the user.
1503 /// An explicit `async` closure written by the user.
1506 /// The `async` block generated as the body of an async function.
1510 impl fmt::Display for AsyncGeneratorKind {
1511 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1512 f.write_str(match self {
1513 AsyncGeneratorKind::Block => "`async` block",
1514 AsyncGeneratorKind::Closure => "`async` closure body",
1515 AsyncGeneratorKind::Fn => "`async fn` body",
1520 impl AsyncGeneratorKind {
1521 pub fn descr(&self) -> &'static str {
1523 AsyncGeneratorKind::Block => "`async` block",
1524 AsyncGeneratorKind::Closure => "`async` closure body",
1525 AsyncGeneratorKind::Fn => "`async fn` body",
1530 #[derive(Copy, Clone, Debug)]
1531 pub enum BodyOwnerKind {
1532 /// Functions and methods.
1538 /// Constants and associated constants.
1541 /// Initializer of a `static` item.
1545 impl BodyOwnerKind {
1546 pub fn is_fn_or_closure(self) -> bool {
1548 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1549 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1554 /// The kind of an item that requires const-checking.
1555 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1556 pub enum ConstContext {
1560 /// A `static` or `static mut`.
1563 /// A `const`, associated `const`, or other const context.
1565 /// Other contexts include:
1566 /// - Array length expressions
1567 /// - Enum discriminants
1568 /// - Const generics
1570 /// For the most part, other contexts are treated just like a regular `const`, so they are
1571 /// lumped into the same category.
1576 /// A description of this const context that can appear between backticks in an error message.
1578 /// E.g. `const` or `static mut`.
1579 pub fn keyword_name(self) -> &'static str {
1581 Self::Const => "const",
1582 Self::Static(Mutability::Not) => "static",
1583 Self::Static(Mutability::Mut) => "static mut",
1584 Self::ConstFn => "const fn",
1589 /// A colloquial, trivially pluralizable description of this const context for use in error
1591 impl fmt::Display for ConstContext {
1592 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1594 Self::Const => write!(f, "constant"),
1595 Self::Static(_) => write!(f, "static"),
1596 Self::ConstFn => write!(f, "constant function"),
1601 // NOTE: `IntoDiagnosticArg` impl for `ConstContext` lives in `rustc_errors`
1602 // due to a cyclical dependency between hir that crate.
1605 pub type Lit = Spanned<LitKind>;
1607 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1614 pub fn hir_id(&self) -> HirId {
1616 &ArrayLen::Infer(hir_id, _) | &ArrayLen::Body(AnonConst { hir_id, body: _ }) => hir_id,
1621 /// A constant (expression) that's not an item or associated item,
1622 /// but needs its own `DefId` for type-checking, const-eval, etc.
1623 /// These are usually found nested inside types (e.g., array lengths)
1624 /// or expressions (e.g., repeat counts), and also used to define
1625 /// explicit discriminant values for enum variants.
1627 /// You can check if this anon const is a default in a const param
1628 /// `const N: usize = { ... }` with `tcx.hir().opt_const_param_default_param_hir_id(..)`
1629 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1630 pub struct AnonConst {
1636 #[derive(Debug, HashStable_Generic)]
1637 pub struct Expr<'hir> {
1639 pub kind: ExprKind<'hir>,
1644 pub fn precedence(&self) -> ExprPrecedence {
1646 ExprKind::Box(_) => ExprPrecedence::Box,
1647 ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1648 ExprKind::Array(_) => ExprPrecedence::Array,
1649 ExprKind::Call(..) => ExprPrecedence::Call,
1650 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1651 ExprKind::Tup(_) => ExprPrecedence::Tup,
1652 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1653 ExprKind::Unary(..) => ExprPrecedence::Unary,
1654 ExprKind::Lit(_) => ExprPrecedence::Lit,
1655 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1656 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1657 ExprKind::If(..) => ExprPrecedence::If,
1658 ExprKind::Let(..) => ExprPrecedence::Let,
1659 ExprKind::Loop(..) => ExprPrecedence::Loop,
1660 ExprKind::Match(..) => ExprPrecedence::Match,
1661 ExprKind::Closure { .. } => ExprPrecedence::Closure,
1662 ExprKind::Block(..) => ExprPrecedence::Block,
1663 ExprKind::Assign(..) => ExprPrecedence::Assign,
1664 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1665 ExprKind::Field(..) => ExprPrecedence::Field,
1666 ExprKind::Index(..) => ExprPrecedence::Index,
1667 ExprKind::Path(..) => ExprPrecedence::Path,
1668 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1669 ExprKind::Break(..) => ExprPrecedence::Break,
1670 ExprKind::Continue(..) => ExprPrecedence::Continue,
1671 ExprKind::Ret(..) => ExprPrecedence::Ret,
1672 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1673 ExprKind::Struct(..) => ExprPrecedence::Struct,
1674 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1675 ExprKind::Yield(..) => ExprPrecedence::Yield,
1676 ExprKind::Err => ExprPrecedence::Err,
1680 // Whether this looks like a place expr, without checking for deref
1682 // This will return `true` in some potentially surprising cases such as
1683 // `CONSTANT.field`.
1684 pub fn is_syntactic_place_expr(&self) -> bool {
1685 self.is_place_expr(|_| true)
1688 /// Whether this is a place expression.
1690 /// `allow_projections_from` should return `true` if indexing a field or index expression based
1691 /// on the given expression should be considered a place expression.
1692 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1694 ExprKind::Path(QPath::Resolved(_, ref path)) => {
1695 matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static(_), _) | Res::Err)
1698 // Type ascription inherits its place expression kind from its
1700 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1701 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1703 ExprKind::Unary(UnOp::Deref, _) => true,
1705 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1706 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1709 // Lang item paths cannot currently be local variables or statics.
1710 ExprKind::Path(QPath::LangItem(..)) => false,
1712 // Partially qualified paths in expressions can only legally
1713 // refer to associated items which are always rvalues.
1714 ExprKind::Path(QPath::TypeRelative(..))
1715 | ExprKind::Call(..)
1716 | ExprKind::MethodCall(..)
1717 | ExprKind::Struct(..)
1720 | ExprKind::Match(..)
1721 | ExprKind::Closure { .. }
1722 | ExprKind::Block(..)
1723 | ExprKind::Repeat(..)
1724 | ExprKind::Array(..)
1725 | ExprKind::Break(..)
1726 | ExprKind::Continue(..)
1729 | ExprKind::Loop(..)
1730 | ExprKind::Assign(..)
1731 | ExprKind::InlineAsm(..)
1732 | ExprKind::AssignOp(..)
1734 | ExprKind::ConstBlock(..)
1735 | ExprKind::Unary(..)
1737 | ExprKind::AddrOf(..)
1738 | ExprKind::Binary(..)
1739 | ExprKind::Yield(..)
1740 | ExprKind::Cast(..)
1741 | ExprKind::DropTemps(..)
1742 | ExprKind::Err => false,
1746 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1747 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1748 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1749 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1750 /// beyond remembering to call this function before doing analysis on it.
1751 pub fn peel_drop_temps(&self) -> &Self {
1752 let mut expr = self;
1753 while let ExprKind::DropTemps(inner) = &expr.kind {
1759 pub fn peel_blocks(&self) -> &Self {
1760 let mut expr = self;
1761 while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind {
1767 pub fn can_have_side_effects(&self) -> bool {
1768 match self.peel_drop_temps().kind {
1769 ExprKind::Path(_) | ExprKind::Lit(_) => false,
1770 ExprKind::Type(base, _)
1771 | ExprKind::Unary(_, base)
1772 | ExprKind::Field(base, _)
1773 | ExprKind::Index(base, _)
1774 | ExprKind::AddrOf(.., base)
1775 | ExprKind::Cast(base, _) => {
1776 // This isn't exactly true for `Index` and all `Unary`, but we are using this
1777 // method exclusively for diagnostics and there's a *cultural* pressure against
1778 // them being used only for its side-effects.
1779 base.can_have_side_effects()
1781 ExprKind::Struct(_, fields, init) => fields
1783 .map(|field| field.expr)
1784 .chain(init.into_iter())
1785 .all(|e| e.can_have_side_effects()),
1787 ExprKind::Array(args)
1788 | ExprKind::Tup(args)
1792 ExprKind::Path(QPath::Resolved(
1794 Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. },
1799 ) => args.iter().all(|arg| arg.can_have_side_effects()),
1801 | ExprKind::Match(..)
1802 | ExprKind::MethodCall(..)
1803 | ExprKind::Call(..)
1804 | ExprKind::Closure { .. }
1805 | ExprKind::Block(..)
1806 | ExprKind::Repeat(..)
1807 | ExprKind::Break(..)
1808 | ExprKind::Continue(..)
1811 | ExprKind::Loop(..)
1812 | ExprKind::Assign(..)
1813 | ExprKind::InlineAsm(..)
1814 | ExprKind::AssignOp(..)
1815 | ExprKind::ConstBlock(..)
1817 | ExprKind::Binary(..)
1818 | ExprKind::Yield(..)
1819 | ExprKind::DropTemps(..)
1820 | ExprKind::Err => true,
1824 // To a first-order approximation, is this a pattern
1825 pub fn is_approximately_pattern(&self) -> bool {
1828 | ExprKind::Array(_)
1829 | ExprKind::Call(..)
1833 | ExprKind::Struct(..) => true,
1838 pub fn method_ident(&self) -> Option<Ident> {
1840 ExprKind::MethodCall(receiver_method, ..) => Some(receiver_method.ident),
1841 ExprKind::Unary(_, expr) | ExprKind::AddrOf(.., expr) => expr.method_ident(),
1847 /// Checks if the specified expression is a built-in range literal.
1848 /// (See: `LoweringContext::lower_expr()`).
1849 pub fn is_range_literal(expr: &Expr<'_>) -> bool {
1851 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1852 ExprKind::Struct(ref qpath, _, _) => matches!(
1857 | LangItem::RangeFrom
1858 | LangItem::RangeFull
1859 | LangItem::RangeToInclusive,
1864 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1865 ExprKind::Call(ref func, _) => {
1866 matches!(func.kind, ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, ..)))
1873 #[derive(Debug, HashStable_Generic)]
1874 pub enum ExprKind<'hir> {
1875 /// A `box x` expression.
1876 Box(&'hir Expr<'hir>),
1877 /// Allow anonymous constants from an inline `const` block
1878 ConstBlock(AnonConst),
1879 /// An array (e.g., `[a, b, c, d]`).
1880 Array(&'hir [Expr<'hir>]),
1881 /// A function call.
1883 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1884 /// and the second field is the list of arguments.
1885 /// This also represents calling the constructor of
1886 /// tuple-like ADTs such as tuple structs and enum variants.
1887 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1888 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1890 /// The `PathSegment` represents the method name and its generic arguments
1891 /// (within the angle brackets).
1892 /// The `&Expr` is the expression that evaluates
1893 /// to the object on which the method is being called on (the receiver),
1894 /// and the `&[Expr]` is the rest of the arguments.
1895 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1896 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, x, [a, b, c, d], span)`.
1897 /// The final `Span` represents the span of the function and arguments
1898 /// (e.g. `foo::<Bar, Baz>(a, b, c, d)` in `x.foo::<Bar, Baz>(a, b, c, d)`
1900 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1901 /// the `hir_id` of the `MethodCall` node itself.
1903 /// [`type_dependent_def_id`]: ../../rustc_middle/ty/struct.TypeckResults.html#method.type_dependent_def_id
1904 MethodCall(&'hir PathSegment<'hir>, &'hir Expr<'hir>, &'hir [Expr<'hir>], Span),
1905 /// A tuple (e.g., `(a, b, c, d)`).
1906 Tup(&'hir [Expr<'hir>]),
1907 /// A binary operation (e.g., `a + b`, `a * b`).
1908 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1909 /// A unary operation (e.g., `!x`, `*x`).
1910 Unary(UnOp, &'hir Expr<'hir>),
1911 /// A literal (e.g., `1`, `"foo"`).
1913 /// A cast (e.g., `foo as f64`).
1914 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1915 /// A type reference (e.g., `Foo`).
1916 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1917 /// Wraps the expression in a terminating scope.
1918 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1920 /// This construct only exists to tweak the drop order in HIR lowering.
1921 /// An example of that is the desugaring of `for` loops.
1922 DropTemps(&'hir Expr<'hir>),
1923 /// A `let $pat = $expr` expression.
1925 /// These are not `Local` and only occur as expressions.
1926 /// The `let Some(x) = foo()` in `if let Some(x) = foo()` is an example of `Let(..)`.
1927 Let(&'hir Let<'hir>),
1928 /// An `if` block, with an optional else block.
1930 /// I.e., `if <expr> { <expr> } else { <expr> }`.
1931 If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
1932 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1934 /// I.e., `'label: loop { <block> }`.
1936 /// The `Span` is the loop header (`for x in y`/`while let pat = expr`).
1937 Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span),
1938 /// A `match` block, with a source that indicates whether or not it is
1939 /// the result of a desugaring, and if so, which kind.
1940 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1941 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1943 /// The `Span` is the argument block `|...|`.
1945 /// This may also be a generator literal or an `async block` as indicated by the
1946 /// `Option<Movability>`.
1947 Closure(&'hir Closure<'hir>),
1948 /// A block (e.g., `'label: { ... }`).
1949 Block(&'hir Block<'hir>, Option<Label>),
1951 /// An assignment (e.g., `a = foo()`).
1952 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1953 /// An assignment with an operator.
1956 AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1957 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1958 Field(&'hir Expr<'hir>, Ident),
1959 /// An indexing operation (`foo[2]`).
1960 Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1962 /// Path to a definition, possibly containing lifetime or type parameters.
1965 /// A referencing operation (i.e., `&a` or `&mut a`).
1966 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1967 /// A `break`, with an optional label to break.
1968 Break(Destination, Option<&'hir Expr<'hir>>),
1969 /// A `continue`, with an optional label.
1970 Continue(Destination),
1971 /// A `return`, with an optional value to be returned.
1972 Ret(Option<&'hir Expr<'hir>>),
1974 /// Inline assembly (from `asm!`), with its outputs and inputs.
1975 InlineAsm(&'hir InlineAsm<'hir>),
1977 /// A struct or struct-like variant literal expression.
1979 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1980 /// where `base` is the `Option<Expr>`.
1981 Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], Option<&'hir Expr<'hir>>),
1983 /// An array literal constructed from one repeated element.
1985 /// E.g., `[1; 5]`. The first expression is the element
1986 /// to be repeated; the second is the number of times to repeat it.
1987 Repeat(&'hir Expr<'hir>, ArrayLen),
1989 /// A suspension point for generators (i.e., `yield <expr>`).
1990 Yield(&'hir Expr<'hir>, YieldSource),
1992 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1996 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1998 /// To resolve the path to a `DefId`, call [`qpath_res`].
2000 /// [`qpath_res`]: ../../rustc_middle/ty/struct.TypeckResults.html#method.qpath_res
2001 #[derive(Debug, HashStable_Generic)]
2002 pub enum QPath<'hir> {
2003 /// Path to a definition, optionally "fully-qualified" with a `Self`
2004 /// type, if the path points to an associated item in a trait.
2006 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
2007 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
2008 /// even though they both have the same two-segment `Clone::clone` `Path`.
2009 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
2011 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
2012 /// Will be resolved by type-checking to an associated item.
2014 /// UFCS source paths can desugar into this, with `Vec::new` turning into
2015 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
2016 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
2017 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
2019 /// Reference to a `#[lang = "foo"]` item. `HirId` of the inner expr.
2020 LangItem(LangItem, Span, Option<HirId>),
2023 impl<'hir> QPath<'hir> {
2024 /// Returns the span of this `QPath`.
2025 pub fn span(&self) -> Span {
2027 QPath::Resolved(_, path) => path.span,
2028 QPath::TypeRelative(qself, ps) => qself.span.to(ps.ident.span),
2029 QPath::LangItem(_, span, _) => span,
2033 /// Returns the span of the qself of this `QPath`. For example, `()` in
2034 /// `<() as Trait>::method`.
2035 pub fn qself_span(&self) -> Span {
2037 QPath::Resolved(_, path) => path.span,
2038 QPath::TypeRelative(qself, _) => qself.span,
2039 QPath::LangItem(_, span, _) => span,
2043 /// Returns the span of the last segment of this `QPath`. For example, `method` in
2044 /// `<() as Trait>::method`.
2045 pub fn last_segment_span(&self) -> Span {
2047 QPath::Resolved(_, path) => path.segments.last().unwrap().ident.span,
2048 QPath::TypeRelative(_, segment) => segment.ident.span,
2049 QPath::LangItem(_, span, _) => span,
2054 /// Hints at the original code for a let statement.
2055 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2056 pub enum LocalSource {
2057 /// A `match _ { .. }`.
2059 /// When lowering async functions, we create locals within the `async move` so that
2060 /// all parameters are dropped after the future is polled.
2062 /// ```ignore (pseudo-Rust)
2063 /// async fn foo(<pattern> @ x: Type) {
2065 /// let <pattern> = x;
2070 /// A desugared `<expr>.await`.
2072 /// A desugared `expr = expr`, where the LHS is a tuple, struct or array.
2073 /// The span is that of the `=` sign.
2074 AssignDesugar(Span),
2077 /// Hints at the original code for a `match _ { .. }`.
2078 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
2079 #[derive(HashStable_Generic)]
2080 pub enum MatchSource {
2081 /// A `match _ { .. }`.
2083 /// A desugared `for _ in _ { .. }` loop.
2085 /// A desugared `?` operator.
2087 /// A desugared `<expr>.await`.
2093 pub const fn name(self) -> &'static str {
2097 ForLoopDesugar => "for",
2099 AwaitDesugar => ".await",
2104 /// The loop type that yielded an `ExprKind::Loop`.
2105 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2106 pub enum LoopSource {
2107 /// A `loop { .. }` loop.
2109 /// A `while _ { .. }` loop.
2111 /// A `for _ in _ { .. }` loop.
2116 pub fn name(self) -> &'static str {
2118 LoopSource::Loop => "loop",
2119 LoopSource::While => "while",
2120 LoopSource::ForLoop => "for",
2125 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2126 pub enum LoopIdError {
2128 UnlabeledCfInWhileCondition,
2132 impl fmt::Display for LoopIdError {
2133 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2134 f.write_str(match self {
2135 LoopIdError::OutsideLoopScope => "not inside loop scope",
2136 LoopIdError::UnlabeledCfInWhileCondition => {
2137 "unlabeled control flow (break or continue) in while condition"
2139 LoopIdError::UnresolvedLabel => "label not found",
2144 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2145 pub struct Destination {
2146 // This is `Some(_)` iff there is an explicit user-specified `label
2147 pub label: Option<Label>,
2149 // These errors are caught and then reported during the diagnostics pass in
2150 // librustc_passes/loops.rs
2151 pub target_id: Result<HirId, LoopIdError>,
2154 /// The yield kind that caused an `ExprKind::Yield`.
2155 #[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
2156 pub enum YieldSource {
2157 /// An `<expr>.await`.
2158 Await { expr: Option<HirId> },
2159 /// A plain `yield`.
2164 pub fn is_await(&self) -> bool {
2165 matches!(self, YieldSource::Await { .. })
2169 impl fmt::Display for YieldSource {
2170 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2171 f.write_str(match self {
2172 YieldSource::Await { .. } => "`await`",
2173 YieldSource::Yield => "`yield`",
2178 impl From<GeneratorKind> for YieldSource {
2179 fn from(kind: GeneratorKind) -> Self {
2181 // Guess based on the kind of the current generator.
2182 GeneratorKind::Gen => Self::Yield,
2183 GeneratorKind::Async(_) => Self::Await { expr: None },
2188 // N.B., if you change this, you'll probably want to change the corresponding
2189 // type structure in middle/ty.rs as well.
2190 #[derive(Debug, HashStable_Generic)]
2191 pub struct MutTy<'hir> {
2192 pub ty: &'hir Ty<'hir>,
2193 pub mutbl: Mutability,
2196 /// Represents a function's signature in a trait declaration,
2197 /// trait implementation, or a free function.
2198 #[derive(Debug, HashStable_Generic)]
2199 pub struct FnSig<'hir> {
2200 pub header: FnHeader,
2201 pub decl: &'hir FnDecl<'hir>,
2205 // The bodies for items are stored "out of line", in a separate
2206 // hashmap in the `Crate`. Here we just record the hir-id of the item
2207 // so it can fetched later.
2208 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2209 pub struct TraitItemId {
2210 pub def_id: OwnerId,
2215 pub fn hir_id(&self) -> HirId {
2216 // Items are always HIR owners.
2217 HirId::make_owner(self.def_id.def_id)
2221 /// Represents an item declaration within a trait declaration,
2222 /// possibly including a default implementation. A trait item is
2223 /// either required (meaning it doesn't have an implementation, just a
2224 /// signature) or provided (meaning it has a default implementation).
2225 #[derive(Debug, HashStable_Generic)]
2226 pub struct TraitItem<'hir> {
2228 pub def_id: OwnerId,
2229 pub generics: &'hir Generics<'hir>,
2230 pub kind: TraitItemKind<'hir>,
2232 pub defaultness: Defaultness,
2235 impl TraitItem<'_> {
2237 pub fn hir_id(&self) -> HirId {
2238 // Items are always HIR owners.
2239 HirId::make_owner(self.def_id.def_id)
2242 pub fn trait_item_id(&self) -> TraitItemId {
2243 TraitItemId { def_id: self.def_id }
2247 /// Represents a trait method's body (or just argument names).
2248 #[derive(Encodable, Debug, HashStable_Generic)]
2249 pub enum TraitFn<'hir> {
2250 /// No default body in the trait, just a signature.
2251 Required(&'hir [Ident]),
2253 /// Both signature and body are provided in the trait.
2257 /// Represents a trait method or associated constant or type
2258 #[derive(Debug, HashStable_Generic)]
2259 pub enum TraitItemKind<'hir> {
2260 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
2261 Const(&'hir Ty<'hir>, Option<BodyId>),
2262 /// An associated function with an optional body.
2263 Fn(FnSig<'hir>, TraitFn<'hir>),
2264 /// An associated type with (possibly empty) bounds and optional concrete
2266 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
2269 // The bodies for items are stored "out of line", in a separate
2270 // hashmap in the `Crate`. Here we just record the hir-id of the item
2271 // so it can fetched later.
2272 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2273 pub struct ImplItemId {
2274 pub def_id: OwnerId,
2279 pub fn hir_id(&self) -> HirId {
2280 // Items are always HIR owners.
2281 HirId::make_owner(self.def_id.def_id)
2285 /// Represents anything within an `impl` block.
2286 #[derive(Debug, HashStable_Generic)]
2287 pub struct ImplItem<'hir> {
2289 pub def_id: OwnerId,
2290 pub generics: &'hir Generics<'hir>,
2291 pub kind: ImplItemKind<'hir>,
2292 pub defaultness: Defaultness,
2299 pub fn hir_id(&self) -> HirId {
2300 // Items are always HIR owners.
2301 HirId::make_owner(self.def_id.def_id)
2304 pub fn impl_item_id(&self) -> ImplItemId {
2305 ImplItemId { def_id: self.def_id }
2309 /// Represents various kinds of content within an `impl`.
2310 #[derive(Debug, HashStable_Generic)]
2311 pub enum ImplItemKind<'hir> {
2312 /// An associated constant of the given type, set to the constant result
2313 /// of the expression.
2314 Const(&'hir Ty<'hir>, BodyId),
2315 /// An associated function implementation with the given signature and body.
2316 Fn(FnSig<'hir>, BodyId),
2317 /// An associated type.
2318 Type(&'hir Ty<'hir>),
2321 // The name of the associated type for `Fn` return types.
2322 pub const FN_OUTPUT_NAME: Symbol = sym::Output;
2324 /// Bind a type to an associated type (i.e., `A = Foo`).
2326 /// Bindings like `A: Debug` are represented as a special type `A =
2327 /// $::Debug` that is understood by the astconv code.
2329 /// FIXME(alexreg): why have a separate type for the binding case,
2330 /// wouldn't it be better to make the `ty` field an enum like the
2333 /// ```ignore (pseudo-rust)
2334 /// enum TypeBindingKind {
2339 #[derive(Debug, HashStable_Generic)]
2340 pub struct TypeBinding<'hir> {
2343 pub gen_args: &'hir GenericArgs<'hir>,
2344 pub kind: TypeBindingKind<'hir>,
2348 #[derive(Debug, HashStable_Generic)]
2349 pub enum Term<'hir> {
2354 impl<'hir> From<&'hir Ty<'hir>> for Term<'hir> {
2355 fn from(ty: &'hir Ty<'hir>) -> Self {
2360 impl<'hir> From<AnonConst> for Term<'hir> {
2361 fn from(c: AnonConst) -> Self {
2366 // Represents the two kinds of type bindings.
2367 #[derive(Debug, HashStable_Generic)]
2368 pub enum TypeBindingKind<'hir> {
2369 /// E.g., `Foo<Bar: Send>`.
2370 Constraint { bounds: &'hir [GenericBound<'hir>] },
2371 /// E.g., `Foo<Bar = ()>`, `Foo<Bar = ()>`
2372 Equality { term: Term<'hir> },
2375 impl TypeBinding<'_> {
2376 pub fn ty(&self) -> &Ty<'_> {
2378 TypeBindingKind::Equality { term: Term::Ty(ref ty) } => ty,
2379 _ => panic!("expected equality type binding for parenthesized generic args"),
2382 pub fn opt_const(&self) -> Option<&'_ AnonConst> {
2384 TypeBindingKind::Equality { term: Term::Const(ref c) } => Some(c),
2390 #[derive(Debug, HashStable_Generic)]
2391 pub struct Ty<'hir> {
2393 pub kind: TyKind<'hir>,
2397 impl<'hir> Ty<'hir> {
2398 /// Returns `true` if `param_def_id` matches the `bounded_ty` of this predicate.
2399 pub fn as_generic_param(&self) -> Option<(DefId, Ident)> {
2400 let TyKind::Path(QPath::Resolved(None, path)) = self.kind else {
2403 let [segment] = &path.segments else {
2407 Res::Def(DefKind::TyParam, def_id) | Res::SelfTyParam { trait_: def_id } => {
2408 Some((def_id, segment.ident))
2414 pub fn peel_refs(&self) -> &Self {
2415 let mut final_ty = self;
2416 while let TyKind::Rptr(_, MutTy { ty, .. }) = &final_ty.kind {
2423 /// Not represented directly in the AST; referred to by name through a `ty_path`.
2424 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
2425 #[derive(HashStable_Generic)]
2436 /// All of the primitive types
2437 pub const ALL: [Self; 17] = [
2438 // any changes here should also be reflected in `PrimTy::from_name`
2439 Self::Int(IntTy::I8),
2440 Self::Int(IntTy::I16),
2441 Self::Int(IntTy::I32),
2442 Self::Int(IntTy::I64),
2443 Self::Int(IntTy::I128),
2444 Self::Int(IntTy::Isize),
2445 Self::Uint(UintTy::U8),
2446 Self::Uint(UintTy::U16),
2447 Self::Uint(UintTy::U32),
2448 Self::Uint(UintTy::U64),
2449 Self::Uint(UintTy::U128),
2450 Self::Uint(UintTy::Usize),
2451 Self::Float(FloatTy::F32),
2452 Self::Float(FloatTy::F64),
2458 /// Like [`PrimTy::name`], but returns a &str instead of a symbol.
2461 pub fn name_str(self) -> &'static str {
2463 PrimTy::Int(i) => i.name_str(),
2464 PrimTy::Uint(u) => u.name_str(),
2465 PrimTy::Float(f) => f.name_str(),
2466 PrimTy::Str => "str",
2467 PrimTy::Bool => "bool",
2468 PrimTy::Char => "char",
2472 pub fn name(self) -> Symbol {
2474 PrimTy::Int(i) => i.name(),
2475 PrimTy::Uint(u) => u.name(),
2476 PrimTy::Float(f) => f.name(),
2477 PrimTy::Str => sym::str,
2478 PrimTy::Bool => sym::bool,
2479 PrimTy::Char => sym::char,
2483 /// Returns the matching `PrimTy` for a `Symbol` such as "str" or "i32".
2484 /// Returns `None` if no matching type is found.
2485 pub fn from_name(name: Symbol) -> Option<Self> {
2486 let ty = match name {
2487 // any changes here should also be reflected in `PrimTy::ALL`
2488 sym::i8 => Self::Int(IntTy::I8),
2489 sym::i16 => Self::Int(IntTy::I16),
2490 sym::i32 => Self::Int(IntTy::I32),
2491 sym::i64 => Self::Int(IntTy::I64),
2492 sym::i128 => Self::Int(IntTy::I128),
2493 sym::isize => Self::Int(IntTy::Isize),
2494 sym::u8 => Self::Uint(UintTy::U8),
2495 sym::u16 => Self::Uint(UintTy::U16),
2496 sym::u32 => Self::Uint(UintTy::U32),
2497 sym::u64 => Self::Uint(UintTy::U64),
2498 sym::u128 => Self::Uint(UintTy::U128),
2499 sym::usize => Self::Uint(UintTy::Usize),
2500 sym::f32 => Self::Float(FloatTy::F32),
2501 sym::f64 => Self::Float(FloatTy::F64),
2502 sym::bool => Self::Bool,
2503 sym::char => Self::Char,
2504 sym::str => Self::Str,
2511 #[derive(Debug, HashStable_Generic)]
2512 pub struct BareFnTy<'hir> {
2513 pub unsafety: Unsafety,
2515 pub generic_params: &'hir [GenericParam<'hir>],
2516 pub decl: &'hir FnDecl<'hir>,
2517 pub param_names: &'hir [Ident],
2520 #[derive(Debug, HashStable_Generic)]
2521 pub struct OpaqueTy<'hir> {
2522 pub generics: &'hir Generics<'hir>,
2523 pub bounds: GenericBounds<'hir>,
2524 pub origin: OpaqueTyOrigin,
2528 /// From whence the opaque type came.
2529 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2530 pub enum OpaqueTyOrigin {
2532 FnReturn(LocalDefId),
2534 AsyncFn(LocalDefId),
2535 /// type aliases: `type Foo = impl Trait;`
2539 /// The various kinds of types recognized by the compiler.
2540 #[derive(Debug, HashStable_Generic)]
2541 pub enum TyKind<'hir> {
2542 /// A variable length slice (i.e., `[T]`).
2543 Slice(&'hir Ty<'hir>),
2544 /// A fixed length array (i.e., `[T; n]`).
2545 Array(&'hir Ty<'hir>, ArrayLen),
2546 /// A raw pointer (i.e., `*const T` or `*mut T`).
2548 /// A reference (i.e., `&'a T` or `&'a mut T`).
2549 Rptr(&'hir Lifetime, MutTy<'hir>),
2550 /// A bare function (e.g., `fn(usize) -> bool`).
2551 BareFn(&'hir BareFnTy<'hir>),
2552 /// The never type (`!`).
2554 /// A tuple (`(A, B, C, D, ...)`).
2555 Tup(&'hir [Ty<'hir>]),
2556 /// A path to a type definition (`module::module::...::Type`), or an
2557 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2559 /// Type parameters may be stored in each `PathSegment`.
2561 /// An opaque type definition itself. This is only used for `impl Trait`.
2563 /// The generic argument list contains the lifetimes (and in the future
2564 /// possibly parameters) that are actually bound on the `impl Trait`.
2566 /// The last parameter specifies whether this opaque appears in a trait definition.
2567 OpaqueDef(ItemId, &'hir [GenericArg<'hir>], bool),
2568 /// A trait object type `Bound1 + Bound2 + Bound3`
2569 /// where `Bound` is a trait or a lifetime.
2570 TraitObject(&'hir [PolyTraitRef<'hir>], &'hir Lifetime, TraitObjectSyntax),
2573 /// `TyKind::Infer` means the type should be inferred instead of it having been
2574 /// specified. This can appear anywhere in a type.
2576 /// Placeholder for a type that has failed to be defined.
2580 #[derive(Debug, HashStable_Generic)]
2581 pub enum InlineAsmOperand<'hir> {
2583 reg: InlineAsmRegOrRegClass,
2584 expr: &'hir Expr<'hir>,
2587 reg: InlineAsmRegOrRegClass,
2589 expr: Option<&'hir Expr<'hir>>,
2592 reg: InlineAsmRegOrRegClass,
2594 expr: &'hir Expr<'hir>,
2597 reg: InlineAsmRegOrRegClass,
2599 in_expr: &'hir Expr<'hir>,
2600 out_expr: Option<&'hir Expr<'hir>>,
2603 anon_const: AnonConst,
2606 anon_const: AnonConst,
2614 impl<'hir> InlineAsmOperand<'hir> {
2615 pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
2617 Self::In { reg, .. }
2618 | Self::Out { reg, .. }
2619 | Self::InOut { reg, .. }
2620 | Self::SplitInOut { reg, .. } => Some(reg),
2621 Self::Const { .. } | Self::SymFn { .. } | Self::SymStatic { .. } => None,
2625 pub fn is_clobber(&self) -> bool {
2628 InlineAsmOperand::Out { reg: InlineAsmRegOrRegClass::Reg(_), late: _, expr: None }
2633 #[derive(Debug, HashStable_Generic)]
2634 pub struct InlineAsm<'hir> {
2635 pub template: &'hir [InlineAsmTemplatePiece],
2636 pub template_strs: &'hir [(Symbol, Option<Symbol>, Span)],
2637 pub operands: &'hir [(InlineAsmOperand<'hir>, Span)],
2638 pub options: InlineAsmOptions,
2639 pub line_spans: &'hir [Span],
2642 /// Represents a parameter in a function header.
2643 #[derive(Debug, HashStable_Generic)]
2644 pub struct Param<'hir> {
2646 pub pat: &'hir Pat<'hir>,
2651 /// Represents the header (not the body) of a function declaration.
2652 #[derive(Debug, HashStable_Generic)]
2653 pub struct FnDecl<'hir> {
2654 /// The types of the function's parameters.
2656 /// Additional argument data is stored in the function's [body](Body::params).
2657 pub inputs: &'hir [Ty<'hir>],
2658 pub output: FnRetTy<'hir>,
2659 pub c_variadic: bool,
2660 /// Does the function have an implicit self?
2661 pub implicit_self: ImplicitSelfKind,
2664 /// Represents what type of implicit self a function has, if any.
2665 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2666 pub enum ImplicitSelfKind {
2667 /// Represents a `fn x(self);`.
2669 /// Represents a `fn x(mut self);`.
2671 /// Represents a `fn x(&self);`.
2673 /// Represents a `fn x(&mut self);`.
2675 /// Represents when a function does not have a self argument or
2676 /// when a function has a `self: X` argument.
2680 impl ImplicitSelfKind {
2681 /// Does this represent an implicit self?
2682 pub fn has_implicit_self(&self) -> bool {
2683 !matches!(*self, ImplicitSelfKind::None)
2687 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable, Debug)]
2688 #[derive(HashStable_Generic)]
2694 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable, HashStable_Generic)]
2695 pub enum Defaultness {
2696 Default { has_value: bool },
2701 pub fn has_value(&self) -> bool {
2703 Defaultness::Default { has_value } => has_value,
2704 Defaultness::Final => true,
2708 pub fn is_final(&self) -> bool {
2709 *self == Defaultness::Final
2712 pub fn is_default(&self) -> bool {
2713 matches!(*self, Defaultness::Default { .. })
2717 #[derive(Debug, HashStable_Generic)]
2718 pub enum FnRetTy<'hir> {
2719 /// Return type is not specified.
2721 /// Functions default to `()` and
2722 /// closures default to inference. Span points to where return
2723 /// type would be inserted.
2724 DefaultReturn(Span),
2725 /// Everything else.
2726 Return(&'hir Ty<'hir>),
2731 pub fn span(&self) -> Span {
2733 Self::DefaultReturn(span) => span,
2734 Self::Return(ref ty) => ty.span,
2739 /// Represents `for<...>` binder before a closure
2740 #[derive(Copy, Clone, Debug, HashStable_Generic)]
2741 pub enum ClosureBinder {
2742 /// Binder is not specified.
2744 /// Binder is specified.
2746 /// Span points to the whole `for<...>`.
2750 #[derive(Encodable, Debug, HashStable_Generic)]
2751 pub struct Mod<'hir> {
2752 pub spans: ModSpans,
2753 pub item_ids: &'hir [ItemId],
2756 #[derive(Copy, Clone, Debug, HashStable_Generic, Encodable)]
2757 pub struct ModSpans {
2758 /// A span from the first token past `{` to the last token until `}`.
2759 /// For `mod foo;`, the inner span ranges from the first token
2760 /// to the last token in the external file.
2761 pub inner_span: Span,
2762 pub inject_use_span: Span,
2765 #[derive(Debug, HashStable_Generic)]
2766 pub struct EnumDef<'hir> {
2767 pub variants: &'hir [Variant<'hir>],
2770 #[derive(Debug, HashStable_Generic)]
2771 pub struct Variant<'hir> {
2772 /// Name of the variant.
2774 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2776 /// Fields and constructor id of the variant.
2777 pub data: VariantData<'hir>,
2778 /// Explicit discriminant (e.g., `Foo = 1`).
2779 pub disr_expr: Option<AnonConst>,
2784 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2786 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2787 /// Also produced for each element of a list `use`, e.g.
2788 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2791 /// Glob import, e.g., `use foo::*`.
2794 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2795 /// an additional `use foo::{}` for performing checks such as
2796 /// unstable feature gating. May be removed in the future.
2800 /// References to traits in impls.
2802 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2803 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2804 /// trait being referred to but just a unique `HirId` that serves as a key
2805 /// within the resolution map.
2806 #[derive(Clone, Debug, HashStable_Generic)]
2807 pub struct TraitRef<'hir> {
2808 pub path: &'hir Path<'hir>,
2809 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2810 #[stable_hasher(ignore)]
2811 pub hir_ref_id: HirId,
2815 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2816 pub fn trait_def_id(&self) -> Option<DefId> {
2817 match self.path.res {
2818 Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
2820 _ => unreachable!(),
2825 #[derive(Clone, Debug, HashStable_Generic)]
2826 pub struct PolyTraitRef<'hir> {
2827 /// The `'a` in `for<'a> Foo<&'a T>`.
2828 pub bound_generic_params: &'hir [GenericParam<'hir>],
2830 /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
2831 pub trait_ref: TraitRef<'hir>,
2836 #[derive(Debug, HashStable_Generic)]
2837 pub struct FieldDef<'hir> {
2842 pub ty: &'hir Ty<'hir>,
2846 // Still necessary in couple of places
2847 pub fn is_positional(&self) -> bool {
2848 let first = self.ident.as_str().as_bytes()[0];
2849 (b'0'..=b'9').contains(&first)
2853 /// Fields and constructor IDs of enum variants and structs.
2854 #[derive(Debug, HashStable_Generic)]
2855 pub enum VariantData<'hir> {
2856 /// A struct variant.
2858 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2859 Struct(&'hir [FieldDef<'hir>], /* recovered */ bool),
2860 /// A tuple variant.
2862 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2863 Tuple(&'hir [FieldDef<'hir>], HirId),
2866 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2870 impl<'hir> VariantData<'hir> {
2871 /// Return the fields of this variant.
2872 pub fn fields(&self) -> &'hir [FieldDef<'hir>] {
2874 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2879 /// Return the `HirId` of this variant's constructor, if it has one.
2880 pub fn ctor_hir_id(&self) -> Option<HirId> {
2882 VariantData::Struct(_, _) => None,
2883 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2888 // The bodies for items are stored "out of line", in a separate
2889 // hashmap in the `Crate`. Here we just record the hir-id of the item
2890 // so it can fetched later.
2891 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
2893 pub def_id: OwnerId,
2898 pub fn hir_id(&self) -> HirId {
2899 // Items are always HIR owners.
2900 HirId::make_owner(self.def_id.def_id)
2906 /// The name might be a dummy name in case of anonymous items
2907 #[derive(Debug, HashStable_Generic)]
2908 pub struct Item<'hir> {
2910 pub def_id: OwnerId,
2911 pub kind: ItemKind<'hir>,
2918 pub fn hir_id(&self) -> HirId {
2919 // Items are always HIR owners.
2920 HirId::make_owner(self.def_id.def_id)
2923 pub fn item_id(&self) -> ItemId {
2924 ItemId { def_id: self.def_id }
2928 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2929 #[derive(Encodable, Decodable, HashStable_Generic)]
2936 pub fn prefix_str(&self) -> &'static str {
2938 Self::Unsafe => "unsafe ",
2944 impl fmt::Display for Unsafety {
2945 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2946 f.write_str(match *self {
2947 Self::Unsafe => "unsafe",
2948 Self::Normal => "normal",
2953 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2954 #[derive(Encodable, Decodable, HashStable_Generic)]
2955 pub enum Constness {
2960 impl fmt::Display for Constness {
2961 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2962 f.write_str(match *self {
2963 Self::Const => "const",
2964 Self::NotConst => "non-const",
2969 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2970 pub struct FnHeader {
2971 pub unsafety: Unsafety,
2972 pub constness: Constness,
2973 pub asyncness: IsAsync,
2978 pub fn is_async(&self) -> bool {
2979 matches!(&self.asyncness, IsAsync::Async)
2982 pub fn is_const(&self) -> bool {
2983 matches!(&self.constness, Constness::Const)
2986 pub fn is_unsafe(&self) -> bool {
2987 matches!(&self.unsafety, Unsafety::Unsafe)
2991 #[derive(Debug, HashStable_Generic)]
2992 pub enum ItemKind<'hir> {
2993 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2995 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2996 ExternCrate(Option<Symbol>),
2998 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
3002 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
3003 Use(&'hir Path<'hir>, UseKind),
3005 /// A `static` item.
3006 Static(&'hir Ty<'hir>, Mutability, BodyId),
3008 Const(&'hir Ty<'hir>, BodyId),
3009 /// A function declaration.
3010 Fn(FnSig<'hir>, &'hir Generics<'hir>, BodyId),
3011 /// A MBE macro definition (`macro_rules!` or `macro`).
3012 Macro(ast::MacroDef, MacroKind),
3014 Mod(&'hir Mod<'hir>),
3015 /// An external module, e.g. `extern { .. }`.
3016 ForeignMod { abi: Abi, items: &'hir [ForeignItemRef] },
3017 /// Module-level inline assembly (from `global_asm!`).
3018 GlobalAsm(&'hir InlineAsm<'hir>),
3019 /// A type alias, e.g., `type Foo = Bar<u8>`.
3020 TyAlias(&'hir Ty<'hir>, &'hir Generics<'hir>),
3021 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
3022 OpaqueTy(OpaqueTy<'hir>),
3023 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
3024 Enum(EnumDef<'hir>, &'hir Generics<'hir>),
3025 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
3026 Struct(VariantData<'hir>, &'hir Generics<'hir>),
3027 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
3028 Union(VariantData<'hir>, &'hir Generics<'hir>),
3029 /// A trait definition.
3030 Trait(IsAuto, Unsafety, &'hir Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
3032 TraitAlias(&'hir Generics<'hir>, GenericBounds<'hir>),
3034 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
3035 Impl(&'hir Impl<'hir>),
3038 #[derive(Debug, HashStable_Generic)]
3039 pub struct Impl<'hir> {
3040 pub unsafety: Unsafety,
3041 pub polarity: ImplPolarity,
3042 pub defaultness: Defaultness,
3043 // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata
3044 // decoding as `Span`s cannot be decoded when a `Session` is not available.
3045 pub defaultness_span: Option<Span>,
3046 pub constness: Constness,
3047 pub generics: &'hir Generics<'hir>,
3049 /// The trait being implemented, if any.
3050 pub of_trait: Option<TraitRef<'hir>>,
3052 pub self_ty: &'hir Ty<'hir>,
3053 pub items: &'hir [ImplItemRef],
3057 pub fn generics(&self) -> Option<&Generics<'_>> {
3059 ItemKind::Fn(_, ref generics, _)
3060 | ItemKind::TyAlias(_, ref generics)
3061 | ItemKind::OpaqueTy(OpaqueTy { ref generics, .. })
3062 | ItemKind::Enum(_, ref generics)
3063 | ItemKind::Struct(_, ref generics)
3064 | ItemKind::Union(_, ref generics)
3065 | ItemKind::Trait(_, _, ref generics, _, _)
3066 | ItemKind::TraitAlias(ref generics, _)
3067 | ItemKind::Impl(Impl { ref generics, .. }) => generics,
3072 pub fn descr(&self) -> &'static str {
3074 ItemKind::ExternCrate(..) => "extern crate",
3075 ItemKind::Use(..) => "`use` import",
3076 ItemKind::Static(..) => "static item",
3077 ItemKind::Const(..) => "constant item",
3078 ItemKind::Fn(..) => "function",
3079 ItemKind::Macro(..) => "macro",
3080 ItemKind::Mod(..) => "module",
3081 ItemKind::ForeignMod { .. } => "extern block",
3082 ItemKind::GlobalAsm(..) => "global asm item",
3083 ItemKind::TyAlias(..) => "type alias",
3084 ItemKind::OpaqueTy(..) => "opaque type",
3085 ItemKind::Enum(..) => "enum",
3086 ItemKind::Struct(..) => "struct",
3087 ItemKind::Union(..) => "union",
3088 ItemKind::Trait(..) => "trait",
3089 ItemKind::TraitAlias(..) => "trait alias",
3090 ItemKind::Impl(..) => "implementation",
3095 /// A reference from an trait to one of its associated items. This
3096 /// contains the item's id, naturally, but also the item's name and
3097 /// some other high-level details (like whether it is an associated
3098 /// type or method, and whether it is public). This allows other
3099 /// passes to find the impl they want without loading the ID (which
3100 /// means fewer edges in the incremental compilation graph).
3101 #[derive(Encodable, Debug, HashStable_Generic)]
3102 pub struct TraitItemRef {
3103 pub id: TraitItemId,
3105 pub kind: AssocItemKind,
3109 /// A reference from an impl to one of its associated items. This
3110 /// contains the item's ID, naturally, but also the item's name and
3111 /// some other high-level details (like whether it is an associated
3112 /// type or method, and whether it is public). This allows other
3113 /// passes to find the impl they want without loading the ID (which
3114 /// means fewer edges in the incremental compilation graph).
3115 #[derive(Debug, HashStable_Generic)]
3116 pub struct ImplItemRef {
3119 pub kind: AssocItemKind,
3121 /// When we are in a trait impl, link to the trait-item's id.
3122 pub trait_item_def_id: Option<DefId>,
3125 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
3126 pub enum AssocItemKind {
3128 Fn { has_self: bool },
3132 // The bodies for items are stored "out of line", in a separate
3133 // hashmap in the `Crate`. Here we just record the hir-id of the item
3134 // so it can fetched later.
3135 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3136 pub struct ForeignItemId {
3137 pub def_id: OwnerId,
3140 impl ForeignItemId {
3142 pub fn hir_id(&self) -> HirId {
3143 // Items are always HIR owners.
3144 HirId::make_owner(self.def_id.def_id)
3148 /// A reference from a foreign block to one of its items. This
3149 /// contains the item's ID, naturally, but also the item's name and
3150 /// some other high-level details (like whether it is an associated
3151 /// type or method, and whether it is public). This allows other
3152 /// passes to find the impl they want without loading the ID (which
3153 /// means fewer edges in the incremental compilation graph).
3154 #[derive(Debug, HashStable_Generic)]
3155 pub struct ForeignItemRef {
3156 pub id: ForeignItemId,
3161 #[derive(Debug, HashStable_Generic)]
3162 pub struct ForeignItem<'hir> {
3164 pub kind: ForeignItemKind<'hir>,
3165 pub def_id: OwnerId,
3170 impl ForeignItem<'_> {
3172 pub fn hir_id(&self) -> HirId {
3173 // Items are always HIR owners.
3174 HirId::make_owner(self.def_id.def_id)
3177 pub fn foreign_item_id(&self) -> ForeignItemId {
3178 ForeignItemId { def_id: self.def_id }
3182 /// An item within an `extern` block.
3183 #[derive(Debug, HashStable_Generic)]
3184 pub enum ForeignItemKind<'hir> {
3185 /// A foreign function.
3186 Fn(&'hir FnDecl<'hir>, &'hir [Ident], &'hir Generics<'hir>),
3187 /// A foreign static item (`static ext: u8`).
3188 Static(&'hir Ty<'hir>, Mutability),
3193 /// A variable captured by a closure.
3194 #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)]
3196 // First span where it is accessed (there can be multiple).
3200 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
3201 // has length > 0 if the trait is found through an chain of imports, starting with the
3202 // import/use statement in the scope where the trait is used.
3203 #[derive(Encodable, Decodable, Clone, Debug, HashStable_Generic)]
3204 pub struct TraitCandidate {
3206 pub import_ids: SmallVec<[LocalDefId; 1]>,
3209 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3210 pub enum OwnerNode<'hir> {
3211 Item(&'hir Item<'hir>),
3212 ForeignItem(&'hir ForeignItem<'hir>),
3213 TraitItem(&'hir TraitItem<'hir>),
3214 ImplItem(&'hir ImplItem<'hir>),
3215 Crate(&'hir Mod<'hir>),
3218 impl<'hir> OwnerNode<'hir> {
3219 pub fn ident(&self) -> Option<Ident> {
3221 OwnerNode::Item(Item { ident, .. })
3222 | OwnerNode::ForeignItem(ForeignItem { ident, .. })
3223 | OwnerNode::ImplItem(ImplItem { ident, .. })
3224 | OwnerNode::TraitItem(TraitItem { ident, .. }) => Some(*ident),
3225 OwnerNode::Crate(..) => None,
3229 pub fn span(&self) -> Span {
3231 OwnerNode::Item(Item { span, .. })
3232 | OwnerNode::ForeignItem(ForeignItem { span, .. })
3233 | OwnerNode::ImplItem(ImplItem { span, .. })
3234 | OwnerNode::TraitItem(TraitItem { span, .. }) => *span,
3235 OwnerNode::Crate(Mod { spans: ModSpans { inner_span, .. }, .. }) => *inner_span,
3239 pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
3241 OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3242 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3243 | OwnerNode::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3244 OwnerNode::ForeignItem(ForeignItem {
3245 kind: ForeignItemKind::Fn(fn_decl, _, _),
3247 }) => Some(fn_decl),
3252 pub fn body_id(&self) -> Option<BodyId> {
3254 OwnerNode::TraitItem(TraitItem {
3255 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3258 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3259 | OwnerNode::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3264 pub fn generics(self) -> Option<&'hir Generics<'hir>> {
3265 Node::generics(self.into())
3268 pub fn def_id(self) -> OwnerId {
3270 OwnerNode::Item(Item { def_id, .. })
3271 | OwnerNode::TraitItem(TraitItem { def_id, .. })
3272 | OwnerNode::ImplItem(ImplItem { def_id, .. })
3273 | OwnerNode::ForeignItem(ForeignItem { def_id, .. }) => *def_id,
3274 OwnerNode::Crate(..) => crate::CRATE_HIR_ID.owner,
3278 pub fn expect_item(self) -> &'hir Item<'hir> {
3280 OwnerNode::Item(n) => n,
3285 pub fn expect_foreign_item(self) -> &'hir ForeignItem<'hir> {
3287 OwnerNode::ForeignItem(n) => n,
3292 pub fn expect_impl_item(self) -> &'hir ImplItem<'hir> {
3294 OwnerNode::ImplItem(n) => n,
3299 pub fn expect_trait_item(self) -> &'hir TraitItem<'hir> {
3301 OwnerNode::TraitItem(n) => n,
3307 impl<'hir> Into<OwnerNode<'hir>> for &'hir Item<'hir> {
3308 fn into(self) -> OwnerNode<'hir> {
3309 OwnerNode::Item(self)
3313 impl<'hir> Into<OwnerNode<'hir>> for &'hir ForeignItem<'hir> {
3314 fn into(self) -> OwnerNode<'hir> {
3315 OwnerNode::ForeignItem(self)
3319 impl<'hir> Into<OwnerNode<'hir>> for &'hir ImplItem<'hir> {
3320 fn into(self) -> OwnerNode<'hir> {
3321 OwnerNode::ImplItem(self)
3325 impl<'hir> Into<OwnerNode<'hir>> for &'hir TraitItem<'hir> {
3326 fn into(self) -> OwnerNode<'hir> {
3327 OwnerNode::TraitItem(self)
3331 impl<'hir> Into<Node<'hir>> for OwnerNode<'hir> {
3332 fn into(self) -> Node<'hir> {
3334 OwnerNode::Item(n) => Node::Item(n),
3335 OwnerNode::ForeignItem(n) => Node::ForeignItem(n),
3336 OwnerNode::ImplItem(n) => Node::ImplItem(n),
3337 OwnerNode::TraitItem(n) => Node::TraitItem(n),
3338 OwnerNode::Crate(n) => Node::Crate(n),
3343 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3344 pub enum Node<'hir> {
3345 Param(&'hir Param<'hir>),
3346 Item(&'hir Item<'hir>),
3347 ForeignItem(&'hir ForeignItem<'hir>),
3348 TraitItem(&'hir TraitItem<'hir>),
3349 ImplItem(&'hir ImplItem<'hir>),
3350 Variant(&'hir Variant<'hir>),
3351 Field(&'hir FieldDef<'hir>),
3352 AnonConst(&'hir AnonConst),
3353 Expr(&'hir Expr<'hir>),
3354 ExprField(&'hir ExprField<'hir>),
3355 Stmt(&'hir Stmt<'hir>),
3356 PathSegment(&'hir PathSegment<'hir>),
3358 TypeBinding(&'hir TypeBinding<'hir>),
3359 TraitRef(&'hir TraitRef<'hir>),
3360 Pat(&'hir Pat<'hir>),
3361 PatField(&'hir PatField<'hir>),
3362 Arm(&'hir Arm<'hir>),
3363 Block(&'hir Block<'hir>),
3364 Local(&'hir Local<'hir>),
3366 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
3367 /// with synthesized constructors.
3368 Ctor(&'hir VariantData<'hir>),
3370 Lifetime(&'hir Lifetime),
3371 GenericParam(&'hir GenericParam<'hir>),
3373 Crate(&'hir Mod<'hir>),
3375 Infer(&'hir InferArg),
3378 impl<'hir> Node<'hir> {
3379 /// Get the identifier of this `Node`, if applicable.
3383 /// Calling `.ident()` on a [`Node::Ctor`] will return `None`
3384 /// because `Ctor`s do not have identifiers themselves.
3385 /// Instead, call `.ident()` on the parent struct/variant, like so:
3387 /// ```ignore (illustrative)
3390 /// .and_then(|ctor_id| tcx.hir().find(tcx.hir().get_parent_node(ctor_id)))
3391 /// .and_then(|parent| parent.ident())
3393 pub fn ident(&self) -> Option<Ident> {
3395 Node::TraitItem(TraitItem { ident, .. })
3396 | Node::ImplItem(ImplItem { ident, .. })
3397 | Node::ForeignItem(ForeignItem { ident, .. })
3398 | Node::Field(FieldDef { ident, .. })
3399 | Node::Variant(Variant { ident, .. })
3400 | Node::Item(Item { ident, .. })
3401 | Node::PathSegment(PathSegment { ident, .. }) => Some(*ident),
3402 Node::Lifetime(lt) => Some(lt.name.ident()),
3403 Node::GenericParam(p) => Some(p.name.ident()),
3404 Node::TypeBinding(b) => Some(b.ident),
3406 | Node::AnonConst(..)
3412 | Node::PatField(..)
3413 | Node::ExprField(..)
3418 | Node::TraitRef(..)
3419 | Node::Infer(..) => None,
3423 pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
3425 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3426 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3427 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3428 Node::Expr(Expr { kind: ExprKind::Closure(Closure { fn_decl, .. }), .. })
3429 | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
3436 pub fn fn_sig(self) -> Option<&'hir FnSig<'hir>> {
3438 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3439 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3440 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig),
3445 pub fn body_id(&self) -> Option<BodyId> {
3447 Node::TraitItem(TraitItem {
3448 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3451 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3452 | Node::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3457 pub fn generics(self) -> Option<&'hir Generics<'hir>> {
3459 Node::ForeignItem(ForeignItem {
3460 kind: ForeignItemKind::Fn(_, _, generics), ..
3462 | Node::TraitItem(TraitItem { generics, .. })
3463 | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
3464 Node::Item(item) => item.kind.generics(),
3469 pub fn as_owner(self) -> Option<OwnerNode<'hir>> {
3471 Node::Item(i) => Some(OwnerNode::Item(i)),
3472 Node::ForeignItem(i) => Some(OwnerNode::ForeignItem(i)),
3473 Node::TraitItem(i) => Some(OwnerNode::TraitItem(i)),
3474 Node::ImplItem(i) => Some(OwnerNode::ImplItem(i)),
3475 Node::Crate(i) => Some(OwnerNode::Crate(i)),
3480 pub fn fn_kind(self) -> Option<FnKind<'hir>> {
3482 Node::Item(i) => match i.kind {
3483 ItemKind::Fn(ref sig, ref generics, _) => {
3484 Some(FnKind::ItemFn(i.ident, generics, sig.header))
3488 Node::TraitItem(ti) => match ti.kind {
3489 TraitItemKind::Fn(ref sig, TraitFn::Provided(_)) => {
3490 Some(FnKind::Method(ti.ident, sig))
3494 Node::ImplItem(ii) => match ii.kind {
3495 ImplItemKind::Fn(ref sig, _) => Some(FnKind::Method(ii.ident, sig)),
3498 Node::Expr(e) => match e.kind {
3499 ExprKind::Closure { .. } => Some(FnKind::Closure),
3506 /// Get the fields for the tuple-constructor,
3507 /// if this node is a tuple constructor, otherwise None
3508 pub fn tuple_fields(&self) -> Option<&'hir [FieldDef<'hir>]> {
3509 if let Node::Ctor(&VariantData::Tuple(fields, _)) = self { Some(fields) } else { None }
3513 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3514 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
3517 // tidy-alphabetical-start
3518 static_assert_size!(Block<'_>, 48);
3519 static_assert_size!(Body<'_>, 32);
3520 static_assert_size!(Expr<'_>, 64);
3521 static_assert_size!(ExprKind<'_>, 48);
3522 static_assert_size!(FnDecl<'_>, 40);
3523 static_assert_size!(ForeignItem<'_>, 72);
3524 static_assert_size!(ForeignItemKind<'_>, 40);
3525 static_assert_size!(GenericArg<'_>, 24);
3526 static_assert_size!(GenericBound<'_>, 48);
3527 static_assert_size!(Generics<'_>, 56);
3528 static_assert_size!(Impl<'_>, 80);
3529 static_assert_size!(ImplItem<'_>, 80);
3530 static_assert_size!(ImplItemKind<'_>, 32);
3531 static_assert_size!(Item<'_>, 80);
3532 static_assert_size!(ItemKind<'_>, 48);
3533 static_assert_size!(Local<'_>, 64);
3534 static_assert_size!(Param<'_>, 32);
3535 static_assert_size!(Pat<'_>, 72);
3536 static_assert_size!(Path<'_>, 40);
3537 static_assert_size!(PathSegment<'_>, 48);
3538 static_assert_size!(PatKind<'_>, 48);
3539 static_assert_size!(QPath<'_>, 24);
3540 static_assert_size!(Res, 12);
3541 static_assert_size!(Stmt<'_>, 32);
3542 static_assert_size!(StmtKind<'_>, 16);
3543 static_assert_size!(TraitItem<'_>, 88);
3544 static_assert_size!(TraitItemKind<'_>, 48);
3545 static_assert_size!(Ty<'_>, 48);
3546 static_assert_size!(TyKind<'_>, 32);
3547 // tidy-alphabetical-end