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:
54 /// impl Foo<'_> for u32
56 /// in that case, we rewrite to
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.in_where_clause,
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 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
725 #[derive(Debug, HashStable_Generic)]
726 pub struct WhereBoundPredicate<'hir> {
728 pub in_where_clause: bool,
729 /// Any generics from a `for` binding.
730 pub bound_generic_params: &'hir [GenericParam<'hir>],
731 /// The type being bounded.
732 pub bounded_ty: &'hir Ty<'hir>,
733 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
734 pub bounds: GenericBounds<'hir>,
737 impl<'hir> WhereBoundPredicate<'hir> {
738 /// Returns `true` if `param_def_id` matches the `bounded_ty` of this predicate.
739 pub fn is_param_bound(&self, param_def_id: DefId) -> bool {
740 self.bounded_ty.as_generic_param().map_or(false, |(def_id, _)| def_id == param_def_id)
744 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
745 #[derive(Debug, HashStable_Generic)]
746 pub struct WhereRegionPredicate<'hir> {
748 pub in_where_clause: bool,
749 pub lifetime: Lifetime,
750 pub bounds: GenericBounds<'hir>,
753 /// An equality predicate (e.g., `T = int`); currently unsupported.
754 #[derive(Debug, HashStable_Generic)]
755 pub struct WhereEqPredicate<'hir> {
758 pub lhs_ty: &'hir Ty<'hir>,
759 pub rhs_ty: &'hir Ty<'hir>,
762 /// HIR node coupled with its parent's id in the same HIR owner.
764 /// The parent is trash when the node is a HIR owner.
765 #[derive(Clone, Debug)]
766 pub struct ParentedNode<'tcx> {
767 pub parent: ItemLocalId,
768 pub node: Node<'tcx>,
771 /// Attributes owned by a HIR owner.
773 pub struct AttributeMap<'tcx> {
774 pub map: SortedMap<ItemLocalId, &'tcx [Attribute]>,
775 pub hash: Fingerprint,
778 impl<'tcx> AttributeMap<'tcx> {
779 pub const EMPTY: &'static AttributeMap<'static> =
780 &AttributeMap { map: SortedMap::new(), hash: Fingerprint::ZERO };
783 pub fn get(&self, id: ItemLocalId) -> &'tcx [Attribute] {
784 self.map.get(&id).copied().unwrap_or(&[])
788 /// Map of all HIR nodes inside the current owner.
789 /// These nodes are mapped by `ItemLocalId` alongside the index of their parent node.
790 /// The HIR tree, including bodies, is pre-hashed.
792 pub struct OwnerNodes<'tcx> {
793 /// Pre-computed hash of the full HIR.
794 pub hash_including_bodies: Fingerprint,
795 /// Pre-computed hash of the item signature, sithout recursing into the body.
796 pub hash_without_bodies: Fingerprint,
797 /// Full HIR for the current owner.
798 // The zeroth node's parent should never be accessed: the owner's parent is computed by the
799 // hir_owner_parent query. It is set to `ItemLocalId::INVALID` to force an ICE if accidentally
801 pub nodes: IndexVec<ItemLocalId, Option<ParentedNode<'tcx>>>,
802 /// Content of local bodies.
803 pub bodies: SortedMap<ItemLocalId, &'tcx Body<'tcx>>,
804 /// Non-owning definitions contained in this owner.
805 pub local_id_to_def_id: SortedMap<ItemLocalId, LocalDefId>,
808 impl<'tcx> OwnerNodes<'tcx> {
809 pub fn node(&self) -> OwnerNode<'tcx> {
810 use rustc_index::vec::Idx;
811 let node = self.nodes[ItemLocalId::new(0)].as_ref().unwrap().node;
812 let node = node.as_owner().unwrap(); // Indexing must ensure it is an OwnerNode.
817 /// Full information resulting from lowering an AST node.
818 #[derive(Debug, HashStable_Generic)]
819 pub struct OwnerInfo<'hir> {
820 /// Contents of the HIR.
821 pub nodes: OwnerNodes<'hir>,
822 /// Map from each nested owner to its parent's local id.
823 pub parenting: FxHashMap<LocalDefId, ItemLocalId>,
824 /// Collected attributes of the HIR nodes.
825 pub attrs: AttributeMap<'hir>,
826 /// Map indicating what traits are in scope for places where this
827 /// is relevant; generated by resolve.
828 pub trait_map: FxHashMap<ItemLocalId, Box<[TraitCandidate]>>,
831 impl<'tcx> OwnerInfo<'tcx> {
833 pub fn node(&self) -> OwnerNode<'tcx> {
838 #[derive(Copy, Clone, Debug, HashStable_Generic)]
839 pub enum MaybeOwner<T> {
842 /// Used as a placeholder for unused LocalDefId.
846 impl<T> MaybeOwner<T> {
847 pub fn as_owner(self) -> Option<T> {
849 MaybeOwner::Owner(i) => Some(i),
850 MaybeOwner::NonOwner(_) | MaybeOwner::Phantom => None,
854 pub fn map<U>(self, f: impl FnOnce(T) -> U) -> MaybeOwner<U> {
856 MaybeOwner::Owner(i) => MaybeOwner::Owner(f(i)),
857 MaybeOwner::NonOwner(hir_id) => MaybeOwner::NonOwner(hir_id),
858 MaybeOwner::Phantom => MaybeOwner::Phantom,
862 pub fn unwrap(self) -> T {
864 MaybeOwner::Owner(i) => i,
865 MaybeOwner::NonOwner(_) | MaybeOwner::Phantom => panic!("Not a HIR owner"),
870 /// The top-level data structure that stores the entire contents of
871 /// the crate currently being compiled.
873 /// For more details, see the [rustc dev guide].
875 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
877 pub struct Crate<'hir> {
878 pub owners: IndexVec<LocalDefId, MaybeOwner<&'hir OwnerInfo<'hir>>>,
879 pub hir_hash: Fingerprint,
882 /// A block of statements `{ .. }`, which may have a label (in this case the
883 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
884 /// the `rules` being anything but `DefaultBlock`.
885 #[derive(Debug, HashStable_Generic)]
886 pub struct Block<'hir> {
887 /// Statements in a block.
888 pub stmts: &'hir [Stmt<'hir>],
889 /// An expression at the end of the block
890 /// without a semicolon, if any.
891 pub expr: Option<&'hir Expr<'hir>>,
892 #[stable_hasher(ignore)]
894 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
895 pub rules: BlockCheckMode,
897 /// If true, then there may exist `break 'a` values that aim to
898 /// break out of this block early.
899 /// Used by `'label: {}` blocks and by `try {}` blocks.
900 pub targeted_by_break: bool,
903 #[derive(Debug, HashStable_Generic)]
904 pub struct Pat<'hir> {
905 #[stable_hasher(ignore)]
907 pub kind: PatKind<'hir>,
909 // Whether to use default binding modes.
910 // At present, this is false only for destructuring assignment.
911 pub default_binding_modes: bool,
914 impl<'hir> Pat<'hir> {
915 // FIXME(#19596) this is a workaround, but there should be a better way
916 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) -> bool {
923 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
924 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
925 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
926 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
927 Slice(before, slice, after) => {
928 before.iter().chain(slice).chain(after.iter()).all(|p| p.walk_short_(it))
933 /// Walk the pattern in left-to-right order,
934 /// short circuiting (with `.all(..)`) if `false` is returned.
936 /// Note that when visiting e.g. `Tuple(ps)`,
937 /// if visiting `ps[0]` returns `false`,
938 /// then `ps[1]` will not be visited.
939 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) -> bool {
940 self.walk_short_(&mut it)
943 // FIXME(#19596) this is a workaround, but there should be a better way
944 fn walk_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) {
951 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
952 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
953 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
954 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
955 Slice(before, slice, after) => {
956 before.iter().chain(slice).chain(after.iter()).for_each(|p| p.walk_(it))
961 /// Walk the pattern in left-to-right order.
963 /// If `it(pat)` returns `false`, the children are not visited.
964 pub fn walk(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) {
968 /// Walk the pattern in left-to-right order.
970 /// If you always want to recurse, prefer this method over `walk`.
971 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
979 /// A single field in a struct pattern.
981 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
982 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
983 /// except `is_shorthand` is true.
984 #[derive(Debug, HashStable_Generic)]
985 pub struct PatField<'hir> {
986 #[stable_hasher(ignore)]
988 /// The identifier for the field.
990 /// The pattern the field is destructured to.
991 pub pat: &'hir Pat<'hir>,
992 pub is_shorthand: bool,
996 /// Explicit binding annotations given in the HIR for a binding. Note
997 /// that this is not the final binding *mode* that we infer after type
999 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1000 pub enum BindingAnnotation {
1001 /// No binding annotation given: this means that the final binding mode
1002 /// will depend on whether we have skipped through a `&` reference
1003 /// when matching. For example, the `x` in `Some(x)` will have binding
1004 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
1005 /// ultimately be inferred to be by-reference.
1007 /// Note that implicit reference skipping is not implemented yet (#42640).
1010 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
1013 /// Annotated as `ref`, like `ref x`
1016 /// Annotated as `ref mut x`.
1020 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1026 impl fmt::Display for RangeEnd {
1027 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1028 f.write_str(match self {
1029 RangeEnd::Included => "..=",
1030 RangeEnd::Excluded => "..",
1035 #[derive(Debug, HashStable_Generic)]
1036 pub enum PatKind<'hir> {
1037 /// Represents a wildcard pattern (i.e., `_`).
1040 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
1041 /// The `HirId` is the canonical ID for the variable being bound,
1042 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
1043 /// which is the pattern ID of the first `x`.
1044 Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
1046 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
1047 /// The `bool` is `true` in the presence of a `..`.
1048 Struct(QPath<'hir>, &'hir [PatField<'hir>], bool),
1050 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
1051 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
1052 /// `0 <= position <= subpats.len()`
1053 TupleStruct(QPath<'hir>, &'hir [Pat<'hir>], Option<usize>),
1055 /// An or-pattern `A | B | C`.
1056 /// Invariant: `pats.len() >= 2`.
1057 Or(&'hir [Pat<'hir>]),
1059 /// A path pattern for a unit struct/variant or a (maybe-associated) constant.
1062 /// A tuple pattern (e.g., `(a, b)`).
1063 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
1064 /// `0 <= position <= subpats.len()`
1065 Tuple(&'hir [Pat<'hir>], Option<usize>),
1067 /// A `box` pattern.
1068 Box(&'hir Pat<'hir>),
1070 /// A reference pattern (e.g., `&mut (a, b)`).
1071 Ref(&'hir Pat<'hir>, Mutability),
1074 Lit(&'hir Expr<'hir>),
1076 /// A range pattern (e.g., `1..=2` or `1..2`).
1077 Range(Option<&'hir Expr<'hir>>, Option<&'hir Expr<'hir>>, RangeEnd),
1079 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
1081 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
1082 /// If `slice` exists, then `after` can be non-empty.
1084 /// The representation for e.g., `[a, b, .., c, d]` is:
1086 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
1088 Slice(&'hir [Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [Pat<'hir>]),
1091 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1092 pub enum BinOpKind {
1093 /// The `+` operator (addition).
1095 /// The `-` operator (subtraction).
1097 /// The `*` operator (multiplication).
1099 /// The `/` operator (division).
1101 /// The `%` operator (modulus).
1103 /// The `&&` operator (logical and).
1105 /// The `||` operator (logical or).
1107 /// The `^` operator (bitwise xor).
1109 /// The `&` operator (bitwise and).
1111 /// The `|` operator (bitwise or).
1113 /// The `<<` operator (shift left).
1115 /// The `>>` operator (shift right).
1117 /// The `==` operator (equality).
1119 /// The `<` operator (less than).
1121 /// The `<=` operator (less than or equal to).
1123 /// The `!=` operator (not equal to).
1125 /// The `>=` operator (greater than or equal to).
1127 /// The `>` operator (greater than).
1132 pub fn as_str(self) -> &'static str {
1134 BinOpKind::Add => "+",
1135 BinOpKind::Sub => "-",
1136 BinOpKind::Mul => "*",
1137 BinOpKind::Div => "/",
1138 BinOpKind::Rem => "%",
1139 BinOpKind::And => "&&",
1140 BinOpKind::Or => "||",
1141 BinOpKind::BitXor => "^",
1142 BinOpKind::BitAnd => "&",
1143 BinOpKind::BitOr => "|",
1144 BinOpKind::Shl => "<<",
1145 BinOpKind::Shr => ">>",
1146 BinOpKind::Eq => "==",
1147 BinOpKind::Lt => "<",
1148 BinOpKind::Le => "<=",
1149 BinOpKind::Ne => "!=",
1150 BinOpKind::Ge => ">=",
1151 BinOpKind::Gt => ">",
1155 pub fn is_lazy(self) -> bool {
1156 matches!(self, BinOpKind::And | BinOpKind::Or)
1159 pub fn is_shift(self) -> bool {
1160 matches!(self, BinOpKind::Shl | BinOpKind::Shr)
1163 pub fn is_comparison(self) -> bool {
1170 | BinOpKind::Ge => true,
1182 | BinOpKind::Shr => false,
1186 /// Returns `true` if the binary operator takes its arguments by value.
1187 pub fn is_by_value(self) -> bool {
1188 !self.is_comparison()
1192 impl Into<ast::BinOpKind> for BinOpKind {
1193 fn into(self) -> ast::BinOpKind {
1195 BinOpKind::Add => ast::BinOpKind::Add,
1196 BinOpKind::Sub => ast::BinOpKind::Sub,
1197 BinOpKind::Mul => ast::BinOpKind::Mul,
1198 BinOpKind::Div => ast::BinOpKind::Div,
1199 BinOpKind::Rem => ast::BinOpKind::Rem,
1200 BinOpKind::And => ast::BinOpKind::And,
1201 BinOpKind::Or => ast::BinOpKind::Or,
1202 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1203 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1204 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1205 BinOpKind::Shl => ast::BinOpKind::Shl,
1206 BinOpKind::Shr => ast::BinOpKind::Shr,
1207 BinOpKind::Eq => ast::BinOpKind::Eq,
1208 BinOpKind::Lt => ast::BinOpKind::Lt,
1209 BinOpKind::Le => ast::BinOpKind::Le,
1210 BinOpKind::Ne => ast::BinOpKind::Ne,
1211 BinOpKind::Ge => ast::BinOpKind::Ge,
1212 BinOpKind::Gt => ast::BinOpKind::Gt,
1217 pub type BinOp = Spanned<BinOpKind>;
1219 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1221 /// The `*` operator (dereferencing).
1223 /// The `!` operator (logical negation).
1225 /// The `-` operator (negation).
1230 pub fn as_str(self) -> &'static str {
1238 /// Returns `true` if the unary operator takes its argument by value.
1239 pub fn is_by_value(self) -> bool {
1240 matches!(self, Self::Neg | Self::Not)
1245 #[derive(Debug, HashStable_Generic)]
1246 pub struct Stmt<'hir> {
1248 pub kind: StmtKind<'hir>,
1252 /// The contents of a statement.
1253 #[derive(Debug, HashStable_Generic)]
1254 pub enum StmtKind<'hir> {
1255 /// A local (`let`) binding.
1256 Local(&'hir Local<'hir>),
1258 /// An item binding.
1261 /// An expression without a trailing semi-colon (must have unit type).
1262 Expr(&'hir Expr<'hir>),
1264 /// An expression with a trailing semi-colon (may have any type).
1265 Semi(&'hir Expr<'hir>),
1268 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1269 #[derive(Debug, HashStable_Generic)]
1270 pub struct Local<'hir> {
1271 pub pat: &'hir Pat<'hir>,
1272 /// Type annotation, if any (otherwise the type will be inferred).
1273 pub ty: Option<&'hir Ty<'hir>>,
1274 /// Initializer expression to set the value, if any.
1275 pub init: Option<&'hir Expr<'hir>>,
1278 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1279 /// desugaring. Otherwise will be `Normal`.
1280 pub source: LocalSource,
1283 /// Represents a single arm of a `match` expression, e.g.
1284 /// `<pat> (if <guard>) => <body>`.
1285 #[derive(Debug, HashStable_Generic)]
1286 pub struct Arm<'hir> {
1287 #[stable_hasher(ignore)]
1290 /// If this pattern and the optional guard matches, then `body` is evaluated.
1291 pub pat: &'hir Pat<'hir>,
1292 /// Optional guard clause.
1293 pub guard: Option<Guard<'hir>>,
1294 /// The expression the arm evaluates to if this arm matches.
1295 pub body: &'hir Expr<'hir>,
1298 /// Represents a `let <pat>[: <ty>] = <expr>` expression (not a Local), occurring in an `if-let` or
1299 /// `let-else`, evaluating to a boolean. Typically the pattern is refutable.
1301 /// In an if-let, imagine it as `if (let <pat> = <expr>) { ... }`; in a let-else, it is part of the
1302 /// desugaring to if-let. Only let-else supports the type annotation at present.
1303 #[derive(Debug, HashStable_Generic)]
1304 pub struct Let<'hir> {
1307 pub pat: &'hir Pat<'hir>,
1308 pub ty: Option<&'hir Ty<'hir>>,
1309 pub init: &'hir Expr<'hir>,
1312 #[derive(Debug, HashStable_Generic)]
1313 pub enum Guard<'hir> {
1314 If(&'hir Expr<'hir>),
1315 // FIXME use hir::Let for this.
1316 IfLet(&'hir Pat<'hir>, &'hir Expr<'hir>),
1319 #[derive(Debug, HashStable_Generic)]
1320 pub struct ExprField<'hir> {
1321 #[stable_hasher(ignore)]
1324 pub expr: &'hir Expr<'hir>,
1326 pub is_shorthand: bool,
1329 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1330 pub enum BlockCheckMode {
1332 UnsafeBlock(UnsafeSource),
1335 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1336 pub enum UnsafeSource {
1341 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
1346 /// The body of a function, closure, or constant value. In the case of
1347 /// a function, the body contains not only the function body itself
1348 /// (which is an expression), but also the argument patterns, since
1349 /// those are something that the caller doesn't really care about.
1354 /// fn foo((x, y): (u32, u32)) -> u32 {
1359 /// Here, the `Body` associated with `foo()` would contain:
1361 /// - an `params` array containing the `(x, y)` pattern
1362 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1363 /// - `generator_kind` would be `None`
1365 /// All bodies have an **owner**, which can be accessed via the HIR
1366 /// map using `body_owner_def_id()`.
1367 #[derive(Debug, HashStable_Generic)]
1368 pub struct Body<'hir> {
1369 pub params: &'hir [Param<'hir>],
1370 pub value: Expr<'hir>,
1371 pub generator_kind: Option<GeneratorKind>,
1374 impl<'hir> Body<'hir> {
1375 pub fn id(&self) -> BodyId {
1376 BodyId { hir_id: self.value.hir_id }
1379 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1384 /// The type of source expression that caused this generator to be created.
1397 pub enum GeneratorKind {
1398 /// An explicit `async` block or the body of an async function.
1399 Async(AsyncGeneratorKind),
1401 /// A generator literal created via a `yield` inside a closure.
1405 impl fmt::Display for GeneratorKind {
1406 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1408 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1409 GeneratorKind::Gen => f.write_str("generator"),
1414 impl GeneratorKind {
1415 pub fn descr(&self) -> &'static str {
1417 GeneratorKind::Async(ask) => ask.descr(),
1418 GeneratorKind::Gen => "generator",
1423 /// In the case of a generator created as part of an async construct,
1424 /// which kind of async construct caused it to be created?
1426 /// This helps error messages but is also used to drive coercions in
1427 /// type-checking (see #60424).
1440 pub enum AsyncGeneratorKind {
1441 /// An explicit `async` block written by the user.
1444 /// An explicit `async` block written by the user.
1447 /// The `async` block generated as the body of an async function.
1451 impl fmt::Display for AsyncGeneratorKind {
1452 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1453 f.write_str(match self {
1454 AsyncGeneratorKind::Block => "`async` block",
1455 AsyncGeneratorKind::Closure => "`async` closure body",
1456 AsyncGeneratorKind::Fn => "`async fn` body",
1461 impl AsyncGeneratorKind {
1462 pub fn descr(&self) -> &'static str {
1464 AsyncGeneratorKind::Block => "`async` block",
1465 AsyncGeneratorKind::Closure => "`async` closure body",
1466 AsyncGeneratorKind::Fn => "`async fn` body",
1471 #[derive(Copy, Clone, Debug)]
1472 pub enum BodyOwnerKind {
1473 /// Functions and methods.
1479 /// Constants and associated constants.
1482 /// Initializer of a `static` item.
1486 impl BodyOwnerKind {
1487 pub fn is_fn_or_closure(self) -> bool {
1489 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1490 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1495 /// The kind of an item that requires const-checking.
1496 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1497 pub enum ConstContext {
1501 /// A `static` or `static mut`.
1504 /// A `const`, associated `const`, or other const context.
1506 /// Other contexts include:
1507 /// - Array length expressions
1508 /// - Enum discriminants
1509 /// - Const generics
1511 /// For the most part, other contexts are treated just like a regular `const`, so they are
1512 /// lumped into the same category.
1517 /// A description of this const context that can appear between backticks in an error message.
1519 /// E.g. `const` or `static mut`.
1520 pub fn keyword_name(self) -> &'static str {
1522 Self::Const => "const",
1523 Self::Static(Mutability::Not) => "static",
1524 Self::Static(Mutability::Mut) => "static mut",
1525 Self::ConstFn => "const fn",
1530 /// A colloquial, trivially pluralizable description of this const context for use in error
1532 impl fmt::Display for ConstContext {
1533 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1535 Self::Const => write!(f, "constant"),
1536 Self::Static(_) => write!(f, "static"),
1537 Self::ConstFn => write!(f, "constant function"),
1543 pub type Lit = Spanned<LitKind>;
1545 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1552 pub fn hir_id(&self) -> HirId {
1554 &ArrayLen::Infer(hir_id, _) | &ArrayLen::Body(AnonConst { hir_id, body: _ }) => hir_id,
1559 /// A constant (expression) that's not an item or associated item,
1560 /// but needs its own `DefId` for type-checking, const-eval, etc.
1561 /// These are usually found nested inside types (e.g., array lengths)
1562 /// or expressions (e.g., repeat counts), and also used to define
1563 /// explicit discriminant values for enum variants.
1565 /// You can check if this anon const is a default in a const param
1566 /// `const N: usize = { ... }` with `tcx.hir().opt_const_param_default_param_hir_id(..)`
1567 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1568 pub struct AnonConst {
1575 pub struct Expr<'hir> {
1577 pub kind: ExprKind<'hir>,
1582 pub fn precedence(&self) -> ExprPrecedence {
1584 ExprKind::Box(_) => ExprPrecedence::Box,
1585 ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1586 ExprKind::Array(_) => ExprPrecedence::Array,
1587 ExprKind::Call(..) => ExprPrecedence::Call,
1588 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1589 ExprKind::Tup(_) => ExprPrecedence::Tup,
1590 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1591 ExprKind::Unary(..) => ExprPrecedence::Unary,
1592 ExprKind::Lit(_) => ExprPrecedence::Lit,
1593 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1594 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1595 ExprKind::If(..) => ExprPrecedence::If,
1596 ExprKind::Let(..) => ExprPrecedence::Let,
1597 ExprKind::Loop(..) => ExprPrecedence::Loop,
1598 ExprKind::Match(..) => ExprPrecedence::Match,
1599 ExprKind::Closure(..) => ExprPrecedence::Closure,
1600 ExprKind::Block(..) => ExprPrecedence::Block,
1601 ExprKind::Assign(..) => ExprPrecedence::Assign,
1602 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1603 ExprKind::Field(..) => ExprPrecedence::Field,
1604 ExprKind::Index(..) => ExprPrecedence::Index,
1605 ExprKind::Path(..) => ExprPrecedence::Path,
1606 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1607 ExprKind::Break(..) => ExprPrecedence::Break,
1608 ExprKind::Continue(..) => ExprPrecedence::Continue,
1609 ExprKind::Ret(..) => ExprPrecedence::Ret,
1610 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1611 ExprKind::Struct(..) => ExprPrecedence::Struct,
1612 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1613 ExprKind::Yield(..) => ExprPrecedence::Yield,
1614 ExprKind::Err => ExprPrecedence::Err,
1618 // Whether this looks like a place expr, without checking for deref
1620 // This will return `true` in some potentially surprising cases such as
1621 // `CONSTANT.field`.
1622 pub fn is_syntactic_place_expr(&self) -> bool {
1623 self.is_place_expr(|_| true)
1626 /// Whether this is a place expression.
1628 /// `allow_projections_from` should return `true` if indexing a field or index expression based
1629 /// on the given expression should be considered a place expression.
1630 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1632 ExprKind::Path(QPath::Resolved(_, ref path)) => {
1633 matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static(_), _) | Res::Err)
1636 // Type ascription inherits its place expression kind from its
1638 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1639 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1641 ExprKind::Unary(UnOp::Deref, _) => true,
1643 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1644 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1647 // Lang item paths cannot currently be local variables or statics.
1648 ExprKind::Path(QPath::LangItem(..)) => false,
1650 // Partially qualified paths in expressions can only legally
1651 // refer to associated items which are always rvalues.
1652 ExprKind::Path(QPath::TypeRelative(..))
1653 | ExprKind::Call(..)
1654 | ExprKind::MethodCall(..)
1655 | ExprKind::Struct(..)
1658 | ExprKind::Match(..)
1659 | ExprKind::Closure(..)
1660 | ExprKind::Block(..)
1661 | ExprKind::Repeat(..)
1662 | ExprKind::Array(..)
1663 | ExprKind::Break(..)
1664 | ExprKind::Continue(..)
1667 | ExprKind::Loop(..)
1668 | ExprKind::Assign(..)
1669 | ExprKind::InlineAsm(..)
1670 | ExprKind::AssignOp(..)
1672 | ExprKind::ConstBlock(..)
1673 | ExprKind::Unary(..)
1675 | ExprKind::AddrOf(..)
1676 | ExprKind::Binary(..)
1677 | ExprKind::Yield(..)
1678 | ExprKind::Cast(..)
1679 | ExprKind::DropTemps(..)
1680 | ExprKind::Err => false,
1684 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1685 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1686 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1687 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1688 /// beyond remembering to call this function before doing analysis on it.
1689 pub fn peel_drop_temps(&self) -> &Self {
1690 let mut expr = self;
1691 while let ExprKind::DropTemps(inner) = &expr.kind {
1697 pub fn peel_blocks(&self) -> &Self {
1698 let mut expr = self;
1699 while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind {
1705 pub fn can_have_side_effects(&self) -> bool {
1706 match self.peel_drop_temps().kind {
1707 ExprKind::Path(_) | ExprKind::Lit(_) => false,
1708 ExprKind::Type(base, _)
1709 | ExprKind::Unary(_, base)
1710 | ExprKind::Field(base, _)
1711 | ExprKind::Index(base, _)
1712 | ExprKind::AddrOf(.., base)
1713 | ExprKind::Cast(base, _) => {
1714 // This isn't exactly true for `Index` and all `Unary`, but we are using this
1715 // method exclusively for diagnostics and there's a *cultural* pressure against
1716 // them being used only for its side-effects.
1717 base.can_have_side_effects()
1719 ExprKind::Struct(_, fields, init) => fields
1721 .map(|field| field.expr)
1722 .chain(init.into_iter())
1723 .all(|e| e.can_have_side_effects()),
1725 ExprKind::Array(args)
1726 | ExprKind::Tup(args)
1730 ExprKind::Path(QPath::Resolved(
1732 Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. },
1737 ) => args.iter().all(|arg| arg.can_have_side_effects()),
1739 | ExprKind::Match(..)
1740 | ExprKind::MethodCall(..)
1741 | ExprKind::Call(..)
1742 | ExprKind::Closure(..)
1743 | ExprKind::Block(..)
1744 | ExprKind::Repeat(..)
1745 | ExprKind::Break(..)
1746 | ExprKind::Continue(..)
1749 | ExprKind::Loop(..)
1750 | ExprKind::Assign(..)
1751 | ExprKind::InlineAsm(..)
1752 | ExprKind::AssignOp(..)
1753 | ExprKind::ConstBlock(..)
1755 | ExprKind::Binary(..)
1756 | ExprKind::Yield(..)
1757 | ExprKind::DropTemps(..)
1758 | ExprKind::Err => true,
1763 /// Checks if the specified expression is a built-in range literal.
1764 /// (See: `LoweringContext::lower_expr()`).
1765 pub fn is_range_literal(expr: &Expr<'_>) -> bool {
1767 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1768 ExprKind::Struct(ref qpath, _, _) => matches!(
1773 | LangItem::RangeFrom
1774 | LangItem::RangeFull
1775 | LangItem::RangeToInclusive,
1780 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1781 ExprKind::Call(ref func, _) => {
1782 matches!(func.kind, ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, ..)))
1789 #[derive(Debug, HashStable_Generic)]
1790 pub enum ExprKind<'hir> {
1791 /// A `box x` expression.
1792 Box(&'hir Expr<'hir>),
1793 /// Allow anonymous constants from an inline `const` block
1794 ConstBlock(AnonConst),
1795 /// An array (e.g., `[a, b, c, d]`).
1796 Array(&'hir [Expr<'hir>]),
1797 /// A function call.
1799 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1800 /// and the second field is the list of arguments.
1801 /// This also represents calling the constructor of
1802 /// tuple-like ADTs such as tuple structs and enum variants.
1803 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1804 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1806 /// The `PathSegment` represents the method name and its generic arguments
1807 /// (within the angle brackets).
1808 /// The first element of the `&[Expr]` is the expression that evaluates
1809 /// to the object on which the method is being called on (the receiver),
1810 /// and the remaining elements are the rest of the arguments.
1811 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1812 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d], span)`.
1813 /// The final `Span` represents the span of the function and arguments
1814 /// (e.g. `foo::<Bar, Baz>(a, b, c, d)` in `x.foo::<Bar, Baz>(a, b, c, d)`
1816 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1817 /// the `hir_id` of the `MethodCall` node itself.
1819 /// [`type_dependent_def_id`]: ../ty/struct.TypeckResults.html#method.type_dependent_def_id
1820 MethodCall(&'hir PathSegment<'hir>, &'hir [Expr<'hir>], Span),
1821 /// A tuple (e.g., `(a, b, c, d)`).
1822 Tup(&'hir [Expr<'hir>]),
1823 /// A binary operation (e.g., `a + b`, `a * b`).
1824 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1825 /// A unary operation (e.g., `!x`, `*x`).
1826 Unary(UnOp, &'hir Expr<'hir>),
1827 /// A literal (e.g., `1`, `"foo"`).
1829 /// A cast (e.g., `foo as f64`).
1830 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1831 /// A type reference (e.g., `Foo`).
1832 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1833 /// Wraps the expression in a terminating scope.
1834 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1836 /// This construct only exists to tweak the drop order in HIR lowering.
1837 /// An example of that is the desugaring of `for` loops.
1838 DropTemps(&'hir Expr<'hir>),
1839 /// A `let $pat = $expr` expression.
1841 /// These are not `Local` and only occur as expressions.
1842 /// The `let Some(x) = foo()` in `if let Some(x) = foo()` is an example of `Let(..)`.
1843 Let(&'hir Let<'hir>),
1844 /// An `if` block, with an optional else block.
1846 /// I.e., `if <expr> { <expr> } else { <expr> }`.
1847 If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
1848 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1850 /// I.e., `'label: loop { <block> }`.
1852 /// The `Span` is the loop header (`for x in y`/`while let pat = expr`).
1853 Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span),
1854 /// A `match` block, with a source that indicates whether or not it is
1855 /// the result of a desugaring, and if so, which kind.
1856 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1857 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1859 /// The `Span` is the argument block `|...|`.
1861 /// This may also be a generator literal or an `async block` as indicated by the
1862 /// `Option<Movability>`.
1863 Closure(CaptureBy, &'hir FnDecl<'hir>, BodyId, Span, Option<Movability>),
1864 /// A block (e.g., `'label: { ... }`).
1865 Block(&'hir Block<'hir>, Option<Label>),
1867 /// An assignment (e.g., `a = foo()`).
1868 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1869 /// An assignment with an operator.
1872 AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1873 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1874 Field(&'hir Expr<'hir>, Ident),
1875 /// An indexing operation (`foo[2]`).
1876 Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1878 /// Path to a definition, possibly containing lifetime or type parameters.
1881 /// A referencing operation (i.e., `&a` or `&mut a`).
1882 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1883 /// A `break`, with an optional label to break.
1884 Break(Destination, Option<&'hir Expr<'hir>>),
1885 /// A `continue`, with an optional label.
1886 Continue(Destination),
1887 /// A `return`, with an optional value to be returned.
1888 Ret(Option<&'hir Expr<'hir>>),
1890 /// Inline assembly (from `asm!`), with its outputs and inputs.
1891 InlineAsm(&'hir InlineAsm<'hir>),
1893 /// A struct or struct-like variant literal expression.
1895 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1896 /// where `base` is the `Option<Expr>`.
1897 Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], Option<&'hir Expr<'hir>>),
1899 /// An array literal constructed from one repeated element.
1901 /// E.g., `[1; 5]`. The first expression is the element
1902 /// to be repeated; the second is the number of times to repeat it.
1903 Repeat(&'hir Expr<'hir>, ArrayLen),
1905 /// A suspension point for generators (i.e., `yield <expr>`).
1906 Yield(&'hir Expr<'hir>, YieldSource),
1908 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1912 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1914 /// To resolve the path to a `DefId`, call [`qpath_res`].
1916 /// [`qpath_res`]: ../rustc_middle/ty/struct.TypeckResults.html#method.qpath_res
1917 #[derive(Debug, HashStable_Generic)]
1918 pub enum QPath<'hir> {
1919 /// Path to a definition, optionally "fully-qualified" with a `Self`
1920 /// type, if the path points to an associated item in a trait.
1922 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1923 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1924 /// even though they both have the same two-segment `Clone::clone` `Path`.
1925 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
1927 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1928 /// Will be resolved by type-checking to an associated item.
1930 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1931 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1932 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1933 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
1935 /// Reference to a `#[lang = "foo"]` item. `HirId` of the inner expr.
1936 LangItem(LangItem, Span, Option<HirId>),
1939 impl<'hir> QPath<'hir> {
1940 /// Returns the span of this `QPath`.
1941 pub fn span(&self) -> Span {
1943 QPath::Resolved(_, path) => path.span,
1944 QPath::TypeRelative(qself, ps) => qself.span.to(ps.ident.span),
1945 QPath::LangItem(_, span, _) => span,
1949 /// Returns the span of the qself of this `QPath`. For example, `()` in
1950 /// `<() as Trait>::method`.
1951 pub fn qself_span(&self) -> Span {
1953 QPath::Resolved(_, path) => path.span,
1954 QPath::TypeRelative(qself, _) => qself.span,
1955 QPath::LangItem(_, span, _) => span,
1959 /// Returns the span of the last segment of this `QPath`. For example, `method` in
1960 /// `<() as Trait>::method`.
1961 pub fn last_segment_span(&self) -> Span {
1963 QPath::Resolved(_, path) => path.segments.last().unwrap().ident.span,
1964 QPath::TypeRelative(_, segment) => segment.ident.span,
1965 QPath::LangItem(_, span, _) => span,
1970 /// Hints at the original code for a let statement.
1971 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1972 pub enum LocalSource {
1973 /// A `match _ { .. }`.
1975 /// When lowering async functions, we create locals within the `async move` so that
1976 /// all parameters are dropped after the future is polled.
1978 /// ```ignore (pseudo-Rust)
1979 /// async fn foo(<pattern> @ x: Type) {
1981 /// let <pattern> = x;
1986 /// A desugared `<expr>.await`.
1988 /// A desugared `expr = expr`, where the LHS is a tuple, struct or array.
1989 /// The span is that of the `=` sign.
1990 AssignDesugar(Span),
1993 /// Hints at the original code for a `match _ { .. }`.
1994 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
1995 #[derive(HashStable_Generic)]
1996 pub enum MatchSource {
1997 /// A `match _ { .. }`.
1999 /// A desugared `for _ in _ { .. }` loop.
2001 /// A desugared `?` operator.
2003 /// A desugared `<expr>.await`.
2009 pub const fn name(self) -> &'static str {
2013 ForLoopDesugar => "for",
2015 AwaitDesugar => ".await",
2020 /// The loop type that yielded an `ExprKind::Loop`.
2021 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2022 pub enum LoopSource {
2023 /// A `loop { .. }` loop.
2025 /// A `while _ { .. }` loop.
2027 /// A `for _ in _ { .. }` loop.
2032 pub fn name(self) -> &'static str {
2034 LoopSource::Loop => "loop",
2035 LoopSource::While => "while",
2036 LoopSource::ForLoop => "for",
2041 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2042 pub enum LoopIdError {
2044 UnlabeledCfInWhileCondition,
2048 impl fmt::Display for LoopIdError {
2049 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2050 f.write_str(match self {
2051 LoopIdError::OutsideLoopScope => "not inside loop scope",
2052 LoopIdError::UnlabeledCfInWhileCondition => {
2053 "unlabeled control flow (break or continue) in while condition"
2055 LoopIdError::UnresolvedLabel => "label not found",
2060 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2061 pub struct Destination {
2062 // This is `Some(_)` iff there is an explicit user-specified `label
2063 pub label: Option<Label>,
2065 // These errors are caught and then reported during the diagnostics pass in
2066 // librustc_passes/loops.rs
2067 pub target_id: Result<HirId, LoopIdError>,
2070 /// The yield kind that caused an `ExprKind::Yield`.
2071 #[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
2072 pub enum YieldSource {
2073 /// An `<expr>.await`.
2074 Await { expr: Option<HirId> },
2075 /// A plain `yield`.
2080 pub fn is_await(&self) -> bool {
2082 YieldSource::Await { .. } => true,
2083 YieldSource::Yield => false,
2088 impl fmt::Display for YieldSource {
2089 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2090 f.write_str(match self {
2091 YieldSource::Await { .. } => "`await`",
2092 YieldSource::Yield => "`yield`",
2097 impl From<GeneratorKind> for YieldSource {
2098 fn from(kind: GeneratorKind) -> Self {
2100 // Guess based on the kind of the current generator.
2101 GeneratorKind::Gen => Self::Yield,
2102 GeneratorKind::Async(_) => Self::Await { expr: None },
2107 // N.B., if you change this, you'll probably want to change the corresponding
2108 // type structure in middle/ty.rs as well.
2109 #[derive(Debug, HashStable_Generic)]
2110 pub struct MutTy<'hir> {
2111 pub ty: &'hir Ty<'hir>,
2112 pub mutbl: Mutability,
2115 /// Represents a function's signature in a trait declaration,
2116 /// trait implementation, or a free function.
2117 #[derive(Debug, HashStable_Generic)]
2118 pub struct FnSig<'hir> {
2119 pub header: FnHeader,
2120 pub decl: &'hir FnDecl<'hir>,
2124 // The bodies for items are stored "out of line", in a separate
2125 // hashmap in the `Crate`. Here we just record the hir-id of the item
2126 // so it can fetched later.
2127 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
2128 pub struct TraitItemId {
2129 pub def_id: LocalDefId,
2134 pub fn hir_id(&self) -> HirId {
2135 // Items are always HIR owners.
2136 HirId::make_owner(self.def_id)
2140 /// Represents an item declaration within a trait declaration,
2141 /// possibly including a default implementation. A trait item is
2142 /// either required (meaning it doesn't have an implementation, just a
2143 /// signature) or provided (meaning it has a default implementation).
2144 #[derive(Debug, HashStable_Generic)]
2145 pub struct TraitItem<'hir> {
2147 pub def_id: LocalDefId,
2148 pub generics: &'hir Generics<'hir>,
2149 pub kind: TraitItemKind<'hir>,
2153 impl TraitItem<'_> {
2155 pub fn hir_id(&self) -> HirId {
2156 // Items are always HIR owners.
2157 HirId::make_owner(self.def_id)
2160 pub fn trait_item_id(&self) -> TraitItemId {
2161 TraitItemId { def_id: self.def_id }
2165 /// Represents a trait method's body (or just argument names).
2166 #[derive(Encodable, Debug, HashStable_Generic)]
2167 pub enum TraitFn<'hir> {
2168 /// No default body in the trait, just a signature.
2169 Required(&'hir [Ident]),
2171 /// Both signature and body are provided in the trait.
2175 /// Represents a trait method or associated constant or type
2176 #[derive(Debug, HashStable_Generic)]
2177 pub enum TraitItemKind<'hir> {
2178 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
2179 Const(&'hir Ty<'hir>, Option<BodyId>),
2180 /// An associated function with an optional body.
2181 Fn(FnSig<'hir>, TraitFn<'hir>),
2182 /// An associated type with (possibly empty) bounds and optional concrete
2184 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
2187 // The bodies for items are stored "out of line", in a separate
2188 // hashmap in the `Crate`. Here we just record the hir-id of the item
2189 // so it can fetched later.
2190 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
2191 pub struct ImplItemId {
2192 pub def_id: LocalDefId,
2197 pub fn hir_id(&self) -> HirId {
2198 // Items are always HIR owners.
2199 HirId::make_owner(self.def_id)
2203 /// Represents anything within an `impl` block.
2204 #[derive(Debug, HashStable_Generic)]
2205 pub struct ImplItem<'hir> {
2207 pub def_id: LocalDefId,
2208 pub generics: &'hir Generics<'hir>,
2209 pub kind: ImplItemKind<'hir>,
2216 pub fn hir_id(&self) -> HirId {
2217 // Items are always HIR owners.
2218 HirId::make_owner(self.def_id)
2221 pub fn impl_item_id(&self) -> ImplItemId {
2222 ImplItemId { def_id: self.def_id }
2226 /// Represents various kinds of content within an `impl`.
2227 #[derive(Debug, HashStable_Generic)]
2228 pub enum ImplItemKind<'hir> {
2229 /// An associated constant of the given type, set to the constant result
2230 /// of the expression.
2231 Const(&'hir Ty<'hir>, BodyId),
2232 /// An associated function implementation with the given signature and body.
2233 Fn(FnSig<'hir>, BodyId),
2234 /// An associated type.
2235 TyAlias(&'hir Ty<'hir>),
2238 // The name of the associated type for `Fn` return types.
2239 pub const FN_OUTPUT_NAME: Symbol = sym::Output;
2241 /// Bind a type to an associated type (i.e., `A = Foo`).
2243 /// Bindings like `A: Debug` are represented as a special type `A =
2244 /// $::Debug` that is understood by the astconv code.
2246 /// FIXME(alexreg): why have a separate type for the binding case,
2247 /// wouldn't it be better to make the `ty` field an enum like the
2251 /// enum TypeBindingKind {
2256 #[derive(Debug, HashStable_Generic)]
2257 pub struct TypeBinding<'hir> {
2260 pub gen_args: &'hir GenericArgs<'hir>,
2261 pub kind: TypeBindingKind<'hir>,
2265 #[derive(Debug, HashStable_Generic)]
2266 pub enum Term<'hir> {
2271 impl<'hir> From<&'hir Ty<'hir>> for Term<'hir> {
2272 fn from(ty: &'hir Ty<'hir>) -> Self {
2277 impl<'hir> From<AnonConst> for Term<'hir> {
2278 fn from(c: AnonConst) -> Self {
2283 // Represents the two kinds of type bindings.
2284 #[derive(Debug, HashStable_Generic)]
2285 pub enum TypeBindingKind<'hir> {
2286 /// E.g., `Foo<Bar: Send>`.
2287 Constraint { bounds: &'hir [GenericBound<'hir>] },
2288 /// E.g., `Foo<Bar = ()>`, `Foo<Bar = ()>`
2289 Equality { term: Term<'hir> },
2292 impl TypeBinding<'_> {
2293 pub fn ty(&self) -> &Ty<'_> {
2295 TypeBindingKind::Equality { term: Term::Ty(ref ty) } => ty,
2296 _ => panic!("expected equality type binding for parenthesized generic args"),
2299 pub fn opt_const(&self) -> Option<&'_ AnonConst> {
2301 TypeBindingKind::Equality { term: Term::Const(ref c) } => Some(c),
2308 pub struct Ty<'hir> {
2310 pub kind: TyKind<'hir>,
2314 impl<'hir> Ty<'hir> {
2315 /// Returns `true` if `param_def_id` matches the `bounded_ty` of this predicate.
2316 pub fn as_generic_param(&self) -> Option<(DefId, Ident)> {
2317 let TyKind::Path(QPath::Resolved(None, path)) = self.kind else {
2320 let [segment] = &path.segments else {
2324 Res::Def(DefKind::TyParam, def_id)
2325 | Res::SelfTy { trait_: Some(def_id), alias_to: None } => Some((def_id, segment.ident)),
2331 /// Not represented directly in the AST; referred to by name through a `ty_path`.
2332 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
2333 #[derive(HashStable_Generic)]
2344 /// All of the primitive types
2345 pub const ALL: [Self; 17] = [
2346 // any changes here should also be reflected in `PrimTy::from_name`
2347 Self::Int(IntTy::I8),
2348 Self::Int(IntTy::I16),
2349 Self::Int(IntTy::I32),
2350 Self::Int(IntTy::I64),
2351 Self::Int(IntTy::I128),
2352 Self::Int(IntTy::Isize),
2353 Self::Uint(UintTy::U8),
2354 Self::Uint(UintTy::U16),
2355 Self::Uint(UintTy::U32),
2356 Self::Uint(UintTy::U64),
2357 Self::Uint(UintTy::U128),
2358 Self::Uint(UintTy::Usize),
2359 Self::Float(FloatTy::F32),
2360 Self::Float(FloatTy::F64),
2366 /// Like [`PrimTy::name`], but returns a &str instead of a symbol.
2369 pub fn name_str(self) -> &'static str {
2371 PrimTy::Int(i) => i.name_str(),
2372 PrimTy::Uint(u) => u.name_str(),
2373 PrimTy::Float(f) => f.name_str(),
2374 PrimTy::Str => "str",
2375 PrimTy::Bool => "bool",
2376 PrimTy::Char => "char",
2380 pub fn name(self) -> Symbol {
2382 PrimTy::Int(i) => i.name(),
2383 PrimTy::Uint(u) => u.name(),
2384 PrimTy::Float(f) => f.name(),
2385 PrimTy::Str => sym::str,
2386 PrimTy::Bool => sym::bool,
2387 PrimTy::Char => sym::char,
2391 /// Returns the matching `PrimTy` for a `Symbol` such as "str" or "i32".
2392 /// Returns `None` if no matching type is found.
2393 pub fn from_name(name: Symbol) -> Option<Self> {
2394 let ty = match name {
2395 // any changes here should also be reflected in `PrimTy::ALL`
2396 sym::i8 => Self::Int(IntTy::I8),
2397 sym::i16 => Self::Int(IntTy::I16),
2398 sym::i32 => Self::Int(IntTy::I32),
2399 sym::i64 => Self::Int(IntTy::I64),
2400 sym::i128 => Self::Int(IntTy::I128),
2401 sym::isize => Self::Int(IntTy::Isize),
2402 sym::u8 => Self::Uint(UintTy::U8),
2403 sym::u16 => Self::Uint(UintTy::U16),
2404 sym::u32 => Self::Uint(UintTy::U32),
2405 sym::u64 => Self::Uint(UintTy::U64),
2406 sym::u128 => Self::Uint(UintTy::U128),
2407 sym::usize => Self::Uint(UintTy::Usize),
2408 sym::f32 => Self::Float(FloatTy::F32),
2409 sym::f64 => Self::Float(FloatTy::F64),
2410 sym::bool => Self::Bool,
2411 sym::char => Self::Char,
2412 sym::str => Self::Str,
2419 #[derive(Debug, HashStable_Generic)]
2420 pub struct BareFnTy<'hir> {
2421 pub unsafety: Unsafety,
2423 pub generic_params: &'hir [GenericParam<'hir>],
2424 pub decl: &'hir FnDecl<'hir>,
2425 pub param_names: &'hir [Ident],
2428 #[derive(Debug, HashStable_Generic)]
2429 pub struct OpaqueTy<'hir> {
2430 pub generics: &'hir Generics<'hir>,
2431 pub bounds: GenericBounds<'hir>,
2432 pub origin: OpaqueTyOrigin,
2435 /// From whence the opaque type came.
2436 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2437 pub enum OpaqueTyOrigin {
2439 FnReturn(LocalDefId),
2441 AsyncFn(LocalDefId),
2442 /// type aliases: `type Foo = impl Trait;`
2446 /// The various kinds of types recognized by the compiler.
2447 #[derive(Debug, HashStable_Generic)]
2448 pub enum TyKind<'hir> {
2449 /// A variable length slice (i.e., `[T]`).
2450 Slice(&'hir Ty<'hir>),
2451 /// A fixed length array (i.e., `[T; n]`).
2452 Array(&'hir Ty<'hir>, ArrayLen),
2453 /// A raw pointer (i.e., `*const T` or `*mut T`).
2455 /// A reference (i.e., `&'a T` or `&'a mut T`).
2456 Rptr(Lifetime, MutTy<'hir>),
2457 /// A bare function (e.g., `fn(usize) -> bool`).
2458 BareFn(&'hir BareFnTy<'hir>),
2459 /// The never type (`!`).
2461 /// A tuple (`(A, B, C, D, ...)`).
2462 Tup(&'hir [Ty<'hir>]),
2463 /// A path to a type definition (`module::module::...::Type`), or an
2464 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2466 /// Type parameters may be stored in each `PathSegment`.
2468 /// An opaque type definition itself. This is only used for `impl Trait`.
2470 /// The generic argument list contains the lifetimes (and in the future
2471 /// possibly parameters) that are actually bound on the `impl Trait`.
2472 OpaqueDef(ItemId, &'hir [GenericArg<'hir>]),
2473 /// A trait object type `Bound1 + Bound2 + Bound3`
2474 /// where `Bound` is a trait or a lifetime.
2475 TraitObject(&'hir [PolyTraitRef<'hir>], Lifetime, TraitObjectSyntax),
2478 /// `TyKind::Infer` means the type should be inferred instead of it having been
2479 /// specified. This can appear anywhere in a type.
2481 /// Placeholder for a type that has failed to be defined.
2485 #[derive(Debug, HashStable_Generic)]
2486 pub enum InlineAsmOperand<'hir> {
2488 reg: InlineAsmRegOrRegClass,
2492 reg: InlineAsmRegOrRegClass,
2494 expr: Option<Expr<'hir>>,
2497 reg: InlineAsmRegOrRegClass,
2502 reg: InlineAsmRegOrRegClass,
2504 in_expr: Expr<'hir>,
2505 out_expr: Option<Expr<'hir>>,
2508 anon_const: AnonConst,
2511 anon_const: AnonConst,
2519 impl<'hir> InlineAsmOperand<'hir> {
2520 pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
2522 Self::In { reg, .. }
2523 | Self::Out { reg, .. }
2524 | Self::InOut { reg, .. }
2525 | Self::SplitInOut { reg, .. } => Some(reg),
2526 Self::Const { .. } | Self::SymFn { .. } | Self::SymStatic { .. } => None,
2530 pub fn is_clobber(&self) -> bool {
2533 InlineAsmOperand::Out { reg: InlineAsmRegOrRegClass::Reg(_), late: _, expr: None }
2538 #[derive(Debug, HashStable_Generic)]
2539 pub struct InlineAsm<'hir> {
2540 pub template: &'hir [InlineAsmTemplatePiece],
2541 pub template_strs: &'hir [(Symbol, Option<Symbol>, Span)],
2542 pub operands: &'hir [(InlineAsmOperand<'hir>, Span)],
2543 pub options: InlineAsmOptions,
2544 pub line_spans: &'hir [Span],
2547 /// Represents a parameter in a function header.
2548 #[derive(Debug, HashStable_Generic)]
2549 pub struct Param<'hir> {
2551 pub pat: &'hir Pat<'hir>,
2556 /// Represents the header (not the body) of a function declaration.
2557 #[derive(Debug, HashStable_Generic)]
2558 pub struct FnDecl<'hir> {
2559 /// The types of the function's parameters.
2561 /// Additional argument data is stored in the function's [body](Body::params).
2562 pub inputs: &'hir [Ty<'hir>],
2563 pub output: FnRetTy<'hir>,
2564 pub c_variadic: bool,
2565 /// Does the function have an implicit self?
2566 pub implicit_self: ImplicitSelfKind,
2569 /// Represents what type of implicit self a function has, if any.
2570 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2571 pub enum ImplicitSelfKind {
2572 /// Represents a `fn x(self);`.
2574 /// Represents a `fn x(mut self);`.
2576 /// Represents a `fn x(&self);`.
2578 /// Represents a `fn x(&mut self);`.
2580 /// Represents when a function does not have a self argument or
2581 /// when a function has a `self: X` argument.
2585 impl ImplicitSelfKind {
2586 /// Does this represent an implicit self?
2587 pub fn has_implicit_self(&self) -> bool {
2588 !matches!(*self, ImplicitSelfKind::None)
2592 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable, Debug)]
2593 #[derive(HashStable_Generic)]
2599 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable, HashStable_Generic)]
2600 pub enum Defaultness {
2601 Default { has_value: bool },
2606 pub fn has_value(&self) -> bool {
2608 Defaultness::Default { has_value } => has_value,
2609 Defaultness::Final => true,
2613 pub fn is_final(&self) -> bool {
2614 *self == Defaultness::Final
2617 pub fn is_default(&self) -> bool {
2618 matches!(*self, Defaultness::Default { .. })
2622 #[derive(Debug, HashStable_Generic)]
2623 pub enum FnRetTy<'hir> {
2624 /// Return type is not specified.
2626 /// Functions default to `()` and
2627 /// closures default to inference. Span points to where return
2628 /// type would be inserted.
2629 DefaultReturn(Span),
2630 /// Everything else.
2631 Return(&'hir Ty<'hir>),
2636 pub fn span(&self) -> Span {
2638 Self::DefaultReturn(span) => span,
2639 Self::Return(ref ty) => ty.span,
2644 #[derive(Encodable, Debug, HashStable_Generic)]
2645 pub struct Mod<'hir> {
2646 pub spans: ModSpans,
2647 pub item_ids: &'hir [ItemId],
2650 #[derive(Copy, Clone, Debug, HashStable_Generic, Encodable)]
2651 pub struct ModSpans {
2652 /// A span from the first token past `{` to the last token until `}`.
2653 /// For `mod foo;`, the inner span ranges from the first token
2654 /// to the last token in the external file.
2655 pub inner_span: Span,
2656 pub inject_use_span: Span,
2659 #[derive(Debug, HashStable_Generic)]
2660 pub struct EnumDef<'hir> {
2661 pub variants: &'hir [Variant<'hir>],
2664 #[derive(Debug, HashStable_Generic)]
2665 pub struct Variant<'hir> {
2666 /// Name of the variant.
2668 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2670 /// Fields and constructor id of the variant.
2671 pub data: VariantData<'hir>,
2672 /// Explicit discriminant (e.g., `Foo = 1`).
2673 pub disr_expr: Option<AnonConst>,
2678 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2680 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2681 /// Also produced for each element of a list `use`, e.g.
2682 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2685 /// Glob import, e.g., `use foo::*`.
2688 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2689 /// an additional `use foo::{}` for performing checks such as
2690 /// unstable feature gating. May be removed in the future.
2694 /// References to traits in impls.
2696 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2697 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2698 /// trait being referred to but just a unique `HirId` that serves as a key
2699 /// within the resolution map.
2700 #[derive(Clone, Debug, HashStable_Generic)]
2701 pub struct TraitRef<'hir> {
2702 pub path: &'hir Path<'hir>,
2703 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2704 #[stable_hasher(ignore)]
2705 pub hir_ref_id: HirId,
2709 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2710 pub fn trait_def_id(&self) -> Option<DefId> {
2711 match self.path.res {
2712 Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
2714 _ => unreachable!(),
2719 #[derive(Clone, Debug, HashStable_Generic)]
2720 pub struct PolyTraitRef<'hir> {
2721 /// The `'a` in `for<'a> Foo<&'a T>`.
2722 pub bound_generic_params: &'hir [GenericParam<'hir>],
2724 /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
2725 pub trait_ref: TraitRef<'hir>,
2730 #[derive(Debug, HashStable_Generic)]
2731 pub struct FieldDef<'hir> {
2736 pub ty: &'hir Ty<'hir>,
2740 // Still necessary in couple of places
2741 pub fn is_positional(&self) -> bool {
2742 let first = self.ident.as_str().as_bytes()[0];
2743 (b'0'..=b'9').contains(&first)
2747 /// Fields and constructor IDs of enum variants and structs.
2748 #[derive(Debug, HashStable_Generic)]
2749 pub enum VariantData<'hir> {
2750 /// A struct variant.
2752 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2753 Struct(&'hir [FieldDef<'hir>], /* recovered */ bool),
2754 /// A tuple variant.
2756 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2757 Tuple(&'hir [FieldDef<'hir>], HirId),
2760 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2764 impl<'hir> VariantData<'hir> {
2765 /// Return the fields of this variant.
2766 pub fn fields(&self) -> &'hir [FieldDef<'hir>] {
2768 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2773 /// Return the `HirId` of this variant's constructor, if it has one.
2774 pub fn ctor_hir_id(&self) -> Option<HirId> {
2776 VariantData::Struct(_, _) => None,
2777 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2782 // The bodies for items are stored "out of line", in a separate
2783 // hashmap in the `Crate`. Here we just record the hir-id of the item
2784 // so it can fetched later.
2785 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, Hash, HashStable_Generic)]
2787 pub def_id: LocalDefId,
2792 pub fn hir_id(&self) -> HirId {
2793 // Items are always HIR owners.
2794 HirId::make_owner(self.def_id)
2800 /// The name might be a dummy name in case of anonymous items
2801 #[derive(Debug, HashStable_Generic)]
2802 pub struct Item<'hir> {
2804 pub def_id: LocalDefId,
2805 pub kind: ItemKind<'hir>,
2812 pub fn hir_id(&self) -> HirId {
2813 // Items are always HIR owners.
2814 HirId::make_owner(self.def_id)
2817 pub fn item_id(&self) -> ItemId {
2818 ItemId { def_id: self.def_id }
2822 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2823 #[derive(Encodable, Decodable, HashStable_Generic)]
2830 pub fn prefix_str(&self) -> &'static str {
2832 Self::Unsafe => "unsafe ",
2838 impl fmt::Display for Unsafety {
2839 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2840 f.write_str(match *self {
2841 Self::Unsafe => "unsafe",
2842 Self::Normal => "normal",
2847 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2848 #[derive(Encodable, Decodable, HashStable_Generic)]
2849 pub enum Constness {
2854 impl fmt::Display for Constness {
2855 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2856 f.write_str(match *self {
2857 Self::Const => "const",
2858 Self::NotConst => "non-const",
2863 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2864 pub struct FnHeader {
2865 pub unsafety: Unsafety,
2866 pub constness: Constness,
2867 pub asyncness: IsAsync,
2872 pub fn is_async(&self) -> bool {
2873 matches!(&self.asyncness, IsAsync::Async)
2876 pub fn is_const(&self) -> bool {
2877 matches!(&self.constness, Constness::Const)
2880 pub fn is_unsafe(&self) -> bool {
2881 matches!(&self.unsafety, Unsafety::Unsafe)
2885 #[derive(Debug, HashStable_Generic)]
2886 pub enum ItemKind<'hir> {
2887 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2889 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2890 ExternCrate(Option<Symbol>),
2892 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2896 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2897 Use(&'hir Path<'hir>, UseKind),
2899 /// A `static` item.
2900 Static(&'hir Ty<'hir>, Mutability, BodyId),
2902 Const(&'hir Ty<'hir>, BodyId),
2903 /// A function declaration.
2904 Fn(FnSig<'hir>, &'hir Generics<'hir>, BodyId),
2905 /// A MBE macro definition (`macro_rules!` or `macro`).
2906 Macro(ast::MacroDef, MacroKind),
2909 /// An external module, e.g. `extern { .. }`.
2910 ForeignMod { abi: Abi, items: &'hir [ForeignItemRef] },
2911 /// Module-level inline assembly (from `global_asm!`).
2912 GlobalAsm(&'hir InlineAsm<'hir>),
2913 /// A type alias, e.g., `type Foo = Bar<u8>`.
2914 TyAlias(&'hir Ty<'hir>, &'hir Generics<'hir>),
2915 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2916 OpaqueTy(OpaqueTy<'hir>),
2917 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2918 Enum(EnumDef<'hir>, &'hir Generics<'hir>),
2919 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2920 Struct(VariantData<'hir>, &'hir Generics<'hir>),
2921 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2922 Union(VariantData<'hir>, &'hir Generics<'hir>),
2923 /// A trait definition.
2924 Trait(IsAuto, Unsafety, &'hir Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
2926 TraitAlias(&'hir Generics<'hir>, GenericBounds<'hir>),
2928 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2929 Impl(&'hir Impl<'hir>),
2932 #[derive(Debug, HashStable_Generic)]
2933 pub struct Impl<'hir> {
2934 pub unsafety: Unsafety,
2935 pub polarity: ImplPolarity,
2936 pub defaultness: Defaultness,
2937 // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata
2938 // decoding as `Span`s cannot be decoded when a `Session` is not available.
2939 pub defaultness_span: Option<Span>,
2940 pub constness: Constness,
2941 pub generics: &'hir Generics<'hir>,
2943 /// The trait being implemented, if any.
2944 pub of_trait: Option<TraitRef<'hir>>,
2946 pub self_ty: &'hir Ty<'hir>,
2947 pub items: &'hir [ImplItemRef],
2951 pub fn generics(&self) -> Option<&Generics<'_>> {
2953 ItemKind::Fn(_, ref generics, _)
2954 | ItemKind::TyAlias(_, ref generics)
2955 | ItemKind::OpaqueTy(OpaqueTy {
2956 ref generics, origin: OpaqueTyOrigin::TyAlias, ..
2958 | ItemKind::Enum(_, ref generics)
2959 | ItemKind::Struct(_, ref generics)
2960 | ItemKind::Union(_, ref generics)
2961 | ItemKind::Trait(_, _, ref generics, _, _)
2962 | ItemKind::Impl(Impl { ref generics, .. }) => generics,
2967 pub fn descr(&self) -> &'static str {
2969 ItemKind::ExternCrate(..) => "extern crate",
2970 ItemKind::Use(..) => "`use` import",
2971 ItemKind::Static(..) => "static item",
2972 ItemKind::Const(..) => "constant item",
2973 ItemKind::Fn(..) => "function",
2974 ItemKind::Macro(..) => "macro",
2975 ItemKind::Mod(..) => "module",
2976 ItemKind::ForeignMod { .. } => "extern block",
2977 ItemKind::GlobalAsm(..) => "global asm item",
2978 ItemKind::TyAlias(..) => "type alias",
2979 ItemKind::OpaqueTy(..) => "opaque type",
2980 ItemKind::Enum(..) => "enum",
2981 ItemKind::Struct(..) => "struct",
2982 ItemKind::Union(..) => "union",
2983 ItemKind::Trait(..) => "trait",
2984 ItemKind::TraitAlias(..) => "trait alias",
2985 ItemKind::Impl(..) => "implementation",
2990 /// A reference from an trait to one of its associated items. This
2991 /// contains the item's id, naturally, but also the item's name and
2992 /// some other high-level details (like whether it is an associated
2993 /// type or method, and whether it is public). This allows other
2994 /// passes to find the impl they want without loading the ID (which
2995 /// means fewer edges in the incremental compilation graph).
2996 #[derive(Encodable, Debug, HashStable_Generic)]
2997 pub struct TraitItemRef {
2998 pub id: TraitItemId,
3000 pub kind: AssocItemKind,
3002 pub defaultness: Defaultness,
3005 /// A reference from an impl to one of its associated items. This
3006 /// contains the item's ID, naturally, but also the item's name and
3007 /// some other high-level details (like whether it is an associated
3008 /// type or method, and whether it is public). This allows other
3009 /// passes to find the impl they want without loading the ID (which
3010 /// means fewer edges in the incremental compilation graph).
3011 #[derive(Debug, HashStable_Generic)]
3012 pub struct ImplItemRef {
3015 pub kind: AssocItemKind,
3017 pub defaultness: Defaultness,
3018 /// When we are in a trait impl, link to the trait-item's id.
3019 pub trait_item_def_id: Option<DefId>,
3022 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
3023 pub enum AssocItemKind {
3025 Fn { has_self: bool },
3029 // The bodies for items are stored "out of line", in a separate
3030 // hashmap in the `Crate`. Here we just record the hir-id of the item
3031 // so it can fetched later.
3032 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
3033 pub struct ForeignItemId {
3034 pub def_id: LocalDefId,
3037 impl ForeignItemId {
3039 pub fn hir_id(&self) -> HirId {
3040 // Items are always HIR owners.
3041 HirId::make_owner(self.def_id)
3045 /// A reference from a foreign block to one of its items. This
3046 /// contains the item's ID, naturally, but also the item's name and
3047 /// some other high-level details (like whether it is an associated
3048 /// type or method, and whether it is public). This allows other
3049 /// passes to find the impl they want without loading the ID (which
3050 /// means fewer edges in the incremental compilation graph).
3051 #[derive(Debug, HashStable_Generic)]
3052 pub struct ForeignItemRef {
3053 pub id: ForeignItemId,
3058 #[derive(Debug, HashStable_Generic)]
3059 pub struct ForeignItem<'hir> {
3061 pub kind: ForeignItemKind<'hir>,
3062 pub def_id: LocalDefId,
3067 impl ForeignItem<'_> {
3069 pub fn hir_id(&self) -> HirId {
3070 // Items are always HIR owners.
3071 HirId::make_owner(self.def_id)
3074 pub fn foreign_item_id(&self) -> ForeignItemId {
3075 ForeignItemId { def_id: self.def_id }
3079 /// An item within an `extern` block.
3080 #[derive(Debug, HashStable_Generic)]
3081 pub enum ForeignItemKind<'hir> {
3082 /// A foreign function.
3083 Fn(&'hir FnDecl<'hir>, &'hir [Ident], &'hir Generics<'hir>),
3084 /// A foreign static item (`static ext: u8`).
3085 Static(&'hir Ty<'hir>, Mutability),
3090 /// A variable captured by a closure.
3091 #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)]
3093 // First span where it is accessed (there can be multiple).
3097 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
3098 // has length > 0 if the trait is found through an chain of imports, starting with the
3099 // import/use statement in the scope where the trait is used.
3100 #[derive(Encodable, Decodable, Clone, Debug, HashStable_Generic)]
3101 pub struct TraitCandidate {
3103 pub import_ids: SmallVec<[LocalDefId; 1]>,
3106 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3107 pub enum OwnerNode<'hir> {
3108 Item(&'hir Item<'hir>),
3109 ForeignItem(&'hir ForeignItem<'hir>),
3110 TraitItem(&'hir TraitItem<'hir>),
3111 ImplItem(&'hir ImplItem<'hir>),
3112 Crate(&'hir Mod<'hir>),
3115 impl<'hir> OwnerNode<'hir> {
3116 pub fn ident(&self) -> Option<Ident> {
3118 OwnerNode::Item(Item { ident, .. })
3119 | OwnerNode::ForeignItem(ForeignItem { ident, .. })
3120 | OwnerNode::ImplItem(ImplItem { ident, .. })
3121 | OwnerNode::TraitItem(TraitItem { ident, .. }) => Some(*ident),
3122 OwnerNode::Crate(..) => None,
3126 pub fn span(&self) -> Span {
3128 OwnerNode::Item(Item { span, .. })
3129 | OwnerNode::ForeignItem(ForeignItem { span, .. })
3130 | OwnerNode::ImplItem(ImplItem { span, .. })
3131 | OwnerNode::TraitItem(TraitItem { span, .. }) => *span,
3132 OwnerNode::Crate(Mod { spans: ModSpans { inner_span, .. }, .. }) => *inner_span,
3136 pub fn fn_decl(&self) -> Option<&FnDecl<'hir>> {
3138 OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3139 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3140 | OwnerNode::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3141 OwnerNode::ForeignItem(ForeignItem {
3142 kind: ForeignItemKind::Fn(fn_decl, _, _),
3144 }) => Some(fn_decl),
3149 pub fn body_id(&self) -> Option<BodyId> {
3151 OwnerNode::TraitItem(TraitItem {
3152 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3155 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3156 | OwnerNode::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3161 pub fn generics(&self) -> Option<&'hir Generics<'hir>> {
3163 OwnerNode::TraitItem(TraitItem { generics, .. })
3164 | OwnerNode::ImplItem(ImplItem { generics, .. }) => Some(generics),
3165 OwnerNode::Item(item) => item.kind.generics(),
3170 pub fn def_id(self) -> LocalDefId {
3172 OwnerNode::Item(Item { def_id, .. })
3173 | OwnerNode::TraitItem(TraitItem { def_id, .. })
3174 | OwnerNode::ImplItem(ImplItem { def_id, .. })
3175 | OwnerNode::ForeignItem(ForeignItem { def_id, .. }) => *def_id,
3176 OwnerNode::Crate(..) => crate::CRATE_HIR_ID.owner,
3180 pub fn expect_item(self) -> &'hir Item<'hir> {
3182 OwnerNode::Item(n) => n,
3187 pub fn expect_foreign_item(self) -> &'hir ForeignItem<'hir> {
3189 OwnerNode::ForeignItem(n) => n,
3194 pub fn expect_impl_item(self) -> &'hir ImplItem<'hir> {
3196 OwnerNode::ImplItem(n) => n,
3201 pub fn expect_trait_item(self) -> &'hir TraitItem<'hir> {
3203 OwnerNode::TraitItem(n) => n,
3209 impl<'hir> Into<OwnerNode<'hir>> for &'hir Item<'hir> {
3210 fn into(self) -> OwnerNode<'hir> {
3211 OwnerNode::Item(self)
3215 impl<'hir> Into<OwnerNode<'hir>> for &'hir ForeignItem<'hir> {
3216 fn into(self) -> OwnerNode<'hir> {
3217 OwnerNode::ForeignItem(self)
3221 impl<'hir> Into<OwnerNode<'hir>> for &'hir ImplItem<'hir> {
3222 fn into(self) -> OwnerNode<'hir> {
3223 OwnerNode::ImplItem(self)
3227 impl<'hir> Into<OwnerNode<'hir>> for &'hir TraitItem<'hir> {
3228 fn into(self) -> OwnerNode<'hir> {
3229 OwnerNode::TraitItem(self)
3233 impl<'hir> Into<Node<'hir>> for OwnerNode<'hir> {
3234 fn into(self) -> Node<'hir> {
3236 OwnerNode::Item(n) => Node::Item(n),
3237 OwnerNode::ForeignItem(n) => Node::ForeignItem(n),
3238 OwnerNode::ImplItem(n) => Node::ImplItem(n),
3239 OwnerNode::TraitItem(n) => Node::TraitItem(n),
3240 OwnerNode::Crate(n) => Node::Crate(n),
3245 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3246 pub enum Node<'hir> {
3247 Param(&'hir Param<'hir>),
3248 Item(&'hir Item<'hir>),
3249 ForeignItem(&'hir ForeignItem<'hir>),
3250 TraitItem(&'hir TraitItem<'hir>),
3251 ImplItem(&'hir ImplItem<'hir>),
3252 Variant(&'hir Variant<'hir>),
3253 Field(&'hir FieldDef<'hir>),
3254 AnonConst(&'hir AnonConst),
3255 Expr(&'hir Expr<'hir>),
3256 Stmt(&'hir Stmt<'hir>),
3257 PathSegment(&'hir PathSegment<'hir>),
3259 TraitRef(&'hir TraitRef<'hir>),
3260 Binding(&'hir Pat<'hir>),
3261 Pat(&'hir Pat<'hir>),
3262 Arm(&'hir Arm<'hir>),
3263 Block(&'hir Block<'hir>),
3264 Local(&'hir Local<'hir>),
3266 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
3267 /// with synthesized constructors.
3268 Ctor(&'hir VariantData<'hir>),
3270 Lifetime(&'hir Lifetime),
3271 GenericParam(&'hir GenericParam<'hir>),
3273 Crate(&'hir Mod<'hir>),
3275 Infer(&'hir InferArg),
3278 impl<'hir> Node<'hir> {
3279 /// Get the identifier of this `Node`, if applicable.
3283 /// Calling `.ident()` on a [`Node::Ctor`] will return `None`
3284 /// because `Ctor`s do not have identifiers themselves.
3285 /// Instead, call `.ident()` on the parent struct/variant, like so:
3287 /// ```ignore (illustrative)
3290 /// .and_then(|ctor_id| tcx.hir().find(tcx.hir().get_parent_node(ctor_id)))
3291 /// .and_then(|parent| parent.ident())
3293 pub fn ident(&self) -> Option<Ident> {
3295 Node::TraitItem(TraitItem { ident, .. })
3296 | Node::ImplItem(ImplItem { ident, .. })
3297 | Node::ForeignItem(ForeignItem { ident, .. })
3298 | Node::Field(FieldDef { ident, .. })
3299 | Node::Variant(Variant { ident, .. })
3300 | Node::Item(Item { ident, .. })
3301 | Node::PathSegment(PathSegment { ident, .. }) => Some(*ident),
3302 Node::Lifetime(lt) => Some(lt.name.ident()),
3303 Node::GenericParam(p) => Some(p.name.ident()),
3305 | Node::AnonConst(..)
3316 | Node::TraitRef(..)
3317 | Node::Infer(..) => None,
3321 pub fn fn_decl(&self) -> Option<&'hir FnDecl<'hir>> {
3323 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3324 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3325 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3326 Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
3333 pub fn fn_sig(&self) -> Option<&'hir FnSig<'hir>> {
3335 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3336 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3337 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig),
3342 pub fn body_id(&self) -> Option<BodyId> {
3344 Node::TraitItem(TraitItem {
3345 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3348 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3349 | Node::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3354 pub fn generics(&self) -> Option<&'hir Generics<'hir>> {
3356 Node::TraitItem(TraitItem { generics, .. })
3357 | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
3358 Node::Item(item) => item.kind.generics(),
3363 pub fn as_owner(self) -> Option<OwnerNode<'hir>> {
3365 Node::Item(i) => Some(OwnerNode::Item(i)),
3366 Node::ForeignItem(i) => Some(OwnerNode::ForeignItem(i)),
3367 Node::TraitItem(i) => Some(OwnerNode::TraitItem(i)),
3368 Node::ImplItem(i) => Some(OwnerNode::ImplItem(i)),
3369 Node::Crate(i) => Some(OwnerNode::Crate(i)),
3374 pub fn fn_kind(self) -> Option<FnKind<'hir>> {
3376 Node::Item(i) => match i.kind {
3377 ItemKind::Fn(ref sig, ref generics, _) => {
3378 Some(FnKind::ItemFn(i.ident, generics, sig.header))
3382 Node::TraitItem(ti) => match ti.kind {
3383 TraitItemKind::Fn(ref sig, TraitFn::Provided(_)) => {
3384 Some(FnKind::Method(ti.ident, sig))
3388 Node::ImplItem(ii) => match ii.kind {
3389 ImplItemKind::Fn(ref sig, _) => Some(FnKind::Method(ii.ident, sig)),
3392 Node::Expr(e) => match e.kind {
3393 ExprKind::Closure(..) => Some(FnKind::Closure),
3400 /// Get the fields for the tuple-constructor,
3401 /// if this node is a tuple constructor, otherwise None
3402 pub fn tuple_fields(&self) -> Option<&'hir [FieldDef<'hir>]> {
3403 if let Node::Ctor(&VariantData::Tuple(fields, _)) = self { Some(fields) } else { None }
3407 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3408 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
3410 rustc_data_structures::static_assert_size!(super::Block<'static>, 48);
3411 rustc_data_structures::static_assert_size!(super::Expr<'static>, 56);
3412 rustc_data_structures::static_assert_size!(super::Pat<'static>, 88);
3413 rustc_data_structures::static_assert_size!(super::QPath<'static>, 24);
3414 rustc_data_structures::static_assert_size!(super::Ty<'static>, 72);
3415 rustc_data_structures::static_assert_size!(super::GenericBound<'_>, 48);
3416 rustc_data_structures::static_assert_size!(super::Generics<'static>, 56);
3417 rustc_data_structures::static_assert_size!(super::Impl<'static>, 80);
3419 rustc_data_structures::static_assert_size!(super::Item<'static>, 80);
3420 rustc_data_structures::static_assert_size!(super::TraitItem<'static>, 88);
3421 rustc_data_structures::static_assert_size!(super::ImplItem<'static>, 80);
3422 rustc_data_structures::static_assert_size!(super::ForeignItem<'static>, 72);