1 use crate::def::{CtorKind, DefKind, Res};
2 use crate::def_id::DefId;
3 crate use crate::hir_id::{HirId, ItemLocalId};
4 use crate::intravisit::FnKind;
8 use rustc_ast::util::parser::ExprPrecedence;
9 use rustc_ast::{Attribute, FloatTy, IntTy, Label, LitKind, TraitObjectSyntax, UintTy};
10 pub use rustc_ast::{BorrowKind, 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(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 => {
76 Ident::with_dummy_span(kw::UnderscoreLifetime)
81 pub fn normalize_to_macros_2_0(&self) -> ParamName {
83 ParamName::Plain(ident) => ParamName::Plain(ident.normalize_to_macros_2_0()),
84 param_name => param_name,
89 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
90 #[derive(HashStable_Generic)]
91 pub enum LifetimeName {
92 /// User-given names or fresh (synthetic) names.
95 /// User wrote nothing (e.g., the lifetime in `&u32`).
98 /// Implicit lifetime in a context like `dyn Foo`. This is
99 /// distinguished from implicit lifetimes elsewhere because the
100 /// lifetime that they default to must appear elsewhere within the
101 /// enclosing type. This means that, in an `impl Trait` context, we
102 /// don't have to create a parameter for them. That is, `impl
103 /// Trait<Item = &u32>` expands to an opaque type like `type
104 /// Foo<'a> = impl Trait<Item = &'a u32>`, but `impl Trait<item =
105 /// dyn Bar>` expands to `type Foo = impl Trait<Item = dyn Bar +
106 /// 'static>`. The latter uses `ImplicitObjectLifetimeDefault` so
107 /// that surrounding code knows not to create a lifetime
109 ImplicitObjectLifetimeDefault,
111 /// Indicates an error during lowering (usually `'_` in wrong place)
112 /// that was already reported.
115 /// User wrote specifies `'_`.
118 /// User wrote `'static`.
123 pub fn ident(&self) -> Ident {
125 LifetimeName::ImplicitObjectLifetimeDefault
126 | LifetimeName::Implicit
127 | LifetimeName::Error => Ident::empty(),
128 LifetimeName::Underscore => Ident::with_dummy_span(kw::UnderscoreLifetime),
129 LifetimeName::Static => Ident::with_dummy_span(kw::StaticLifetime),
130 LifetimeName::Param(param_name) => param_name.ident(),
134 pub fn is_elided(&self) -> bool {
136 LifetimeName::ImplicitObjectLifetimeDefault
137 | LifetimeName::Implicit
138 | LifetimeName::Underscore => true,
140 // It might seem surprising that `Fresh(_)` counts as
141 // *not* elided -- but this is because, as far as the code
142 // in the compiler is concerned -- `Fresh(_)` variants act
143 // equivalently to "some fresh name". They correspond to
144 // early-bound regions on an impl, in other words.
145 LifetimeName::Error | LifetimeName::Param(_) | LifetimeName::Static => false,
149 fn is_static(&self) -> bool {
150 self == &LifetimeName::Static
153 pub fn normalize_to_macros_2_0(&self) -> LifetimeName {
155 LifetimeName::Param(param_name) => {
156 LifetimeName::Param(param_name.normalize_to_macros_2_0())
158 lifetime_name => lifetime_name,
163 impl fmt::Display for Lifetime {
164 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
165 self.name.ident().fmt(f)
169 impl fmt::Debug for Lifetime {
170 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171 write!(f, "lifetime({}: {})", self.hir_id, self.name.ident())
176 pub fn is_elided(&self) -> bool {
177 self.name.is_elided()
180 pub fn is_static(&self) -> bool {
181 self.name.is_static()
185 /// A `Path` is essentially Rust's notion of a name; for instance,
186 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
187 /// along with a bunch of supporting information.
188 #[derive(Debug, HashStable_Generic)]
189 pub struct Path<'hir> {
191 /// The resolution for the path.
193 /// The segments in the path: the things separated by `::`.
194 pub segments: &'hir [PathSegment<'hir>],
198 pub fn is_global(&self) -> bool {
199 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
203 /// A segment of a path: an identifier, an optional lifetime, and a set of
205 #[derive(Debug, HashStable_Generic)]
206 pub struct PathSegment<'hir> {
207 /// The identifier portion of this path segment.
209 // `id` and `res` are optional. We currently only use these in save-analysis,
210 // any path segments without these will not have save-analysis info and
211 // therefore will not have 'jump to def' in IDEs, but otherwise will not be
212 // affected. (In general, we don't bother to get the defs for synthesized
213 // segments, only for segments which have come from the AST).
214 pub hir_id: Option<HirId>,
215 pub res: Option<Res>,
217 /// Type/lifetime parameters attached to this path. They come in
218 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
219 /// this is more than just simple syntactic sugar; the use of
220 /// parens affects the region binding rules, so we preserve the
222 pub args: Option<&'hir GenericArgs<'hir>>,
224 /// Whether to infer remaining type parameters, if any.
225 /// This only applies to expression and pattern paths, and
226 /// out of those only the segments with no type parameters
227 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
228 pub infer_args: bool,
231 impl<'hir> PathSegment<'hir> {
232 /// Converts an identifier to the corresponding segment.
233 pub fn from_ident(ident: Ident) -> PathSegment<'hir> {
234 PathSegment { ident, hir_id: None, res: None, infer_args: true, args: None }
237 pub fn invalid() -> Self {
238 Self::from_ident(Ident::empty())
241 pub fn args(&self) -> &GenericArgs<'hir> {
242 if let Some(ref args) = self.args {
245 const DUMMY: &GenericArgs<'_> = &GenericArgs::none();
251 #[derive(Encodable, Debug, HashStable_Generic)]
252 pub struct ConstArg {
253 pub value: AnonConst,
257 #[derive(Encodable, Debug, HashStable_Generic)]
258 pub struct InferArg {
264 pub fn to_ty(&self) -> Ty<'_> {
265 Ty { kind: TyKind::Infer, span: self.span, hir_id: self.hir_id }
269 #[derive(Debug, HashStable_Generic)]
270 pub enum GenericArg<'hir> {
277 impl GenericArg<'_> {
278 pub fn span(&self) -> Span {
280 GenericArg::Lifetime(l) => l.span,
281 GenericArg::Type(t) => t.span,
282 GenericArg::Const(c) => c.span,
283 GenericArg::Infer(i) => i.span,
287 pub fn id(&self) -> HirId {
289 GenericArg::Lifetime(l) => l.hir_id,
290 GenericArg::Type(t) => t.hir_id,
291 GenericArg::Const(c) => c.value.hir_id,
292 GenericArg::Infer(i) => i.hir_id,
296 pub fn is_synthetic(&self) -> bool {
297 matches!(self, GenericArg::Lifetime(lifetime) if lifetime.name.ident() == Ident::empty())
300 pub fn descr(&self) -> &'static str {
302 GenericArg::Lifetime(_) => "lifetime",
303 GenericArg::Type(_) => "type",
304 GenericArg::Const(_) => "constant",
305 GenericArg::Infer(_) => "inferred",
309 pub fn to_ord(&self) -> ast::ParamKindOrd {
311 GenericArg::Lifetime(_) => ast::ParamKindOrd::Lifetime,
312 GenericArg::Type(_) => ast::ParamKindOrd::Type,
313 GenericArg::Const(_) => ast::ParamKindOrd::Const,
314 GenericArg::Infer(_) => ast::ParamKindOrd::Infer,
318 pub fn is_ty_or_const(&self) -> bool {
320 GenericArg::Lifetime(_) => false,
321 GenericArg::Type(_) | GenericArg::Const(_) | GenericArg::Infer(_) => true,
326 #[derive(Debug, HashStable_Generic)]
327 pub struct GenericArgs<'hir> {
328 /// The generic arguments for this path segment.
329 pub args: &'hir [GenericArg<'hir>],
330 /// Bindings (equality constraints) on associated types, if present.
331 /// E.g., `Foo<A = Bar>`.
332 pub bindings: &'hir [TypeBinding<'hir>],
333 /// Were arguments written in parenthesized form `Fn(T) -> U`?
334 /// This is required mostly for pretty-printing and diagnostics,
335 /// but also for changing lifetime elision rules to be "function-like".
336 pub parenthesized: bool,
337 /// The span encompassing arguments and the surrounding brackets `<>` or `()`
338 /// Foo<A, B, AssocTy = D> Fn(T, U, V) -> W
339 /// ^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^
340 /// Note that this may be:
341 /// - empty, if there are no generic brackets (but there may be hidden lifetimes)
342 /// - dummy, if this was generated while desugaring
346 impl GenericArgs<'_> {
347 pub const fn none() -> Self {
348 Self { args: &[], bindings: &[], parenthesized: false, span_ext: DUMMY_SP }
351 pub fn inputs(&self) -> &[Ty<'_>] {
352 if self.parenthesized {
353 for arg in self.args {
355 GenericArg::Lifetime(_) => {}
356 GenericArg::Type(ref ty) => {
357 if let TyKind::Tup(ref tys) = ty.kind {
362 GenericArg::Const(_) => {}
363 GenericArg::Infer(_) => {}
367 panic!("GenericArgs::inputs: not a `Fn(T) -> U`");
371 pub fn has_type_params(&self) -> bool {
372 self.args.iter().any(|arg| matches!(arg, GenericArg::Type(_)))
375 pub fn has_err(&self) -> bool {
376 self.args.iter().any(|arg| match arg {
377 GenericArg::Type(ty) => matches!(ty.kind, TyKind::Err),
379 }) || self.bindings.iter().any(|arg| match arg.kind {
380 TypeBindingKind::Equality { term: Term::Ty(ty) } => matches!(ty.kind, TyKind::Err),
386 pub fn num_type_params(&self) -> usize {
387 self.args.iter().filter(|arg| matches!(arg, GenericArg::Type(_))).count()
391 pub fn num_lifetime_params(&self) -> usize {
392 self.args.iter().filter(|arg| matches!(arg, GenericArg::Lifetime(_))).count()
396 pub fn has_lifetime_params(&self) -> bool {
397 self.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)))
401 pub fn num_generic_params(&self) -> usize {
402 self.args.iter().filter(|arg| !matches!(arg, GenericArg::Lifetime(_))).count()
405 /// The span encompassing the text inside the surrounding brackets.
406 /// It will also include bindings if they aren't in the form `-> Ret`
407 /// Returns `None` if the span is empty (e.g. no brackets) or dummy
408 pub fn span(&self) -> Option<Span> {
409 let span_ext = self.span_ext()?;
410 Some(span_ext.with_lo(span_ext.lo() + BytePos(1)).with_hi(span_ext.hi() - BytePos(1)))
413 /// Returns span encompassing arguments and their surrounding `<>` or `()`
414 pub fn span_ext(&self) -> Option<Span> {
415 Some(self.span_ext).filter(|span| !span.is_empty())
418 pub fn is_empty(&self) -> bool {
423 /// A modifier on a bound, currently this is only used for `?Sized`, where the
424 /// modifier is `Maybe`. Negative bounds should also be handled here.
425 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
426 #[derive(HashStable_Generic)]
427 pub enum TraitBoundModifier {
433 /// The AST represents all type param bounds as types.
434 /// `typeck::collect::compute_bounds` matches these against
435 /// the "special" built-in traits (see `middle::lang_items`) and
436 /// detects `Copy`, `Send` and `Sync`.
437 #[derive(Clone, Debug, HashStable_Generic)]
438 pub enum GenericBound<'hir> {
439 Trait(PolyTraitRef<'hir>, TraitBoundModifier),
440 // FIXME(davidtwco): Introduce `PolyTraitRef::LangItem`
441 LangItemTrait(LangItem, Span, HirId, &'hir GenericArgs<'hir>),
445 impl GenericBound<'_> {
446 pub fn trait_ref(&self) -> Option<&TraitRef<'_>> {
448 GenericBound::Trait(data, _) => Some(&data.trait_ref),
453 pub fn span(&self) -> Span {
455 GenericBound::Trait(t, ..) => t.span,
456 GenericBound::LangItemTrait(_, span, ..) => *span,
457 GenericBound::Outlives(l) => l.span,
462 pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
464 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
465 pub enum LifetimeParamKind {
466 // Indicates that the lifetime definition was explicitly declared (e.g., in
467 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
470 // Indication that the lifetime was elided (e.g., in both cases in
471 // `fn foo(x: &u8) -> &'_ u8 { x }`).
474 // Indication that the lifetime name was somehow in error.
478 #[derive(Debug, HashStable_Generic)]
479 pub enum GenericParamKind<'hir> {
480 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
482 kind: LifetimeParamKind,
485 default: Option<&'hir Ty<'hir>>,
490 /// Optional default value for the const generic param
491 default: Option<AnonConst>,
495 #[derive(Debug, HashStable_Generic)]
496 pub struct GenericParam<'hir> {
500 pub pure_wrt_drop: bool,
501 pub kind: GenericParamKind<'hir>,
502 pub colon_span: Option<Span>,
505 impl<'hir> GenericParam<'hir> {
506 /// Synthetic type-parameters are inserted after normal ones.
507 /// In order for normal parameters to be able to refer to synthetic ones,
508 /// scans them first.
509 pub fn is_impl_trait(&self) -> bool {
510 matches!(self.kind, GenericParamKind::Type { synthetic: true, .. })
513 /// This can happen for `async fn`, e.g. `async fn f<'_>(&'_ self)`.
515 /// See `lifetime_to_generic_param` in `rustc_ast_lowering` for more information.
516 pub fn is_elided_lifetime(&self) -> bool {
517 matches!(self.kind, GenericParamKind::Lifetime { kind: LifetimeParamKind::Elided })
522 pub struct GenericParamCount {
523 pub lifetimes: usize,
529 /// Represents lifetimes and type parameters attached to a declaration
530 /// of a function, enum, trait, etc.
531 #[derive(Debug, HashStable_Generic)]
532 pub struct Generics<'hir> {
533 pub params: &'hir [GenericParam<'hir>],
534 pub predicates: &'hir [WherePredicate<'hir>],
535 pub has_where_clause: bool,
536 pub where_clause_span: Span,
540 impl<'hir> Generics<'hir> {
541 pub const fn empty() -> &'hir Generics<'hir> {
542 const NOPE: Generics<'_> = Generics {
545 has_where_clause: false,
546 where_clause_span: DUMMY_SP,
552 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'_>> {
553 for param in self.params {
554 if name == param.name.ident().name {
561 pub fn spans(&self) -> MultiSpan {
562 if self.params.is_empty() {
565 self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
569 /// If there are generic parameters, return where to introduce a new one.
570 pub fn span_for_param_suggestion(&self) -> Option<Span> {
571 if self.params.iter().any(|p| self.span.contains(p.span)) {
572 // `fn foo<A>(t: impl Trait)`
573 // ^ suggest `, T: Trait` here
574 let span = self.span.with_lo(self.span.hi() - BytePos(1)).shrink_to_lo();
581 pub fn where_clause_span(&self) -> Option<Span> {
582 if self.predicates.is_empty() { None } else { Some(self.where_clause_span) }
585 /// The `where_span` under normal circumstances points at either the predicates or the empty
586 /// space where the `where` clause should be. Only of use for diagnostic suggestions.
587 pub fn span_for_predicates_or_empty_place(&self) -> Span {
588 self.where_clause_span
591 /// `Span` where further predicates would be suggested, accounting for trailing commas, like
592 /// in `fn foo<T>(t: T) where T: Foo,` so we don't suggest two trailing commas.
593 pub fn tail_span_for_predicate_suggestion(&self) -> Span {
594 let end = self.span_for_predicates_or_empty_place().shrink_to_hi();
595 if self.has_where_clause {
598 .filter(|p| p.in_where_clause())
600 .map_or(end, |p| p.span())
608 pub fn bounds_for_param(
610 param_def_id: LocalDefId,
611 ) -> impl Iterator<Item = &WhereBoundPredicate<'_>> {
612 self.predicates.iter().filter_map(move |pred| match pred {
613 WherePredicate::BoundPredicate(bp) if bp.is_param_bound(param_def_id.to_def_id()) => {
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(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> {
735 /// Origin of the predicate.
736 pub origin: PredicateOrigin,
737 /// Any generics from a `for` binding.
738 pub bound_generic_params: &'hir [GenericParam<'hir>],
739 /// The type being bounded.
740 pub bounded_ty: &'hir Ty<'hir>,
741 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
742 pub bounds: GenericBounds<'hir>,
745 impl<'hir> WhereBoundPredicate<'hir> {
746 /// Returns `true` if `param_def_id` matches the `bounded_ty` of this predicate.
747 pub fn is_param_bound(&self, param_def_id: DefId) -> bool {
748 self.bounded_ty.as_generic_param().map_or(false, |(def_id, _)| def_id == param_def_id)
752 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
753 #[derive(Debug, HashStable_Generic)]
754 pub struct WhereRegionPredicate<'hir> {
756 pub in_where_clause: bool,
757 pub lifetime: Lifetime,
758 pub bounds: GenericBounds<'hir>,
761 /// An equality predicate (e.g., `T = int`); currently unsupported.
762 #[derive(Debug, HashStable_Generic)]
763 pub struct WhereEqPredicate<'hir> {
766 pub lhs_ty: &'hir Ty<'hir>,
767 pub rhs_ty: &'hir Ty<'hir>,
770 /// HIR node coupled with its parent's id in the same HIR owner.
772 /// The parent is trash when the node is a HIR owner.
773 #[derive(Clone, Debug)]
774 pub struct ParentedNode<'tcx> {
775 pub parent: ItemLocalId,
776 pub node: Node<'tcx>,
779 /// Attributes owned by a HIR owner.
781 pub struct AttributeMap<'tcx> {
782 pub map: SortedMap<ItemLocalId, &'tcx [Attribute]>,
783 pub hash: Fingerprint,
786 impl<'tcx> AttributeMap<'tcx> {
787 pub const EMPTY: &'static AttributeMap<'static> =
788 &AttributeMap { map: SortedMap::new(), hash: Fingerprint::ZERO };
791 pub fn get(&self, id: ItemLocalId) -> &'tcx [Attribute] {
792 self.map.get(&id).copied().unwrap_or(&[])
796 /// Map of all HIR nodes inside the current owner.
797 /// These nodes are mapped by `ItemLocalId` alongside the index of their parent node.
798 /// The HIR tree, including bodies, is pre-hashed.
800 pub struct OwnerNodes<'tcx> {
801 /// Pre-computed hash of the full HIR.
802 pub hash_including_bodies: Fingerprint,
803 /// Pre-computed hash of the item signature, sithout recursing into the body.
804 pub hash_without_bodies: Fingerprint,
805 /// Full HIR for the current owner.
806 // The zeroth node's parent should never be accessed: the owner's parent is computed by the
807 // hir_owner_parent query. It is set to `ItemLocalId::INVALID` to force an ICE if accidentally
809 pub nodes: IndexVec<ItemLocalId, Option<ParentedNode<'tcx>>>,
810 /// Content of local bodies.
811 pub bodies: SortedMap<ItemLocalId, &'tcx Body<'tcx>>,
812 /// Non-owning definitions contained in this owner.
813 pub local_id_to_def_id: SortedMap<ItemLocalId, LocalDefId>,
816 impl<'tcx> OwnerNodes<'tcx> {
817 pub fn node(&self) -> OwnerNode<'tcx> {
818 use rustc_index::vec::Idx;
819 let node = self.nodes[ItemLocalId::new(0)].as_ref().unwrap().node;
820 let node = node.as_owner().unwrap(); // Indexing must ensure it is an OwnerNode.
825 /// Full information resulting from lowering an AST node.
826 #[derive(Debug, HashStable_Generic)]
827 pub struct OwnerInfo<'hir> {
828 /// Contents of the HIR.
829 pub nodes: OwnerNodes<'hir>,
830 /// Map from each nested owner to its parent's local id.
831 pub parenting: FxHashMap<LocalDefId, ItemLocalId>,
832 /// Collected attributes of the HIR nodes.
833 pub attrs: AttributeMap<'hir>,
834 /// Map indicating what traits are in scope for places where this
835 /// is relevant; generated by resolve.
836 pub trait_map: FxHashMap<ItemLocalId, Box<[TraitCandidate]>>,
839 impl<'tcx> OwnerInfo<'tcx> {
841 pub fn node(&self) -> OwnerNode<'tcx> {
846 #[derive(Copy, Clone, Debug, HashStable_Generic)]
847 pub enum MaybeOwner<T> {
850 /// Used as a placeholder for unused LocalDefId.
854 impl<T> MaybeOwner<T> {
855 pub fn as_owner(self) -> Option<T> {
857 MaybeOwner::Owner(i) => Some(i),
858 MaybeOwner::NonOwner(_) | MaybeOwner::Phantom => None,
862 pub fn map<U>(self, f: impl FnOnce(T) -> U) -> MaybeOwner<U> {
864 MaybeOwner::Owner(i) => MaybeOwner::Owner(f(i)),
865 MaybeOwner::NonOwner(hir_id) => MaybeOwner::NonOwner(hir_id),
866 MaybeOwner::Phantom => MaybeOwner::Phantom,
870 pub fn unwrap(self) -> T {
872 MaybeOwner::Owner(i) => i,
873 MaybeOwner::NonOwner(_) | MaybeOwner::Phantom => panic!("Not a HIR owner"),
878 /// The top-level data structure that stores the entire contents of
879 /// the crate currently being compiled.
881 /// For more details, see the [rustc dev guide].
883 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
885 pub struct Crate<'hir> {
886 pub owners: IndexVec<LocalDefId, MaybeOwner<&'hir OwnerInfo<'hir>>>,
887 pub hir_hash: Fingerprint,
890 /// A block of statements `{ .. }`, which may have a label (in this case the
891 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
892 /// the `rules` being anything but `DefaultBlock`.
893 #[derive(Debug, HashStable_Generic)]
894 pub struct Block<'hir> {
895 /// Statements in a block.
896 pub stmts: &'hir [Stmt<'hir>],
897 /// An expression at the end of the block
898 /// without a semicolon, if any.
899 pub expr: Option<&'hir Expr<'hir>>,
900 #[stable_hasher(ignore)]
902 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
903 pub rules: BlockCheckMode,
905 /// If true, then there may exist `break 'a` values that aim to
906 /// break out of this block early.
907 /// Used by `'label: {}` blocks and by `try {}` blocks.
908 pub targeted_by_break: bool,
911 #[derive(Debug, HashStable_Generic)]
912 pub struct Pat<'hir> {
913 #[stable_hasher(ignore)]
915 pub kind: PatKind<'hir>,
917 // Whether to use default binding modes.
918 // At present, this is false only for destructuring assignment.
919 pub default_binding_modes: bool,
922 impl<'hir> Pat<'hir> {
923 // FIXME(#19596) this is a workaround, but there should be a better way
924 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) -> bool {
931 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
932 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
933 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
934 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
935 Slice(before, slice, after) => {
936 before.iter().chain(slice).chain(after.iter()).all(|p| p.walk_short_(it))
941 /// Walk the pattern in left-to-right order,
942 /// short circuiting (with `.all(..)`) if `false` is returned.
944 /// Note that when visiting e.g. `Tuple(ps)`,
945 /// if visiting `ps[0]` returns `false`,
946 /// then `ps[1]` will not be visited.
947 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) -> bool {
948 self.walk_short_(&mut it)
951 // FIXME(#19596) this is a workaround, but there should be a better way
952 fn walk_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) {
959 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
960 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
961 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
962 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
963 Slice(before, slice, after) => {
964 before.iter().chain(slice).chain(after.iter()).for_each(|p| p.walk_(it))
969 /// Walk the pattern in left-to-right order.
971 /// If `it(pat)` returns `false`, the children are not visited.
972 pub fn walk(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) {
976 /// Walk the pattern in left-to-right order.
978 /// If you always want to recurse, prefer this method over `walk`.
979 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
987 /// A single field in a struct pattern.
989 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
990 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
991 /// except `is_shorthand` is true.
992 #[derive(Debug, HashStable_Generic)]
993 pub struct PatField<'hir> {
994 #[stable_hasher(ignore)]
996 /// The identifier for the field.
998 /// The pattern the field is destructured to.
999 pub pat: &'hir Pat<'hir>,
1000 pub is_shorthand: bool,
1004 /// Explicit binding annotations given in the HIR for a binding. Note
1005 /// that this is not the final binding *mode* that we infer after type
1007 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1008 pub enum BindingAnnotation {
1009 /// No binding annotation given: this means that the final binding mode
1010 /// will depend on whether we have skipped through a `&` reference
1011 /// when matching. For example, the `x` in `Some(x)` will have binding
1012 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
1013 /// ultimately be inferred to be by-reference.
1015 /// Note that implicit reference skipping is not implemented yet (#42640).
1018 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
1021 /// Annotated as `ref`, like `ref x`
1024 /// Annotated as `ref mut x`.
1028 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1034 impl fmt::Display for RangeEnd {
1035 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1036 f.write_str(match self {
1037 RangeEnd::Included => "..=",
1038 RangeEnd::Excluded => "..",
1043 #[derive(Debug, HashStable_Generic)]
1044 pub enum PatKind<'hir> {
1045 /// Represents a wildcard pattern (i.e., `_`).
1048 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
1049 /// The `HirId` is the canonical ID for the variable being bound,
1050 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
1051 /// which is the pattern ID of the first `x`.
1052 Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
1054 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
1055 /// The `bool` is `true` in the presence of a `..`.
1056 Struct(QPath<'hir>, &'hir [PatField<'hir>], bool),
1058 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
1059 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
1060 /// `0 <= position <= subpats.len()`
1061 TupleStruct(QPath<'hir>, &'hir [Pat<'hir>], Option<usize>),
1063 /// An or-pattern `A | B | C`.
1064 /// Invariant: `pats.len() >= 2`.
1065 Or(&'hir [Pat<'hir>]),
1067 /// A path pattern for a unit struct/variant or a (maybe-associated) constant.
1070 /// A tuple pattern (e.g., `(a, b)`).
1071 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
1072 /// `0 <= position <= subpats.len()`
1073 Tuple(&'hir [Pat<'hir>], Option<usize>),
1075 /// A `box` pattern.
1076 Box(&'hir Pat<'hir>),
1078 /// A reference pattern (e.g., `&mut (a, b)`).
1079 Ref(&'hir Pat<'hir>, Mutability),
1082 Lit(&'hir Expr<'hir>),
1084 /// A range pattern (e.g., `1..=2` or `1..2`).
1085 Range(Option<&'hir Expr<'hir>>, Option<&'hir Expr<'hir>>, RangeEnd),
1087 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
1089 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
1090 /// If `slice` exists, then `after` can be non-empty.
1092 /// The representation for e.g., `[a, b, .., c, d]` is:
1093 /// ```ignore (illustrative)
1094 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
1096 Slice(&'hir [Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [Pat<'hir>]),
1099 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1100 pub enum BinOpKind {
1101 /// The `+` operator (addition).
1103 /// The `-` operator (subtraction).
1105 /// The `*` operator (multiplication).
1107 /// The `/` operator (division).
1109 /// The `%` operator (modulus).
1111 /// The `&&` operator (logical and).
1113 /// The `||` operator (logical or).
1115 /// The `^` operator (bitwise xor).
1117 /// The `&` operator (bitwise and).
1119 /// The `|` operator (bitwise or).
1121 /// The `<<` operator (shift left).
1123 /// The `>>` operator (shift right).
1125 /// The `==` operator (equality).
1127 /// The `<` operator (less than).
1129 /// The `<=` operator (less than or equal to).
1131 /// The `!=` operator (not equal to).
1133 /// The `>=` operator (greater than or equal to).
1135 /// The `>` operator (greater than).
1140 pub fn as_str(self) -> &'static str {
1142 BinOpKind::Add => "+",
1143 BinOpKind::Sub => "-",
1144 BinOpKind::Mul => "*",
1145 BinOpKind::Div => "/",
1146 BinOpKind::Rem => "%",
1147 BinOpKind::And => "&&",
1148 BinOpKind::Or => "||",
1149 BinOpKind::BitXor => "^",
1150 BinOpKind::BitAnd => "&",
1151 BinOpKind::BitOr => "|",
1152 BinOpKind::Shl => "<<",
1153 BinOpKind::Shr => ">>",
1154 BinOpKind::Eq => "==",
1155 BinOpKind::Lt => "<",
1156 BinOpKind::Le => "<=",
1157 BinOpKind::Ne => "!=",
1158 BinOpKind::Ge => ">=",
1159 BinOpKind::Gt => ">",
1163 pub fn is_lazy(self) -> bool {
1164 matches!(self, BinOpKind::And | BinOpKind::Or)
1167 pub fn is_shift(self) -> bool {
1168 matches!(self, BinOpKind::Shl | BinOpKind::Shr)
1171 pub fn is_comparison(self) -> bool {
1178 | BinOpKind::Ge => true,
1190 | BinOpKind::Shr => false,
1194 /// Returns `true` if the binary operator takes its arguments by value.
1195 pub fn is_by_value(self) -> bool {
1196 !self.is_comparison()
1200 impl Into<ast::BinOpKind> for BinOpKind {
1201 fn into(self) -> ast::BinOpKind {
1203 BinOpKind::Add => ast::BinOpKind::Add,
1204 BinOpKind::Sub => ast::BinOpKind::Sub,
1205 BinOpKind::Mul => ast::BinOpKind::Mul,
1206 BinOpKind::Div => ast::BinOpKind::Div,
1207 BinOpKind::Rem => ast::BinOpKind::Rem,
1208 BinOpKind::And => ast::BinOpKind::And,
1209 BinOpKind::Or => ast::BinOpKind::Or,
1210 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1211 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1212 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1213 BinOpKind::Shl => ast::BinOpKind::Shl,
1214 BinOpKind::Shr => ast::BinOpKind::Shr,
1215 BinOpKind::Eq => ast::BinOpKind::Eq,
1216 BinOpKind::Lt => ast::BinOpKind::Lt,
1217 BinOpKind::Le => ast::BinOpKind::Le,
1218 BinOpKind::Ne => ast::BinOpKind::Ne,
1219 BinOpKind::Ge => ast::BinOpKind::Ge,
1220 BinOpKind::Gt => ast::BinOpKind::Gt,
1225 pub type BinOp = Spanned<BinOpKind>;
1227 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1229 /// The `*` operator (dereferencing).
1231 /// The `!` operator (logical negation).
1233 /// The `-` operator (negation).
1238 pub fn as_str(self) -> &'static str {
1246 /// Returns `true` if the unary operator takes its argument by value.
1247 pub fn is_by_value(self) -> bool {
1248 matches!(self, Self::Neg | Self::Not)
1253 #[derive(Debug, HashStable_Generic)]
1254 pub struct Stmt<'hir> {
1256 pub kind: StmtKind<'hir>,
1260 /// The contents of a statement.
1261 #[derive(Debug, HashStable_Generic)]
1262 pub enum StmtKind<'hir> {
1263 /// A local (`let`) binding.
1264 Local(&'hir Local<'hir>),
1266 /// An item binding.
1269 /// An expression without a trailing semi-colon (must have unit type).
1270 Expr(&'hir Expr<'hir>),
1272 /// An expression with a trailing semi-colon (may have any type).
1273 Semi(&'hir Expr<'hir>),
1276 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1277 #[derive(Debug, HashStable_Generic)]
1278 pub struct Local<'hir> {
1279 pub pat: &'hir Pat<'hir>,
1280 /// Type annotation, if any (otherwise the type will be inferred).
1281 pub ty: Option<&'hir Ty<'hir>>,
1282 /// Initializer expression to set the value, if any.
1283 pub init: Option<&'hir Expr<'hir>>,
1286 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1287 /// desugaring. Otherwise will be `Normal`.
1288 pub source: LocalSource,
1291 /// Represents a single arm of a `match` expression, e.g.
1292 /// `<pat> (if <guard>) => <body>`.
1293 #[derive(Debug, HashStable_Generic)]
1294 pub struct Arm<'hir> {
1295 #[stable_hasher(ignore)]
1298 /// If this pattern and the optional guard matches, then `body` is evaluated.
1299 pub pat: &'hir Pat<'hir>,
1300 /// Optional guard clause.
1301 pub guard: Option<Guard<'hir>>,
1302 /// The expression the arm evaluates to if this arm matches.
1303 pub body: &'hir Expr<'hir>,
1306 /// Represents a `let <pat>[: <ty>] = <expr>` expression (not a Local), occurring in an `if-let` or
1307 /// `let-else`, evaluating to a boolean. Typically the pattern is refutable.
1309 /// In an if-let, imagine it as `if (let <pat> = <expr>) { ... }`; in a let-else, it is part of the
1310 /// desugaring to if-let. Only let-else supports the type annotation at present.
1311 #[derive(Debug, HashStable_Generic)]
1312 pub struct Let<'hir> {
1315 pub pat: &'hir Pat<'hir>,
1316 pub ty: Option<&'hir Ty<'hir>>,
1317 pub init: &'hir Expr<'hir>,
1320 #[derive(Debug, HashStable_Generic)]
1321 pub enum Guard<'hir> {
1322 If(&'hir Expr<'hir>),
1323 // FIXME use hir::Let for this.
1324 IfLet(&'hir Pat<'hir>, &'hir Expr<'hir>),
1327 #[derive(Debug, HashStable_Generic)]
1328 pub struct ExprField<'hir> {
1329 #[stable_hasher(ignore)]
1332 pub expr: &'hir Expr<'hir>,
1334 pub is_shorthand: bool,
1337 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1338 pub enum BlockCheckMode {
1340 UnsafeBlock(UnsafeSource),
1343 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1344 pub enum UnsafeSource {
1349 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
1354 /// The body of a function, closure, or constant value. In the case of
1355 /// a function, the body contains not only the function body itself
1356 /// (which is an expression), but also the argument patterns, since
1357 /// those are something that the caller doesn't really care about.
1362 /// fn foo((x, y): (u32, u32)) -> u32 {
1367 /// Here, the `Body` associated with `foo()` would contain:
1369 /// - an `params` array containing the `(x, y)` pattern
1370 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1371 /// - `generator_kind` would be `None`
1373 /// All bodies have an **owner**, which can be accessed via the HIR
1374 /// map using `body_owner_def_id()`.
1375 #[derive(Debug, HashStable_Generic)]
1376 pub struct Body<'hir> {
1377 pub params: &'hir [Param<'hir>],
1378 pub value: Expr<'hir>,
1379 pub generator_kind: Option<GeneratorKind>,
1382 impl<'hir> Body<'hir> {
1383 pub fn id(&self) -> BodyId {
1384 BodyId { hir_id: self.value.hir_id }
1387 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1392 /// The type of source expression that caused this generator to be created.
1405 pub enum GeneratorKind {
1406 /// An explicit `async` block or the body of an async function.
1407 Async(AsyncGeneratorKind),
1409 /// A generator literal created via a `yield` inside a closure.
1413 impl fmt::Display for GeneratorKind {
1414 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1416 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1417 GeneratorKind::Gen => f.write_str("generator"),
1422 impl GeneratorKind {
1423 pub fn descr(&self) -> &'static str {
1425 GeneratorKind::Async(ask) => ask.descr(),
1426 GeneratorKind::Gen => "generator",
1431 /// In the case of a generator created as part of an async construct,
1432 /// which kind of async construct caused it to be created?
1434 /// This helps error messages but is also used to drive coercions in
1435 /// type-checking (see #60424).
1448 pub enum AsyncGeneratorKind {
1449 /// An explicit `async` block written by the user.
1452 /// An explicit `async` closure written by the user.
1455 /// The `async` block generated as the body of an async function.
1459 impl fmt::Display for AsyncGeneratorKind {
1460 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1461 f.write_str(match self {
1462 AsyncGeneratorKind::Block => "`async` block",
1463 AsyncGeneratorKind::Closure => "`async` closure body",
1464 AsyncGeneratorKind::Fn => "`async fn` body",
1469 impl AsyncGeneratorKind {
1470 pub fn descr(&self) -> &'static str {
1472 AsyncGeneratorKind::Block => "`async` block",
1473 AsyncGeneratorKind::Closure => "`async` closure body",
1474 AsyncGeneratorKind::Fn => "`async fn` body",
1479 #[derive(Copy, Clone, Debug)]
1480 pub enum BodyOwnerKind {
1481 /// Functions and methods.
1487 /// Constants and associated constants.
1490 /// Initializer of a `static` item.
1494 impl BodyOwnerKind {
1495 pub fn is_fn_or_closure(self) -> bool {
1497 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1498 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1503 /// The kind of an item that requires const-checking.
1504 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1505 pub enum ConstContext {
1509 /// A `static` or `static mut`.
1512 /// A `const`, associated `const`, or other const context.
1514 /// Other contexts include:
1515 /// - Array length expressions
1516 /// - Enum discriminants
1517 /// - Const generics
1519 /// For the most part, other contexts are treated just like a regular `const`, so they are
1520 /// lumped into the same category.
1525 /// A description of this const context that can appear between backticks in an error message.
1527 /// E.g. `const` or `static mut`.
1528 pub fn keyword_name(self) -> &'static str {
1530 Self::Const => "const",
1531 Self::Static(Mutability::Not) => "static",
1532 Self::Static(Mutability::Mut) => "static mut",
1533 Self::ConstFn => "const fn",
1538 /// A colloquial, trivially pluralizable description of this const context for use in error
1540 impl fmt::Display for ConstContext {
1541 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1543 Self::Const => write!(f, "constant"),
1544 Self::Static(_) => write!(f, "static"),
1545 Self::ConstFn => write!(f, "constant function"),
1551 pub type Lit = Spanned<LitKind>;
1553 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1560 pub fn hir_id(&self) -> HirId {
1562 &ArrayLen::Infer(hir_id, _) | &ArrayLen::Body(AnonConst { hir_id, body: _ }) => hir_id,
1567 /// A constant (expression) that's not an item or associated item,
1568 /// but needs its own `DefId` for type-checking, const-eval, etc.
1569 /// These are usually found nested inside types (e.g., array lengths)
1570 /// or expressions (e.g., repeat counts), and also used to define
1571 /// explicit discriminant values for enum variants.
1573 /// You can check if this anon const is a default in a const param
1574 /// `const N: usize = { ... }` with `tcx.hir().opt_const_param_default_param_hir_id(..)`
1575 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1576 pub struct AnonConst {
1583 pub struct Expr<'hir> {
1585 pub kind: ExprKind<'hir>,
1590 pub fn precedence(&self) -> ExprPrecedence {
1592 ExprKind::Box(_) => ExprPrecedence::Box,
1593 ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1594 ExprKind::Array(_) => ExprPrecedence::Array,
1595 ExprKind::Call(..) => ExprPrecedence::Call,
1596 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1597 ExprKind::Tup(_) => ExprPrecedence::Tup,
1598 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1599 ExprKind::Unary(..) => ExprPrecedence::Unary,
1600 ExprKind::Lit(_) => ExprPrecedence::Lit,
1601 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1602 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1603 ExprKind::If(..) => ExprPrecedence::If,
1604 ExprKind::Let(..) => ExprPrecedence::Let,
1605 ExprKind::Loop(..) => ExprPrecedence::Loop,
1606 ExprKind::Match(..) => ExprPrecedence::Match,
1607 ExprKind::Closure(..) => ExprPrecedence::Closure,
1608 ExprKind::Block(..) => ExprPrecedence::Block,
1609 ExprKind::Assign(..) => ExprPrecedence::Assign,
1610 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1611 ExprKind::Field(..) => ExprPrecedence::Field,
1612 ExprKind::Index(..) => ExprPrecedence::Index,
1613 ExprKind::Path(..) => ExprPrecedence::Path,
1614 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1615 ExprKind::Break(..) => ExprPrecedence::Break,
1616 ExprKind::Continue(..) => ExprPrecedence::Continue,
1617 ExprKind::Ret(..) => ExprPrecedence::Ret,
1618 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1619 ExprKind::Struct(..) => ExprPrecedence::Struct,
1620 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1621 ExprKind::Yield(..) => ExprPrecedence::Yield,
1622 ExprKind::Err => ExprPrecedence::Err,
1626 // Whether this looks like a place expr, without checking for deref
1628 // This will return `true` in some potentially surprising cases such as
1629 // `CONSTANT.field`.
1630 pub fn is_syntactic_place_expr(&self) -> bool {
1631 self.is_place_expr(|_| true)
1634 /// Whether this is a place expression.
1636 /// `allow_projections_from` should return `true` if indexing a field or index expression based
1637 /// on the given expression should be considered a place expression.
1638 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1640 ExprKind::Path(QPath::Resolved(_, ref path)) => {
1641 matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static(_), _) | Res::Err)
1644 // Type ascription inherits its place expression kind from its
1646 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1647 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1649 ExprKind::Unary(UnOp::Deref, _) => true,
1651 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1652 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1655 // Lang item paths cannot currently be local variables or statics.
1656 ExprKind::Path(QPath::LangItem(..)) => false,
1658 // Partially qualified paths in expressions can only legally
1659 // refer to associated items which are always rvalues.
1660 ExprKind::Path(QPath::TypeRelative(..))
1661 | ExprKind::Call(..)
1662 | ExprKind::MethodCall(..)
1663 | ExprKind::Struct(..)
1666 | ExprKind::Match(..)
1667 | ExprKind::Closure(..)
1668 | ExprKind::Block(..)
1669 | ExprKind::Repeat(..)
1670 | ExprKind::Array(..)
1671 | ExprKind::Break(..)
1672 | ExprKind::Continue(..)
1675 | ExprKind::Loop(..)
1676 | ExprKind::Assign(..)
1677 | ExprKind::InlineAsm(..)
1678 | ExprKind::AssignOp(..)
1680 | ExprKind::ConstBlock(..)
1681 | ExprKind::Unary(..)
1683 | ExprKind::AddrOf(..)
1684 | ExprKind::Binary(..)
1685 | ExprKind::Yield(..)
1686 | ExprKind::Cast(..)
1687 | ExprKind::DropTemps(..)
1688 | ExprKind::Err => false,
1692 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1693 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1694 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1695 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1696 /// beyond remembering to call this function before doing analysis on it.
1697 pub fn peel_drop_temps(&self) -> &Self {
1698 let mut expr = self;
1699 while let ExprKind::DropTemps(inner) = &expr.kind {
1705 pub fn peel_blocks(&self) -> &Self {
1706 let mut expr = self;
1707 while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind {
1713 pub fn can_have_side_effects(&self) -> bool {
1714 match self.peel_drop_temps().kind {
1715 ExprKind::Path(_) | ExprKind::Lit(_) => false,
1716 ExprKind::Type(base, _)
1717 | ExprKind::Unary(_, base)
1718 | ExprKind::Field(base, _)
1719 | ExprKind::Index(base, _)
1720 | ExprKind::AddrOf(.., base)
1721 | ExprKind::Cast(base, _) => {
1722 // This isn't exactly true for `Index` and all `Unary`, but we are using this
1723 // method exclusively for diagnostics and there's a *cultural* pressure against
1724 // them being used only for its side-effects.
1725 base.can_have_side_effects()
1727 ExprKind::Struct(_, fields, init) => fields
1729 .map(|field| field.expr)
1730 .chain(init.into_iter())
1731 .all(|e| e.can_have_side_effects()),
1733 ExprKind::Array(args)
1734 | ExprKind::Tup(args)
1738 ExprKind::Path(QPath::Resolved(
1740 Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. },
1745 ) => args.iter().all(|arg| arg.can_have_side_effects()),
1747 | ExprKind::Match(..)
1748 | ExprKind::MethodCall(..)
1749 | ExprKind::Call(..)
1750 | ExprKind::Closure(..)
1751 | ExprKind::Block(..)
1752 | ExprKind::Repeat(..)
1753 | ExprKind::Break(..)
1754 | ExprKind::Continue(..)
1757 | ExprKind::Loop(..)
1758 | ExprKind::Assign(..)
1759 | ExprKind::InlineAsm(..)
1760 | ExprKind::AssignOp(..)
1761 | ExprKind::ConstBlock(..)
1763 | ExprKind::Binary(..)
1764 | ExprKind::Yield(..)
1765 | ExprKind::DropTemps(..)
1766 | ExprKind::Err => true,
1771 /// Checks if the specified expression is a built-in range literal.
1772 /// (See: `LoweringContext::lower_expr()`).
1773 pub fn is_range_literal(expr: &Expr<'_>) -> bool {
1775 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1776 ExprKind::Struct(ref qpath, _, _) => matches!(
1781 | LangItem::RangeFrom
1782 | LangItem::RangeFull
1783 | LangItem::RangeToInclusive,
1788 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1789 ExprKind::Call(ref func, _) => {
1790 matches!(func.kind, ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, ..)))
1797 #[derive(Debug, HashStable_Generic)]
1798 pub enum ExprKind<'hir> {
1799 /// A `box x` expression.
1800 Box(&'hir Expr<'hir>),
1801 /// Allow anonymous constants from an inline `const` block
1802 ConstBlock(AnonConst),
1803 /// An array (e.g., `[a, b, c, d]`).
1804 Array(&'hir [Expr<'hir>]),
1805 /// A function call.
1807 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1808 /// and the second field is the list of arguments.
1809 /// This also represents calling the constructor of
1810 /// tuple-like ADTs such as tuple structs and enum variants.
1811 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1812 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1814 /// The `PathSegment` represents the method name and its generic arguments
1815 /// (within the angle brackets).
1816 /// The first element of the `&[Expr]` is the expression that evaluates
1817 /// to the object on which the method is being called on (the receiver),
1818 /// and the remaining elements are the rest of the arguments.
1819 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1820 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d], span)`.
1821 /// The final `Span` represents the span of the function and arguments
1822 /// (e.g. `foo::<Bar, Baz>(a, b, c, d)` in `x.foo::<Bar, Baz>(a, b, c, d)`
1824 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1825 /// the `hir_id` of the `MethodCall` node itself.
1827 /// [`type_dependent_def_id`]: ../ty/struct.TypeckResults.html#method.type_dependent_def_id
1828 MethodCall(&'hir PathSegment<'hir>, &'hir [Expr<'hir>], Span),
1829 /// A tuple (e.g., `(a, b, c, d)`).
1830 Tup(&'hir [Expr<'hir>]),
1831 /// A binary operation (e.g., `a + b`, `a * b`).
1832 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1833 /// A unary operation (e.g., `!x`, `*x`).
1834 Unary(UnOp, &'hir Expr<'hir>),
1835 /// A literal (e.g., `1`, `"foo"`).
1837 /// A cast (e.g., `foo as f64`).
1838 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1839 /// A type reference (e.g., `Foo`).
1840 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1841 /// Wraps the expression in a terminating scope.
1842 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1844 /// This construct only exists to tweak the drop order in HIR lowering.
1845 /// An example of that is the desugaring of `for` loops.
1846 DropTemps(&'hir Expr<'hir>),
1847 /// A `let $pat = $expr` expression.
1849 /// These are not `Local` and only occur as expressions.
1850 /// The `let Some(x) = foo()` in `if let Some(x) = foo()` is an example of `Let(..)`.
1851 Let(&'hir Let<'hir>),
1852 /// An `if` block, with an optional else block.
1854 /// I.e., `if <expr> { <expr> } else { <expr> }`.
1855 If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
1856 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1858 /// I.e., `'label: loop { <block> }`.
1860 /// The `Span` is the loop header (`for x in y`/`while let pat = expr`).
1861 Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span),
1862 /// A `match` block, with a source that indicates whether or not it is
1863 /// the result of a desugaring, and if so, which kind.
1864 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1865 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1867 /// The `Span` is the argument block `|...|`.
1869 /// This may also be a generator literal or an `async block` as indicated by the
1870 /// `Option<Movability>`.
1871 Closure(CaptureBy, &'hir FnDecl<'hir>, BodyId, Span, Option<Movability>),
1872 /// A block (e.g., `'label: { ... }`).
1873 Block(&'hir Block<'hir>, Option<Label>),
1875 /// An assignment (e.g., `a = foo()`).
1876 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1877 /// An assignment with an operator.
1880 AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1881 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1882 Field(&'hir Expr<'hir>, Ident),
1883 /// An indexing operation (`foo[2]`).
1884 Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1886 /// Path to a definition, possibly containing lifetime or type parameters.
1889 /// A referencing operation (i.e., `&a` or `&mut a`).
1890 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1891 /// A `break`, with an optional label to break.
1892 Break(Destination, Option<&'hir Expr<'hir>>),
1893 /// A `continue`, with an optional label.
1894 Continue(Destination),
1895 /// A `return`, with an optional value to be returned.
1896 Ret(Option<&'hir Expr<'hir>>),
1898 /// Inline assembly (from `asm!`), with its outputs and inputs.
1899 InlineAsm(&'hir InlineAsm<'hir>),
1901 /// A struct or struct-like variant literal expression.
1903 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1904 /// where `base` is the `Option<Expr>`.
1905 Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], Option<&'hir Expr<'hir>>),
1907 /// An array literal constructed from one repeated element.
1909 /// E.g., `[1; 5]`. The first expression is the element
1910 /// to be repeated; the second is the number of times to repeat it.
1911 Repeat(&'hir Expr<'hir>, ArrayLen),
1913 /// A suspension point for generators (i.e., `yield <expr>`).
1914 Yield(&'hir Expr<'hir>, YieldSource),
1916 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1920 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1922 /// To resolve the path to a `DefId`, call [`qpath_res`].
1924 /// [`qpath_res`]: ../rustc_middle/ty/struct.TypeckResults.html#method.qpath_res
1925 #[derive(Debug, HashStable_Generic)]
1926 pub enum QPath<'hir> {
1927 /// Path to a definition, optionally "fully-qualified" with a `Self`
1928 /// type, if the path points to an associated item in a trait.
1930 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1931 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1932 /// even though they both have the same two-segment `Clone::clone` `Path`.
1933 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
1935 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1936 /// Will be resolved by type-checking to an associated item.
1938 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1939 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1940 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1941 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
1943 /// Reference to a `#[lang = "foo"]` item. `HirId` of the inner expr.
1944 LangItem(LangItem, Span, Option<HirId>),
1947 impl<'hir> QPath<'hir> {
1948 /// Returns the span of this `QPath`.
1949 pub fn span(&self) -> Span {
1951 QPath::Resolved(_, path) => path.span,
1952 QPath::TypeRelative(qself, ps) => qself.span.to(ps.ident.span),
1953 QPath::LangItem(_, span, _) => span,
1957 /// Returns the span of the qself of this `QPath`. For example, `()` in
1958 /// `<() as Trait>::method`.
1959 pub fn qself_span(&self) -> Span {
1961 QPath::Resolved(_, path) => path.span,
1962 QPath::TypeRelative(qself, _) => qself.span,
1963 QPath::LangItem(_, span, _) => span,
1967 /// Returns the span of the last segment of this `QPath`. For example, `method` in
1968 /// `<() as Trait>::method`.
1969 pub fn last_segment_span(&self) -> Span {
1971 QPath::Resolved(_, path) => path.segments.last().unwrap().ident.span,
1972 QPath::TypeRelative(_, segment) => segment.ident.span,
1973 QPath::LangItem(_, span, _) => span,
1978 /// Hints at the original code for a let statement.
1979 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1980 pub enum LocalSource {
1981 /// A `match _ { .. }`.
1983 /// When lowering async functions, we create locals within the `async move` so that
1984 /// all parameters are dropped after the future is polled.
1986 /// ```ignore (pseudo-Rust)
1987 /// async fn foo(<pattern> @ x: Type) {
1989 /// let <pattern> = x;
1994 /// A desugared `<expr>.await`.
1996 /// A desugared `expr = expr`, where the LHS is a tuple, struct or array.
1997 /// The span is that of the `=` sign.
1998 AssignDesugar(Span),
2001 /// Hints at the original code for a `match _ { .. }`.
2002 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
2003 #[derive(HashStable_Generic)]
2004 pub enum MatchSource {
2005 /// A `match _ { .. }`.
2007 /// A desugared `for _ in _ { .. }` loop.
2009 /// A desugared `?` operator.
2011 /// A desugared `<expr>.await`.
2017 pub const fn name(self) -> &'static str {
2021 ForLoopDesugar => "for",
2023 AwaitDesugar => ".await",
2028 /// The loop type that yielded an `ExprKind::Loop`.
2029 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2030 pub enum LoopSource {
2031 /// A `loop { .. }` loop.
2033 /// A `while _ { .. }` loop.
2035 /// A `for _ in _ { .. }` loop.
2040 pub fn name(self) -> &'static str {
2042 LoopSource::Loop => "loop",
2043 LoopSource::While => "while",
2044 LoopSource::ForLoop => "for",
2049 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2050 pub enum LoopIdError {
2052 UnlabeledCfInWhileCondition,
2056 impl fmt::Display for LoopIdError {
2057 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2058 f.write_str(match self {
2059 LoopIdError::OutsideLoopScope => "not inside loop scope",
2060 LoopIdError::UnlabeledCfInWhileCondition => {
2061 "unlabeled control flow (break or continue) in while condition"
2063 LoopIdError::UnresolvedLabel => "label not found",
2068 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2069 pub struct Destination {
2070 // This is `Some(_)` iff there is an explicit user-specified `label
2071 pub label: Option<Label>,
2073 // These errors are caught and then reported during the diagnostics pass in
2074 // librustc_passes/loops.rs
2075 pub target_id: Result<HirId, LoopIdError>,
2078 /// The yield kind that caused an `ExprKind::Yield`.
2079 #[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
2080 pub enum YieldSource {
2081 /// An `<expr>.await`.
2082 Await { expr: Option<HirId> },
2083 /// A plain `yield`.
2088 pub fn is_await(&self) -> bool {
2089 matches!(self, YieldSource::Await { .. })
2093 impl fmt::Display for YieldSource {
2094 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2095 f.write_str(match self {
2096 YieldSource::Await { .. } => "`await`",
2097 YieldSource::Yield => "`yield`",
2102 impl From<GeneratorKind> for YieldSource {
2103 fn from(kind: GeneratorKind) -> Self {
2105 // Guess based on the kind of the current generator.
2106 GeneratorKind::Gen => Self::Yield,
2107 GeneratorKind::Async(_) => Self::Await { expr: None },
2112 // N.B., if you change this, you'll probably want to change the corresponding
2113 // type structure in middle/ty.rs as well.
2114 #[derive(Debug, HashStable_Generic)]
2115 pub struct MutTy<'hir> {
2116 pub ty: &'hir Ty<'hir>,
2117 pub mutbl: Mutability,
2120 /// Represents a function's signature in a trait declaration,
2121 /// trait implementation, or a free function.
2122 #[derive(Debug, HashStable_Generic)]
2123 pub struct FnSig<'hir> {
2124 pub header: FnHeader,
2125 pub decl: &'hir FnDecl<'hir>,
2129 // The bodies for items are stored "out of line", in a separate
2130 // hashmap in the `Crate`. Here we just record the hir-id of the item
2131 // so it can fetched later.
2132 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
2133 pub struct TraitItemId {
2134 pub def_id: LocalDefId,
2139 pub fn hir_id(&self) -> HirId {
2140 // Items are always HIR owners.
2141 HirId::make_owner(self.def_id)
2145 /// Represents an item declaration within a trait declaration,
2146 /// possibly including a default implementation. A trait item is
2147 /// either required (meaning it doesn't have an implementation, just a
2148 /// signature) or provided (meaning it has a default implementation).
2149 #[derive(Debug, HashStable_Generic)]
2150 pub struct TraitItem<'hir> {
2152 pub def_id: LocalDefId,
2153 pub generics: &'hir Generics<'hir>,
2154 pub kind: TraitItemKind<'hir>,
2158 impl TraitItem<'_> {
2160 pub fn hir_id(&self) -> HirId {
2161 // Items are always HIR owners.
2162 HirId::make_owner(self.def_id)
2165 pub fn trait_item_id(&self) -> TraitItemId {
2166 TraitItemId { def_id: self.def_id }
2170 /// Represents a trait method's body (or just argument names).
2171 #[derive(Encodable, Debug, HashStable_Generic)]
2172 pub enum TraitFn<'hir> {
2173 /// No default body in the trait, just a signature.
2174 Required(&'hir [Ident]),
2176 /// Both signature and body are provided in the trait.
2180 /// Represents a trait method or associated constant or type
2181 #[derive(Debug, HashStable_Generic)]
2182 pub enum TraitItemKind<'hir> {
2183 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
2184 Const(&'hir Ty<'hir>, Option<BodyId>),
2185 /// An associated function with an optional body.
2186 Fn(FnSig<'hir>, TraitFn<'hir>),
2187 /// An associated type with (possibly empty) bounds and optional concrete
2189 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
2192 // The bodies for items are stored "out of line", in a separate
2193 // hashmap in the `Crate`. Here we just record the hir-id of the item
2194 // so it can fetched later.
2195 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
2196 pub struct ImplItemId {
2197 pub def_id: LocalDefId,
2202 pub fn hir_id(&self) -> HirId {
2203 // Items are always HIR owners.
2204 HirId::make_owner(self.def_id)
2208 /// Represents anything within an `impl` block.
2209 #[derive(Debug, HashStable_Generic)]
2210 pub struct ImplItem<'hir> {
2212 pub def_id: LocalDefId,
2213 pub generics: &'hir Generics<'hir>,
2214 pub kind: ImplItemKind<'hir>,
2221 pub fn hir_id(&self) -> HirId {
2222 // Items are always HIR owners.
2223 HirId::make_owner(self.def_id)
2226 pub fn impl_item_id(&self) -> ImplItemId {
2227 ImplItemId { def_id: self.def_id }
2231 /// Represents various kinds of content within an `impl`.
2232 #[derive(Debug, HashStable_Generic)]
2233 pub enum ImplItemKind<'hir> {
2234 /// An associated constant of the given type, set to the constant result
2235 /// of the expression.
2236 Const(&'hir Ty<'hir>, BodyId),
2237 /// An associated function implementation with the given signature and body.
2238 Fn(FnSig<'hir>, BodyId),
2239 /// An associated type.
2240 TyAlias(&'hir Ty<'hir>),
2243 // The name of the associated type for `Fn` return types.
2244 pub const FN_OUTPUT_NAME: Symbol = sym::Output;
2246 /// Bind a type to an associated type (i.e., `A = Foo`).
2248 /// Bindings like `A: Debug` are represented as a special type `A =
2249 /// $::Debug` that is understood by the astconv code.
2251 /// FIXME(alexreg): why have a separate type for the binding case,
2252 /// wouldn't it be better to make the `ty` field an enum like the
2255 /// ```ignore (pseudo-rust)
2256 /// enum TypeBindingKind {
2261 #[derive(Debug, HashStable_Generic)]
2262 pub struct TypeBinding<'hir> {
2265 pub gen_args: &'hir GenericArgs<'hir>,
2266 pub kind: TypeBindingKind<'hir>,
2270 #[derive(Debug, HashStable_Generic)]
2271 pub enum Term<'hir> {
2276 impl<'hir> From<&'hir Ty<'hir>> for Term<'hir> {
2277 fn from(ty: &'hir Ty<'hir>) -> Self {
2282 impl<'hir> From<AnonConst> for Term<'hir> {
2283 fn from(c: AnonConst) -> Self {
2288 // Represents the two kinds of type bindings.
2289 #[derive(Debug, HashStable_Generic)]
2290 pub enum TypeBindingKind<'hir> {
2291 /// E.g., `Foo<Bar: Send>`.
2292 Constraint { bounds: &'hir [GenericBound<'hir>] },
2293 /// E.g., `Foo<Bar = ()>`, `Foo<Bar = ()>`
2294 Equality { term: Term<'hir> },
2297 impl TypeBinding<'_> {
2298 pub fn ty(&self) -> &Ty<'_> {
2300 TypeBindingKind::Equality { term: Term::Ty(ref ty) } => ty,
2301 _ => panic!("expected equality type binding for parenthesized generic args"),
2304 pub fn opt_const(&self) -> Option<&'_ AnonConst> {
2306 TypeBindingKind::Equality { term: Term::Const(ref c) } => Some(c),
2313 pub struct Ty<'hir> {
2315 pub kind: TyKind<'hir>,
2319 impl<'hir> Ty<'hir> {
2320 /// Returns `true` if `param_def_id` matches the `bounded_ty` of this predicate.
2321 pub fn as_generic_param(&self) -> Option<(DefId, Ident)> {
2322 let TyKind::Path(QPath::Resolved(None, path)) = self.kind else {
2325 let [segment] = &path.segments else {
2329 Res::Def(DefKind::TyParam, def_id)
2330 | Res::SelfTy { trait_: Some(def_id), alias_to: None } => Some((def_id, segment.ident)),
2336 /// Not represented directly in the AST; referred to by name through a `ty_path`.
2337 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
2338 #[derive(HashStable_Generic)]
2349 /// All of the primitive types
2350 pub const ALL: [Self; 17] = [
2351 // any changes here should also be reflected in `PrimTy::from_name`
2352 Self::Int(IntTy::I8),
2353 Self::Int(IntTy::I16),
2354 Self::Int(IntTy::I32),
2355 Self::Int(IntTy::I64),
2356 Self::Int(IntTy::I128),
2357 Self::Int(IntTy::Isize),
2358 Self::Uint(UintTy::U8),
2359 Self::Uint(UintTy::U16),
2360 Self::Uint(UintTy::U32),
2361 Self::Uint(UintTy::U64),
2362 Self::Uint(UintTy::U128),
2363 Self::Uint(UintTy::Usize),
2364 Self::Float(FloatTy::F32),
2365 Self::Float(FloatTy::F64),
2371 /// Like [`PrimTy::name`], but returns a &str instead of a symbol.
2374 pub fn name_str(self) -> &'static str {
2376 PrimTy::Int(i) => i.name_str(),
2377 PrimTy::Uint(u) => u.name_str(),
2378 PrimTy::Float(f) => f.name_str(),
2379 PrimTy::Str => "str",
2380 PrimTy::Bool => "bool",
2381 PrimTy::Char => "char",
2385 pub fn name(self) -> Symbol {
2387 PrimTy::Int(i) => i.name(),
2388 PrimTy::Uint(u) => u.name(),
2389 PrimTy::Float(f) => f.name(),
2390 PrimTy::Str => sym::str,
2391 PrimTy::Bool => sym::bool,
2392 PrimTy::Char => sym::char,
2396 /// Returns the matching `PrimTy` for a `Symbol` such as "str" or "i32".
2397 /// Returns `None` if no matching type is found.
2398 pub fn from_name(name: Symbol) -> Option<Self> {
2399 let ty = match name {
2400 // any changes here should also be reflected in `PrimTy::ALL`
2401 sym::i8 => Self::Int(IntTy::I8),
2402 sym::i16 => Self::Int(IntTy::I16),
2403 sym::i32 => Self::Int(IntTy::I32),
2404 sym::i64 => Self::Int(IntTy::I64),
2405 sym::i128 => Self::Int(IntTy::I128),
2406 sym::isize => Self::Int(IntTy::Isize),
2407 sym::u8 => Self::Uint(UintTy::U8),
2408 sym::u16 => Self::Uint(UintTy::U16),
2409 sym::u32 => Self::Uint(UintTy::U32),
2410 sym::u64 => Self::Uint(UintTy::U64),
2411 sym::u128 => Self::Uint(UintTy::U128),
2412 sym::usize => Self::Uint(UintTy::Usize),
2413 sym::f32 => Self::Float(FloatTy::F32),
2414 sym::f64 => Self::Float(FloatTy::F64),
2415 sym::bool => Self::Bool,
2416 sym::char => Self::Char,
2417 sym::str => Self::Str,
2424 #[derive(Debug, HashStable_Generic)]
2425 pub struct BareFnTy<'hir> {
2426 pub unsafety: Unsafety,
2428 pub generic_params: &'hir [GenericParam<'hir>],
2429 pub decl: &'hir FnDecl<'hir>,
2430 pub param_names: &'hir [Ident],
2433 #[derive(Debug, HashStable_Generic)]
2434 pub struct OpaqueTy<'hir> {
2435 pub generics: &'hir Generics<'hir>,
2436 pub bounds: GenericBounds<'hir>,
2437 pub origin: OpaqueTyOrigin,
2440 /// From whence the opaque type came.
2441 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2442 pub enum OpaqueTyOrigin {
2444 FnReturn(LocalDefId),
2446 AsyncFn(LocalDefId),
2447 /// type aliases: `type Foo = impl Trait;`
2451 /// The various kinds of types recognized by the compiler.
2452 #[derive(Debug, HashStable_Generic)]
2453 pub enum TyKind<'hir> {
2454 /// A variable length slice (i.e., `[T]`).
2455 Slice(&'hir Ty<'hir>),
2456 /// A fixed length array (i.e., `[T; n]`).
2457 Array(&'hir Ty<'hir>, ArrayLen),
2458 /// A raw pointer (i.e., `*const T` or `*mut T`).
2460 /// A reference (i.e., `&'a T` or `&'a mut T`).
2461 Rptr(Lifetime, MutTy<'hir>),
2462 /// A bare function (e.g., `fn(usize) -> bool`).
2463 BareFn(&'hir BareFnTy<'hir>),
2464 /// The never type (`!`).
2466 /// A tuple (`(A, B, C, D, ...)`).
2467 Tup(&'hir [Ty<'hir>]),
2468 /// A path to a type definition (`module::module::...::Type`), or an
2469 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2471 /// Type parameters may be stored in each `PathSegment`.
2473 /// An opaque type definition itself. This is only used for `impl Trait`.
2475 /// The generic argument list contains the lifetimes (and in the future
2476 /// possibly parameters) that are actually bound on the `impl Trait`.
2477 OpaqueDef(ItemId, &'hir [GenericArg<'hir>]),
2478 /// A trait object type `Bound1 + Bound2 + Bound3`
2479 /// where `Bound` is a trait or a lifetime.
2480 TraitObject(&'hir [PolyTraitRef<'hir>], Lifetime, TraitObjectSyntax),
2483 /// `TyKind::Infer` means the type should be inferred instead of it having been
2484 /// specified. This can appear anywhere in a type.
2486 /// Placeholder for a type that has failed to be defined.
2490 #[derive(Debug, HashStable_Generic)]
2491 pub enum InlineAsmOperand<'hir> {
2493 reg: InlineAsmRegOrRegClass,
2497 reg: InlineAsmRegOrRegClass,
2499 expr: Option<Expr<'hir>>,
2502 reg: InlineAsmRegOrRegClass,
2507 reg: InlineAsmRegOrRegClass,
2509 in_expr: Expr<'hir>,
2510 out_expr: Option<Expr<'hir>>,
2513 anon_const: AnonConst,
2516 anon_const: AnonConst,
2524 impl<'hir> InlineAsmOperand<'hir> {
2525 pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
2527 Self::In { reg, .. }
2528 | Self::Out { reg, .. }
2529 | Self::InOut { reg, .. }
2530 | Self::SplitInOut { reg, .. } => Some(reg),
2531 Self::Const { .. } | Self::SymFn { .. } | Self::SymStatic { .. } => None,
2535 pub fn is_clobber(&self) -> bool {
2538 InlineAsmOperand::Out { reg: InlineAsmRegOrRegClass::Reg(_), late: _, expr: None }
2543 #[derive(Debug, HashStable_Generic)]
2544 pub struct InlineAsm<'hir> {
2545 pub template: &'hir [InlineAsmTemplatePiece],
2546 pub template_strs: &'hir [(Symbol, Option<Symbol>, Span)],
2547 pub operands: &'hir [(InlineAsmOperand<'hir>, Span)],
2548 pub options: InlineAsmOptions,
2549 pub line_spans: &'hir [Span],
2552 /// Represents a parameter in a function header.
2553 #[derive(Debug, HashStable_Generic)]
2554 pub struct Param<'hir> {
2556 pub pat: &'hir Pat<'hir>,
2561 /// Represents the header (not the body) of a function declaration.
2562 #[derive(Debug, HashStable_Generic)]
2563 pub struct FnDecl<'hir> {
2564 /// The types of the function's parameters.
2566 /// Additional argument data is stored in the function's [body](Body::params).
2567 pub inputs: &'hir [Ty<'hir>],
2568 pub output: FnRetTy<'hir>,
2569 pub c_variadic: bool,
2570 /// Does the function have an implicit self?
2571 pub implicit_self: ImplicitSelfKind,
2574 /// Represents what type of implicit self a function has, if any.
2575 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2576 pub enum ImplicitSelfKind {
2577 /// Represents a `fn x(self);`.
2579 /// Represents a `fn x(mut self);`.
2581 /// Represents a `fn x(&self);`.
2583 /// Represents a `fn x(&mut self);`.
2585 /// Represents when a function does not have a self argument or
2586 /// when a function has a `self: X` argument.
2590 impl ImplicitSelfKind {
2591 /// Does this represent an implicit self?
2592 pub fn has_implicit_self(&self) -> bool {
2593 !matches!(*self, ImplicitSelfKind::None)
2597 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable, Debug)]
2598 #[derive(HashStable_Generic)]
2604 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable, HashStable_Generic)]
2605 pub enum Defaultness {
2606 Default { has_value: bool },
2611 pub fn has_value(&self) -> bool {
2613 Defaultness::Default { has_value } => has_value,
2614 Defaultness::Final => true,
2618 pub fn is_final(&self) -> bool {
2619 *self == Defaultness::Final
2622 pub fn is_default(&self) -> bool {
2623 matches!(*self, Defaultness::Default { .. })
2627 #[derive(Debug, HashStable_Generic)]
2628 pub enum FnRetTy<'hir> {
2629 /// Return type is not specified.
2631 /// Functions default to `()` and
2632 /// closures default to inference. Span points to where return
2633 /// type would be inserted.
2634 DefaultReturn(Span),
2635 /// Everything else.
2636 Return(&'hir Ty<'hir>),
2641 pub fn span(&self) -> Span {
2643 Self::DefaultReturn(span) => span,
2644 Self::Return(ref ty) => ty.span,
2649 #[derive(Encodable, Debug, HashStable_Generic)]
2650 pub struct Mod<'hir> {
2651 pub spans: ModSpans,
2652 pub item_ids: &'hir [ItemId],
2655 #[derive(Copy, Clone, Debug, HashStable_Generic, Encodable)]
2656 pub struct ModSpans {
2657 /// A span from the first token past `{` to the last token until `}`.
2658 /// For `mod foo;`, the inner span ranges from the first token
2659 /// to the last token in the external file.
2660 pub inner_span: Span,
2661 pub inject_use_span: Span,
2664 #[derive(Debug, HashStable_Generic)]
2665 pub struct EnumDef<'hir> {
2666 pub variants: &'hir [Variant<'hir>],
2669 #[derive(Debug, HashStable_Generic)]
2670 pub struct Variant<'hir> {
2671 /// Name of the variant.
2673 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2675 /// Fields and constructor id of the variant.
2676 pub data: VariantData<'hir>,
2677 /// Explicit discriminant (e.g., `Foo = 1`).
2678 pub disr_expr: Option<AnonConst>,
2683 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2685 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2686 /// Also produced for each element of a list `use`, e.g.
2687 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2690 /// Glob import, e.g., `use foo::*`.
2693 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2694 /// an additional `use foo::{}` for performing checks such as
2695 /// unstable feature gating. May be removed in the future.
2699 /// References to traits in impls.
2701 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2702 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2703 /// trait being referred to but just a unique `HirId` that serves as a key
2704 /// within the resolution map.
2705 #[derive(Clone, Debug, HashStable_Generic)]
2706 pub struct TraitRef<'hir> {
2707 pub path: &'hir Path<'hir>,
2708 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2709 #[stable_hasher(ignore)]
2710 pub hir_ref_id: HirId,
2714 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2715 pub fn trait_def_id(&self) -> Option<DefId> {
2716 match self.path.res {
2717 Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
2719 _ => unreachable!(),
2724 #[derive(Clone, Debug, HashStable_Generic)]
2725 pub struct PolyTraitRef<'hir> {
2726 /// The `'a` in `for<'a> Foo<&'a T>`.
2727 pub bound_generic_params: &'hir [GenericParam<'hir>],
2729 /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
2730 pub trait_ref: TraitRef<'hir>,
2735 #[derive(Debug, HashStable_Generic)]
2736 pub struct FieldDef<'hir> {
2741 pub ty: &'hir Ty<'hir>,
2745 // Still necessary in couple of places
2746 pub fn is_positional(&self) -> bool {
2747 let first = self.ident.as_str().as_bytes()[0];
2748 (b'0'..=b'9').contains(&first)
2752 /// Fields and constructor IDs of enum variants and structs.
2753 #[derive(Debug, HashStable_Generic)]
2754 pub enum VariantData<'hir> {
2755 /// A struct variant.
2757 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2758 Struct(&'hir [FieldDef<'hir>], /* recovered */ bool),
2759 /// A tuple variant.
2761 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2762 Tuple(&'hir [FieldDef<'hir>], HirId),
2765 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2769 impl<'hir> VariantData<'hir> {
2770 /// Return the fields of this variant.
2771 pub fn fields(&self) -> &'hir [FieldDef<'hir>] {
2773 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2778 /// Return the `HirId` of this variant's constructor, if it has one.
2779 pub fn ctor_hir_id(&self) -> Option<HirId> {
2781 VariantData::Struct(_, _) => None,
2782 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2787 // The bodies for items are stored "out of line", in a separate
2788 // hashmap in the `Crate`. Here we just record the hir-id of the item
2789 // so it can fetched later.
2790 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, Hash, HashStable_Generic)]
2792 pub def_id: LocalDefId,
2797 pub fn hir_id(&self) -> HirId {
2798 // Items are always HIR owners.
2799 HirId::make_owner(self.def_id)
2805 /// The name might be a dummy name in case of anonymous items
2806 #[derive(Debug, HashStable_Generic)]
2807 pub struct Item<'hir> {
2809 pub def_id: LocalDefId,
2810 pub kind: ItemKind<'hir>,
2817 pub fn hir_id(&self) -> HirId {
2818 // Items are always HIR owners.
2819 HirId::make_owner(self.def_id)
2822 pub fn item_id(&self) -> ItemId {
2823 ItemId { def_id: self.def_id }
2827 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2828 #[derive(Encodable, Decodable, HashStable_Generic)]
2835 pub fn prefix_str(&self) -> &'static str {
2837 Self::Unsafe => "unsafe ",
2843 impl fmt::Display for Unsafety {
2844 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2845 f.write_str(match *self {
2846 Self::Unsafe => "unsafe",
2847 Self::Normal => "normal",
2852 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2853 #[derive(Encodable, Decodable, HashStable_Generic)]
2854 pub enum Constness {
2859 impl fmt::Display for Constness {
2860 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2861 f.write_str(match *self {
2862 Self::Const => "const",
2863 Self::NotConst => "non-const",
2868 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2869 pub struct FnHeader {
2870 pub unsafety: Unsafety,
2871 pub constness: Constness,
2872 pub asyncness: IsAsync,
2877 pub fn is_async(&self) -> bool {
2878 matches!(&self.asyncness, IsAsync::Async)
2881 pub fn is_const(&self) -> bool {
2882 matches!(&self.constness, Constness::Const)
2885 pub fn is_unsafe(&self) -> bool {
2886 matches!(&self.unsafety, Unsafety::Unsafe)
2890 #[derive(Debug, HashStable_Generic)]
2891 pub enum ItemKind<'hir> {
2892 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2894 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2895 ExternCrate(Option<Symbol>),
2897 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2901 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2902 Use(&'hir Path<'hir>, UseKind),
2904 /// A `static` item.
2905 Static(&'hir Ty<'hir>, Mutability, BodyId),
2907 Const(&'hir Ty<'hir>, BodyId),
2908 /// A function declaration.
2909 Fn(FnSig<'hir>, &'hir Generics<'hir>, BodyId),
2910 /// A MBE macro definition (`macro_rules!` or `macro`).
2911 Macro(ast::MacroDef, MacroKind),
2914 /// An external module, e.g. `extern { .. }`.
2915 ForeignMod { abi: Abi, items: &'hir [ForeignItemRef] },
2916 /// Module-level inline assembly (from `global_asm!`).
2917 GlobalAsm(&'hir InlineAsm<'hir>),
2918 /// A type alias, e.g., `type Foo = Bar<u8>`.
2919 TyAlias(&'hir Ty<'hir>, &'hir Generics<'hir>),
2920 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2921 OpaqueTy(OpaqueTy<'hir>),
2922 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2923 Enum(EnumDef<'hir>, &'hir Generics<'hir>),
2924 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2925 Struct(VariantData<'hir>, &'hir Generics<'hir>),
2926 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2927 Union(VariantData<'hir>, &'hir Generics<'hir>),
2928 /// A trait definition.
2929 Trait(IsAuto, Unsafety, &'hir Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
2931 TraitAlias(&'hir Generics<'hir>, GenericBounds<'hir>),
2933 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2934 Impl(&'hir Impl<'hir>),
2937 #[derive(Debug, HashStable_Generic)]
2938 pub struct Impl<'hir> {
2939 pub unsafety: Unsafety,
2940 pub polarity: ImplPolarity,
2941 pub defaultness: Defaultness,
2942 // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata
2943 // decoding as `Span`s cannot be decoded when a `Session` is not available.
2944 pub defaultness_span: Option<Span>,
2945 pub constness: Constness,
2946 pub generics: &'hir Generics<'hir>,
2948 /// The trait being implemented, if any.
2949 pub of_trait: Option<TraitRef<'hir>>,
2951 pub self_ty: &'hir Ty<'hir>,
2952 pub items: &'hir [ImplItemRef],
2956 pub fn generics(&self) -> Option<&Generics<'_>> {
2958 ItemKind::Fn(_, ref generics, _)
2959 | ItemKind::TyAlias(_, ref generics)
2960 | ItemKind::OpaqueTy(OpaqueTy {
2961 ref generics, origin: OpaqueTyOrigin::TyAlias, ..
2963 | ItemKind::Enum(_, ref generics)
2964 | ItemKind::Struct(_, ref generics)
2965 | ItemKind::Union(_, ref generics)
2966 | ItemKind::Trait(_, _, ref generics, _, _)
2967 | ItemKind::Impl(Impl { ref generics, .. }) => generics,
2972 pub fn descr(&self) -> &'static str {
2974 ItemKind::ExternCrate(..) => "extern crate",
2975 ItemKind::Use(..) => "`use` import",
2976 ItemKind::Static(..) => "static item",
2977 ItemKind::Const(..) => "constant item",
2978 ItemKind::Fn(..) => "function",
2979 ItemKind::Macro(..) => "macro",
2980 ItemKind::Mod(..) => "module",
2981 ItemKind::ForeignMod { .. } => "extern block",
2982 ItemKind::GlobalAsm(..) => "global asm item",
2983 ItemKind::TyAlias(..) => "type alias",
2984 ItemKind::OpaqueTy(..) => "opaque type",
2985 ItemKind::Enum(..) => "enum",
2986 ItemKind::Struct(..) => "struct",
2987 ItemKind::Union(..) => "union",
2988 ItemKind::Trait(..) => "trait",
2989 ItemKind::TraitAlias(..) => "trait alias",
2990 ItemKind::Impl(..) => "implementation",
2995 /// A reference from an trait to one of its associated items. This
2996 /// contains the item's id, naturally, but also the item's name and
2997 /// some other high-level details (like whether it is an associated
2998 /// type or method, and whether it is public). This allows other
2999 /// passes to find the impl they want without loading the ID (which
3000 /// means fewer edges in the incremental compilation graph).
3001 #[derive(Encodable, Debug, HashStable_Generic)]
3002 pub struct TraitItemRef {
3003 pub id: TraitItemId,
3005 pub kind: AssocItemKind,
3007 pub defaultness: Defaultness,
3010 /// A reference from an impl to one of its associated items. This
3011 /// contains the item's ID, naturally, but also the item's name and
3012 /// some other high-level details (like whether it is an associated
3013 /// type or method, and whether it is public). This allows other
3014 /// passes to find the impl they want without loading the ID (which
3015 /// means fewer edges in the incremental compilation graph).
3016 #[derive(Debug, HashStable_Generic)]
3017 pub struct ImplItemRef {
3020 pub kind: AssocItemKind,
3022 pub defaultness: Defaultness,
3023 /// When we are in a trait impl, link to the trait-item's id.
3024 pub trait_item_def_id: Option<DefId>,
3027 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
3028 pub enum AssocItemKind {
3030 Fn { has_self: bool },
3034 // The bodies for items are stored "out of line", in a separate
3035 // hashmap in the `Crate`. Here we just record the hir-id of the item
3036 // so it can fetched later.
3037 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
3038 pub struct ForeignItemId {
3039 pub def_id: LocalDefId,
3042 impl ForeignItemId {
3044 pub fn hir_id(&self) -> HirId {
3045 // Items are always HIR owners.
3046 HirId::make_owner(self.def_id)
3050 /// A reference from a foreign block to one of its items. This
3051 /// contains the item's ID, naturally, but also the item's name and
3052 /// some other high-level details (like whether it is an associated
3053 /// type or method, and whether it is public). This allows other
3054 /// passes to find the impl they want without loading the ID (which
3055 /// means fewer edges in the incremental compilation graph).
3056 #[derive(Debug, HashStable_Generic)]
3057 pub struct ForeignItemRef {
3058 pub id: ForeignItemId,
3063 #[derive(Debug, HashStable_Generic)]
3064 pub struct ForeignItem<'hir> {
3066 pub kind: ForeignItemKind<'hir>,
3067 pub def_id: LocalDefId,
3072 impl ForeignItem<'_> {
3074 pub fn hir_id(&self) -> HirId {
3075 // Items are always HIR owners.
3076 HirId::make_owner(self.def_id)
3079 pub fn foreign_item_id(&self) -> ForeignItemId {
3080 ForeignItemId { def_id: self.def_id }
3084 /// An item within an `extern` block.
3085 #[derive(Debug, HashStable_Generic)]
3086 pub enum ForeignItemKind<'hir> {
3087 /// A foreign function.
3088 Fn(&'hir FnDecl<'hir>, &'hir [Ident], &'hir Generics<'hir>),
3089 /// A foreign static item (`static ext: u8`).
3090 Static(&'hir Ty<'hir>, Mutability),
3095 /// A variable captured by a closure.
3096 #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)]
3098 // First span where it is accessed (there can be multiple).
3102 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
3103 // has length > 0 if the trait is found through an chain of imports, starting with the
3104 // import/use statement in the scope where the trait is used.
3105 #[derive(Encodable, Decodable, Clone, Debug, HashStable_Generic)]
3106 pub struct TraitCandidate {
3108 pub import_ids: SmallVec<[LocalDefId; 1]>,
3111 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3112 pub enum OwnerNode<'hir> {
3113 Item(&'hir Item<'hir>),
3114 ForeignItem(&'hir ForeignItem<'hir>),
3115 TraitItem(&'hir TraitItem<'hir>),
3116 ImplItem(&'hir ImplItem<'hir>),
3117 Crate(&'hir Mod<'hir>),
3120 impl<'hir> OwnerNode<'hir> {
3121 pub fn ident(&self) -> Option<Ident> {
3123 OwnerNode::Item(Item { ident, .. })
3124 | OwnerNode::ForeignItem(ForeignItem { ident, .. })
3125 | OwnerNode::ImplItem(ImplItem { ident, .. })
3126 | OwnerNode::TraitItem(TraitItem { ident, .. }) => Some(*ident),
3127 OwnerNode::Crate(..) => None,
3131 pub fn span(&self) -> Span {
3133 OwnerNode::Item(Item { span, .. })
3134 | OwnerNode::ForeignItem(ForeignItem { span, .. })
3135 | OwnerNode::ImplItem(ImplItem { span, .. })
3136 | OwnerNode::TraitItem(TraitItem { span, .. }) => *span,
3137 OwnerNode::Crate(Mod { spans: ModSpans { inner_span, .. }, .. }) => *inner_span,
3141 pub fn fn_decl(&self) -> Option<&FnDecl<'hir>> {
3143 OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3144 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3145 | OwnerNode::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3146 OwnerNode::ForeignItem(ForeignItem {
3147 kind: ForeignItemKind::Fn(fn_decl, _, _),
3149 }) => Some(fn_decl),
3154 pub fn body_id(&self) -> Option<BodyId> {
3156 OwnerNode::TraitItem(TraitItem {
3157 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3160 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3161 | OwnerNode::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3166 pub fn generics(&self) -> Option<&'hir Generics<'hir>> {
3168 OwnerNode::TraitItem(TraitItem { generics, .. })
3169 | OwnerNode::ImplItem(ImplItem { generics, .. }) => Some(generics),
3170 OwnerNode::Item(item) => item.kind.generics(),
3175 pub fn def_id(self) -> LocalDefId {
3177 OwnerNode::Item(Item { def_id, .. })
3178 | OwnerNode::TraitItem(TraitItem { def_id, .. })
3179 | OwnerNode::ImplItem(ImplItem { def_id, .. })
3180 | OwnerNode::ForeignItem(ForeignItem { def_id, .. }) => *def_id,
3181 OwnerNode::Crate(..) => crate::CRATE_HIR_ID.owner,
3185 pub fn expect_item(self) -> &'hir Item<'hir> {
3187 OwnerNode::Item(n) => n,
3192 pub fn expect_foreign_item(self) -> &'hir ForeignItem<'hir> {
3194 OwnerNode::ForeignItem(n) => n,
3199 pub fn expect_impl_item(self) -> &'hir ImplItem<'hir> {
3201 OwnerNode::ImplItem(n) => n,
3206 pub fn expect_trait_item(self) -> &'hir TraitItem<'hir> {
3208 OwnerNode::TraitItem(n) => n,
3214 impl<'hir> Into<OwnerNode<'hir>> for &'hir Item<'hir> {
3215 fn into(self) -> OwnerNode<'hir> {
3216 OwnerNode::Item(self)
3220 impl<'hir> Into<OwnerNode<'hir>> for &'hir ForeignItem<'hir> {
3221 fn into(self) -> OwnerNode<'hir> {
3222 OwnerNode::ForeignItem(self)
3226 impl<'hir> Into<OwnerNode<'hir>> for &'hir ImplItem<'hir> {
3227 fn into(self) -> OwnerNode<'hir> {
3228 OwnerNode::ImplItem(self)
3232 impl<'hir> Into<OwnerNode<'hir>> for &'hir TraitItem<'hir> {
3233 fn into(self) -> OwnerNode<'hir> {
3234 OwnerNode::TraitItem(self)
3238 impl<'hir> Into<Node<'hir>> for OwnerNode<'hir> {
3239 fn into(self) -> Node<'hir> {
3241 OwnerNode::Item(n) => Node::Item(n),
3242 OwnerNode::ForeignItem(n) => Node::ForeignItem(n),
3243 OwnerNode::ImplItem(n) => Node::ImplItem(n),
3244 OwnerNode::TraitItem(n) => Node::TraitItem(n),
3245 OwnerNode::Crate(n) => Node::Crate(n),
3250 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3251 pub enum Node<'hir> {
3252 Param(&'hir Param<'hir>),
3253 Item(&'hir Item<'hir>),
3254 ForeignItem(&'hir ForeignItem<'hir>),
3255 TraitItem(&'hir TraitItem<'hir>),
3256 ImplItem(&'hir ImplItem<'hir>),
3257 Variant(&'hir Variant<'hir>),
3258 Field(&'hir FieldDef<'hir>),
3259 AnonConst(&'hir AnonConst),
3260 Expr(&'hir Expr<'hir>),
3261 Stmt(&'hir Stmt<'hir>),
3262 PathSegment(&'hir PathSegment<'hir>),
3264 TraitRef(&'hir TraitRef<'hir>),
3265 Binding(&'hir Pat<'hir>),
3266 Pat(&'hir Pat<'hir>),
3267 Arm(&'hir Arm<'hir>),
3268 Block(&'hir Block<'hir>),
3269 Local(&'hir Local<'hir>),
3271 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
3272 /// with synthesized constructors.
3273 Ctor(&'hir VariantData<'hir>),
3275 Lifetime(&'hir Lifetime),
3276 GenericParam(&'hir GenericParam<'hir>),
3278 Crate(&'hir Mod<'hir>),
3280 Infer(&'hir InferArg),
3283 impl<'hir> Node<'hir> {
3284 /// Get the identifier of this `Node`, if applicable.
3288 /// Calling `.ident()` on a [`Node::Ctor`] will return `None`
3289 /// because `Ctor`s do not have identifiers themselves.
3290 /// Instead, call `.ident()` on the parent struct/variant, like so:
3292 /// ```ignore (illustrative)
3295 /// .and_then(|ctor_id| tcx.hir().find(tcx.hir().get_parent_node(ctor_id)))
3296 /// .and_then(|parent| parent.ident())
3298 pub fn ident(&self) -> Option<Ident> {
3300 Node::TraitItem(TraitItem { ident, .. })
3301 | Node::ImplItem(ImplItem { ident, .. })
3302 | Node::ForeignItem(ForeignItem { ident, .. })
3303 | Node::Field(FieldDef { ident, .. })
3304 | Node::Variant(Variant { ident, .. })
3305 | Node::Item(Item { ident, .. })
3306 | Node::PathSegment(PathSegment { ident, .. }) => Some(*ident),
3307 Node::Lifetime(lt) => Some(lt.name.ident()),
3308 Node::GenericParam(p) => Some(p.name.ident()),
3310 | Node::AnonConst(..)
3321 | Node::TraitRef(..)
3322 | Node::Infer(..) => None,
3326 pub fn fn_decl(&self) -> Option<&'hir FnDecl<'hir>> {
3328 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3329 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3330 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3331 Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
3338 pub fn fn_sig(&self) -> Option<&'hir FnSig<'hir>> {
3340 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3341 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3342 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig),
3347 pub fn body_id(&self) -> Option<BodyId> {
3349 Node::TraitItem(TraitItem {
3350 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3353 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3354 | Node::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3359 pub fn generics(&self) -> Option<&'hir Generics<'hir>> {
3361 Node::TraitItem(TraitItem { generics, .. })
3362 | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
3363 Node::Item(item) => item.kind.generics(),
3368 pub fn as_owner(self) -> Option<OwnerNode<'hir>> {
3370 Node::Item(i) => Some(OwnerNode::Item(i)),
3371 Node::ForeignItem(i) => Some(OwnerNode::ForeignItem(i)),
3372 Node::TraitItem(i) => Some(OwnerNode::TraitItem(i)),
3373 Node::ImplItem(i) => Some(OwnerNode::ImplItem(i)),
3374 Node::Crate(i) => Some(OwnerNode::Crate(i)),
3379 pub fn fn_kind(self) -> Option<FnKind<'hir>> {
3381 Node::Item(i) => match i.kind {
3382 ItemKind::Fn(ref sig, ref generics, _) => {
3383 Some(FnKind::ItemFn(i.ident, generics, sig.header))
3387 Node::TraitItem(ti) => match ti.kind {
3388 TraitItemKind::Fn(ref sig, TraitFn::Provided(_)) => {
3389 Some(FnKind::Method(ti.ident, sig))
3393 Node::ImplItem(ii) => match ii.kind {
3394 ImplItemKind::Fn(ref sig, _) => Some(FnKind::Method(ii.ident, sig)),
3397 Node::Expr(e) => match e.kind {
3398 ExprKind::Closure(..) => Some(FnKind::Closure),
3405 /// Get the fields for the tuple-constructor,
3406 /// if this node is a tuple constructor, otherwise None
3407 pub fn tuple_fields(&self) -> Option<&'hir [FieldDef<'hir>]> {
3408 if let Node::Ctor(&VariantData::Tuple(fields, _)) = self { Some(fields) } else { None }
3412 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3413 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
3415 rustc_data_structures::static_assert_size!(super::Block<'static>, 48);
3416 rustc_data_structures::static_assert_size!(super::Expr<'static>, 56);
3417 rustc_data_structures::static_assert_size!(super::Pat<'static>, 88);
3418 rustc_data_structures::static_assert_size!(super::QPath<'static>, 24);
3419 rustc_data_structures::static_assert_size!(super::Ty<'static>, 72);
3420 rustc_data_structures::static_assert_size!(super::GenericBound<'_>, 48);
3421 rustc_data_structures::static_assert_size!(super::Generics<'static>, 56);
3422 rustc_data_structures::static_assert_size!(super::Impl<'static>, 80);
3424 rustc_data_structures::static_assert_size!(super::Item<'static>, 80);
3425 rustc_data_structures::static_assert_size!(super::TraitItem<'static>, 88);
3426 rustc_data_structures::static_assert_size!(super::ImplItem<'static>, 80);
3427 rustc_data_structures::static_assert_size!(super::ForeignItem<'static>, 72);