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::{SourceMap, 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> {
499 pub bounds: GenericBounds<'hir>,
501 pub pure_wrt_drop: bool,
502 pub kind: GenericParamKind<'hir>,
505 impl<'hir> GenericParam<'hir> {
506 pub fn bounds_span_for_suggestions(&self) -> Option<Span> {
509 .fold(None, |span: Option<Span>, bound| {
510 // We include bounds that come from a `#[derive(_)]` but point at the user's code,
511 // as we use this method to get a span appropriate for suggestions.
512 if !bound.span().can_be_used_for_suggestions() {
515 let span = span.map(|s| s.to(bound.span())).unwrap_or_else(|| bound.span());
519 .map(|sp| sp.shrink_to_hi())
522 /// Returns the span of `:` after a generic parameter.
541 pub fn colon_span_for_suggestions(&self, source_map: &SourceMap) -> Option<Span> {
543 .span_extend_while(self.span.shrink_to_hi(), |c| c.is_whitespace() || c == ':')
546 let snippet = source_map.span_to_snippet(sp).ok()?;
547 let offset = snippet.find(':')?;
550 .with_lo(BytePos(sp.lo().0 + offset as u32))
551 .with_hi(BytePos(sp.lo().0 + (offset + ':'.len_utf8()) as u32));
558 pub struct GenericParamCount {
559 pub lifetimes: usize,
565 /// Represents lifetimes and type parameters attached to a declaration
566 /// of a function, enum, trait, etc.
567 #[derive(Debug, HashStable_Generic)]
568 pub struct Generics<'hir> {
569 pub params: &'hir [GenericParam<'hir>],
570 pub where_clause: WhereClause<'hir>,
574 impl<'hir> Generics<'hir> {
575 pub const fn empty() -> Generics<'hir> {
578 where_clause: WhereClause { predicates: &[], span: DUMMY_SP },
583 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'_>> {
584 for param in self.params {
585 if name == param.name.ident().name {
592 pub fn spans(&self) -> MultiSpan {
593 if self.params.is_empty() {
596 self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
601 /// A where-clause in a definition.
602 #[derive(Debug, HashStable_Generic)]
603 pub struct WhereClause<'hir> {
604 pub predicates: &'hir [WherePredicate<'hir>],
605 // Only valid if predicates aren't empty.
609 impl WhereClause<'_> {
610 pub fn span(&self) -> Option<Span> {
611 if self.predicates.is_empty() { None } else { Some(self.span) }
614 /// The `WhereClause` under normal circumstances points at either the predicates or the empty
615 /// space where the `where` clause should be. Only of use for diagnostic suggestions.
616 pub fn span_for_predicates_or_empty_place(&self) -> Span {
620 /// `Span` where further predicates would be suggested, accounting for trailing commas, like
621 /// in `fn foo<T>(t: T) where T: Foo,` so we don't suggest two trailing commas.
622 pub fn tail_span_for_suggestion(&self) -> Span {
623 let end = self.span_for_predicates_or_empty_place().shrink_to_hi();
624 self.predicates.last().map_or(end, |p| p.span()).shrink_to_hi().to(end)
628 /// A single predicate in a where-clause.
629 #[derive(Debug, HashStable_Generic)]
630 pub enum WherePredicate<'hir> {
631 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
632 BoundPredicate(WhereBoundPredicate<'hir>),
633 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
634 RegionPredicate(WhereRegionPredicate<'hir>),
635 /// An equality predicate (unsupported).
636 EqPredicate(WhereEqPredicate<'hir>),
639 impl<'hir> WherePredicate<'hir> {
640 pub fn span(&self) -> Span {
642 WherePredicate::BoundPredicate(p) => p.span,
643 WherePredicate::RegionPredicate(p) => p.span,
644 WherePredicate::EqPredicate(p) => p.span,
649 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
650 #[derive(Debug, HashStable_Generic)]
651 pub struct WhereBoundPredicate<'hir> {
653 /// Any generics from a `for` binding.
654 pub bound_generic_params: &'hir [GenericParam<'hir>],
655 /// The type being bounded.
656 pub bounded_ty: &'hir Ty<'hir>,
657 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
658 pub bounds: GenericBounds<'hir>,
661 impl<'hir> WhereBoundPredicate<'hir> {
662 /// Returns `true` if `param_def_id` matches the `bounded_ty` of this predicate.
663 pub fn is_param_bound(&self, param_def_id: DefId) -> bool {
664 let TyKind::Path(QPath::Resolved(None, path)) = self.bounded_ty.kind else {
668 Res::Def(DefKind::TyParam, def_id)
669 | Res::SelfTy { trait_: Some(def_id), alias_to: None } => def_id == param_def_id,
675 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
676 #[derive(Debug, HashStable_Generic)]
677 pub struct WhereRegionPredicate<'hir> {
679 pub lifetime: Lifetime,
680 pub bounds: GenericBounds<'hir>,
683 /// An equality predicate (e.g., `T = int`); currently unsupported.
684 #[derive(Debug, HashStable_Generic)]
685 pub struct WhereEqPredicate<'hir> {
688 pub lhs_ty: &'hir Ty<'hir>,
689 pub rhs_ty: &'hir Ty<'hir>,
692 /// HIR node coupled with its parent's id in the same HIR owner.
694 /// The parent is trash when the node is a HIR owner.
695 #[derive(Clone, Debug)]
696 pub struct ParentedNode<'tcx> {
697 pub parent: ItemLocalId,
698 pub node: Node<'tcx>,
701 /// Attributes owned by a HIR owner.
703 pub struct AttributeMap<'tcx> {
704 pub map: SortedMap<ItemLocalId, &'tcx [Attribute]>,
705 pub hash: Fingerprint,
708 impl<'tcx> AttributeMap<'tcx> {
709 pub const EMPTY: &'static AttributeMap<'static> =
710 &AttributeMap { map: SortedMap::new(), hash: Fingerprint::ZERO };
713 pub fn get(&self, id: ItemLocalId) -> &'tcx [Attribute] {
714 self.map.get(&id).copied().unwrap_or(&[])
718 /// Map of all HIR nodes inside the current owner.
719 /// These nodes are mapped by `ItemLocalId` alongside the index of their parent node.
720 /// The HIR tree, including bodies, is pre-hashed.
722 pub struct OwnerNodes<'tcx> {
723 /// Pre-computed hash of the full HIR.
724 pub hash_including_bodies: Fingerprint,
725 /// Pre-computed hash of the item signature, sithout recursing into the body.
726 pub hash_without_bodies: Fingerprint,
727 /// Full HIR for the current owner.
728 // The zeroth node's parent should never be accessed: the owner's parent is computed by the
729 // hir_owner_parent query. It is set to `ItemLocalId::INVALID` to force an ICE if accidentally
731 pub nodes: IndexVec<ItemLocalId, Option<ParentedNode<'tcx>>>,
732 /// Content of local bodies.
733 pub bodies: SortedMap<ItemLocalId, &'tcx Body<'tcx>>,
734 /// Non-owning definitions contained in this owner.
735 pub local_id_to_def_id: SortedMap<ItemLocalId, LocalDefId>,
738 impl<'tcx> OwnerNodes<'tcx> {
739 pub fn node(&self) -> OwnerNode<'tcx> {
740 use rustc_index::vec::Idx;
741 let node = self.nodes[ItemLocalId::new(0)].as_ref().unwrap().node;
742 let node = node.as_owner().unwrap(); // Indexing must ensure it is an OwnerNode.
747 /// Full information resulting from lowering an AST node.
748 #[derive(Debug, HashStable_Generic)]
749 pub struct OwnerInfo<'hir> {
750 /// Contents of the HIR.
751 pub nodes: OwnerNodes<'hir>,
752 /// Map from each nested owner to its parent's local id.
753 pub parenting: FxHashMap<LocalDefId, ItemLocalId>,
754 /// Collected attributes of the HIR nodes.
755 pub attrs: AttributeMap<'hir>,
756 /// Map indicating what traits are in scope for places where this
757 /// is relevant; generated by resolve.
758 pub trait_map: FxHashMap<ItemLocalId, Box<[TraitCandidate]>>,
761 impl<'tcx> OwnerInfo<'tcx> {
763 pub fn node(&self) -> OwnerNode<'tcx> {
768 #[derive(Copy, Clone, Debug, HashStable_Generic)]
769 pub enum MaybeOwner<T> {
772 /// Used as a placeholder for unused LocalDefId.
776 impl<T> MaybeOwner<T> {
777 pub fn as_owner(self) -> Option<T> {
779 MaybeOwner::Owner(i) => Some(i),
780 MaybeOwner::NonOwner(_) | MaybeOwner::Phantom => None,
784 pub fn map<U>(self, f: impl FnOnce(T) -> U) -> MaybeOwner<U> {
786 MaybeOwner::Owner(i) => MaybeOwner::Owner(f(i)),
787 MaybeOwner::NonOwner(hir_id) => MaybeOwner::NonOwner(hir_id),
788 MaybeOwner::Phantom => MaybeOwner::Phantom,
792 pub fn unwrap(self) -> T {
794 MaybeOwner::Owner(i) => i,
795 MaybeOwner::NonOwner(_) | MaybeOwner::Phantom => panic!("Not a HIR owner"),
800 /// The top-level data structure that stores the entire contents of
801 /// the crate currently being compiled.
803 /// For more details, see the [rustc dev guide].
805 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
807 pub struct Crate<'hir> {
808 pub owners: IndexVec<LocalDefId, MaybeOwner<&'hir OwnerInfo<'hir>>>,
809 pub hir_hash: Fingerprint,
812 /// A block of statements `{ .. }`, which may have a label (in this case the
813 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
814 /// the `rules` being anything but `DefaultBlock`.
815 #[derive(Debug, HashStable_Generic)]
816 pub struct Block<'hir> {
817 /// Statements in a block.
818 pub stmts: &'hir [Stmt<'hir>],
819 /// An expression at the end of the block
820 /// without a semicolon, if any.
821 pub expr: Option<&'hir Expr<'hir>>,
822 #[stable_hasher(ignore)]
824 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
825 pub rules: BlockCheckMode,
827 /// If true, then there may exist `break 'a` values that aim to
828 /// break out of this block early.
829 /// Used by `'label: {}` blocks and by `try {}` blocks.
830 pub targeted_by_break: bool,
833 #[derive(Debug, HashStable_Generic)]
834 pub struct Pat<'hir> {
835 #[stable_hasher(ignore)]
837 pub kind: PatKind<'hir>,
839 // Whether to use default binding modes.
840 // At present, this is false only for destructuring assignment.
841 pub default_binding_modes: bool,
844 impl<'hir> Pat<'hir> {
845 // FIXME(#19596) this is a workaround, but there should be a better way
846 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) -> bool {
853 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
854 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
855 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
856 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
857 Slice(before, slice, after) => {
858 before.iter().chain(slice).chain(after.iter()).all(|p| p.walk_short_(it))
863 /// Walk the pattern in left-to-right order,
864 /// short circuiting (with `.all(..)`) if `false` is returned.
866 /// Note that when visiting e.g. `Tuple(ps)`,
867 /// if visiting `ps[0]` returns `false`,
868 /// then `ps[1]` will not be visited.
869 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) -> bool {
870 self.walk_short_(&mut it)
873 // FIXME(#19596) this is a workaround, but there should be a better way
874 fn walk_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) {
881 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
882 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
883 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
884 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
885 Slice(before, slice, after) => {
886 before.iter().chain(slice).chain(after.iter()).for_each(|p| p.walk_(it))
891 /// Walk the pattern in left-to-right order.
893 /// If `it(pat)` returns `false`, the children are not visited.
894 pub fn walk(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) {
898 /// Walk the pattern in left-to-right order.
900 /// If you always want to recurse, prefer this method over `walk`.
901 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
909 /// A single field in a struct pattern.
911 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
912 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
913 /// except `is_shorthand` is true.
914 #[derive(Debug, HashStable_Generic)]
915 pub struct PatField<'hir> {
916 #[stable_hasher(ignore)]
918 /// The identifier for the field.
920 /// The pattern the field is destructured to.
921 pub pat: &'hir Pat<'hir>,
922 pub is_shorthand: bool,
926 /// Explicit binding annotations given in the HIR for a binding. Note
927 /// that this is not the final binding *mode* that we infer after type
929 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
930 pub enum BindingAnnotation {
931 /// No binding annotation given: this means that the final binding mode
932 /// will depend on whether we have skipped through a `&` reference
933 /// when matching. For example, the `x` in `Some(x)` will have binding
934 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
935 /// ultimately be inferred to be by-reference.
937 /// Note that implicit reference skipping is not implemented yet (#42640).
940 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
943 /// Annotated as `ref`, like `ref x`
946 /// Annotated as `ref mut x`.
950 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
956 impl fmt::Display for RangeEnd {
957 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
958 f.write_str(match self {
959 RangeEnd::Included => "..=",
960 RangeEnd::Excluded => "..",
965 #[derive(Debug, HashStable_Generic)]
966 pub enum PatKind<'hir> {
967 /// Represents a wildcard pattern (i.e., `_`).
970 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
971 /// The `HirId` is the canonical ID for the variable being bound,
972 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
973 /// which is the pattern ID of the first `x`.
974 Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
976 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
977 /// The `bool` is `true` in the presence of a `..`.
978 Struct(QPath<'hir>, &'hir [PatField<'hir>], bool),
980 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
981 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
982 /// `0 <= position <= subpats.len()`
983 TupleStruct(QPath<'hir>, &'hir [Pat<'hir>], Option<usize>),
985 /// An or-pattern `A | B | C`.
986 /// Invariant: `pats.len() >= 2`.
987 Or(&'hir [Pat<'hir>]),
989 /// A path pattern for a unit struct/variant or a (maybe-associated) constant.
992 /// A tuple pattern (e.g., `(a, b)`).
993 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
994 /// `0 <= position <= subpats.len()`
995 Tuple(&'hir [Pat<'hir>], Option<usize>),
998 Box(&'hir Pat<'hir>),
1000 /// A reference pattern (e.g., `&mut (a, b)`).
1001 Ref(&'hir Pat<'hir>, Mutability),
1004 Lit(&'hir Expr<'hir>),
1006 /// A range pattern (e.g., `1..=2` or `1..2`).
1007 Range(Option<&'hir Expr<'hir>>, Option<&'hir Expr<'hir>>, RangeEnd),
1009 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
1011 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
1012 /// If `slice` exists, then `after` can be non-empty.
1014 /// The representation for e.g., `[a, b, .., c, d]` is:
1016 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
1018 Slice(&'hir [Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [Pat<'hir>]),
1021 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1022 pub enum BinOpKind {
1023 /// The `+` operator (addition).
1025 /// The `-` operator (subtraction).
1027 /// The `*` operator (multiplication).
1029 /// The `/` operator (division).
1031 /// The `%` operator (modulus).
1033 /// The `&&` operator (logical and).
1035 /// The `||` operator (logical or).
1037 /// The `^` operator (bitwise xor).
1039 /// The `&` operator (bitwise and).
1041 /// The `|` operator (bitwise or).
1043 /// The `<<` operator (shift left).
1045 /// The `>>` operator (shift right).
1047 /// The `==` operator (equality).
1049 /// The `<` operator (less than).
1051 /// The `<=` operator (less than or equal to).
1053 /// The `!=` operator (not equal to).
1055 /// The `>=` operator (greater than or equal to).
1057 /// The `>` operator (greater than).
1062 pub fn as_str(self) -> &'static str {
1064 BinOpKind::Add => "+",
1065 BinOpKind::Sub => "-",
1066 BinOpKind::Mul => "*",
1067 BinOpKind::Div => "/",
1068 BinOpKind::Rem => "%",
1069 BinOpKind::And => "&&",
1070 BinOpKind::Or => "||",
1071 BinOpKind::BitXor => "^",
1072 BinOpKind::BitAnd => "&",
1073 BinOpKind::BitOr => "|",
1074 BinOpKind::Shl => "<<",
1075 BinOpKind::Shr => ">>",
1076 BinOpKind::Eq => "==",
1077 BinOpKind::Lt => "<",
1078 BinOpKind::Le => "<=",
1079 BinOpKind::Ne => "!=",
1080 BinOpKind::Ge => ">=",
1081 BinOpKind::Gt => ">",
1085 pub fn is_lazy(self) -> bool {
1086 matches!(self, BinOpKind::And | BinOpKind::Or)
1089 pub fn is_shift(self) -> bool {
1090 matches!(self, BinOpKind::Shl | BinOpKind::Shr)
1093 pub fn is_comparison(self) -> bool {
1100 | BinOpKind::Ge => true,
1112 | BinOpKind::Shr => false,
1116 /// Returns `true` if the binary operator takes its arguments by value.
1117 pub fn is_by_value(self) -> bool {
1118 !self.is_comparison()
1122 impl Into<ast::BinOpKind> for BinOpKind {
1123 fn into(self) -> ast::BinOpKind {
1125 BinOpKind::Add => ast::BinOpKind::Add,
1126 BinOpKind::Sub => ast::BinOpKind::Sub,
1127 BinOpKind::Mul => ast::BinOpKind::Mul,
1128 BinOpKind::Div => ast::BinOpKind::Div,
1129 BinOpKind::Rem => ast::BinOpKind::Rem,
1130 BinOpKind::And => ast::BinOpKind::And,
1131 BinOpKind::Or => ast::BinOpKind::Or,
1132 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1133 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1134 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1135 BinOpKind::Shl => ast::BinOpKind::Shl,
1136 BinOpKind::Shr => ast::BinOpKind::Shr,
1137 BinOpKind::Eq => ast::BinOpKind::Eq,
1138 BinOpKind::Lt => ast::BinOpKind::Lt,
1139 BinOpKind::Le => ast::BinOpKind::Le,
1140 BinOpKind::Ne => ast::BinOpKind::Ne,
1141 BinOpKind::Ge => ast::BinOpKind::Ge,
1142 BinOpKind::Gt => ast::BinOpKind::Gt,
1147 pub type BinOp = Spanned<BinOpKind>;
1149 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1151 /// The `*` operator (dereferencing).
1153 /// The `!` operator (logical negation).
1155 /// The `-` operator (negation).
1160 pub fn as_str(self) -> &'static str {
1168 /// Returns `true` if the unary operator takes its argument by value.
1169 pub fn is_by_value(self) -> bool {
1170 matches!(self, Self::Neg | Self::Not)
1175 #[derive(Debug, HashStable_Generic)]
1176 pub struct Stmt<'hir> {
1178 pub kind: StmtKind<'hir>,
1182 /// The contents of a statement.
1183 #[derive(Debug, HashStable_Generic)]
1184 pub enum StmtKind<'hir> {
1185 /// A local (`let`) binding.
1186 Local(&'hir Local<'hir>),
1188 /// An item binding.
1191 /// An expression without a trailing semi-colon (must have unit type).
1192 Expr(&'hir Expr<'hir>),
1194 /// An expression with a trailing semi-colon (may have any type).
1195 Semi(&'hir Expr<'hir>),
1198 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1199 #[derive(Debug, HashStable_Generic)]
1200 pub struct Local<'hir> {
1201 pub pat: &'hir Pat<'hir>,
1202 /// Type annotation, if any (otherwise the type will be inferred).
1203 pub ty: Option<&'hir Ty<'hir>>,
1204 /// Initializer expression to set the value, if any.
1205 pub init: Option<&'hir Expr<'hir>>,
1208 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1209 /// desugaring. Otherwise will be `Normal`.
1210 pub source: LocalSource,
1213 /// Represents a single arm of a `match` expression, e.g.
1214 /// `<pat> (if <guard>) => <body>`.
1215 #[derive(Debug, HashStable_Generic)]
1216 pub struct Arm<'hir> {
1217 #[stable_hasher(ignore)]
1220 /// If this pattern and the optional guard matches, then `body` is evaluated.
1221 pub pat: &'hir Pat<'hir>,
1222 /// Optional guard clause.
1223 pub guard: Option<Guard<'hir>>,
1224 /// The expression the arm evaluates to if this arm matches.
1225 pub body: &'hir Expr<'hir>,
1228 /// Represents a `let <pat>[: <ty>] = <expr>` expression (not a Local), occurring in an `if-let` or
1229 /// `let-else`, evaluating to a boolean. Typically the pattern is refutable.
1231 /// In an if-let, imagine it as `if (let <pat> = <expr>) { ... }`; in a let-else, it is part of the
1232 /// desugaring to if-let. Only let-else supports the type annotation at present.
1233 #[derive(Debug, HashStable_Generic)]
1234 pub struct Let<'hir> {
1237 pub pat: &'hir Pat<'hir>,
1238 pub ty: Option<&'hir Ty<'hir>>,
1239 pub init: &'hir Expr<'hir>,
1242 #[derive(Debug, HashStable_Generic)]
1243 pub enum Guard<'hir> {
1244 If(&'hir Expr<'hir>),
1245 // FIXME use hir::Let for this.
1246 IfLet(&'hir Pat<'hir>, &'hir Expr<'hir>),
1249 #[derive(Debug, HashStable_Generic)]
1250 pub struct ExprField<'hir> {
1251 #[stable_hasher(ignore)]
1254 pub expr: &'hir Expr<'hir>,
1256 pub is_shorthand: bool,
1259 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1260 pub enum BlockCheckMode {
1262 UnsafeBlock(UnsafeSource),
1265 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1266 pub enum UnsafeSource {
1271 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
1276 /// The body of a function, closure, or constant value. In the case of
1277 /// a function, the body contains not only the function body itself
1278 /// (which is an expression), but also the argument patterns, since
1279 /// those are something that the caller doesn't really care about.
1284 /// fn foo((x, y): (u32, u32)) -> u32 {
1289 /// Here, the `Body` associated with `foo()` would contain:
1291 /// - an `params` array containing the `(x, y)` pattern
1292 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1293 /// - `generator_kind` would be `None`
1295 /// All bodies have an **owner**, which can be accessed via the HIR
1296 /// map using `body_owner_def_id()`.
1297 #[derive(Debug, HashStable_Generic)]
1298 pub struct Body<'hir> {
1299 pub params: &'hir [Param<'hir>],
1300 pub value: Expr<'hir>,
1301 pub generator_kind: Option<GeneratorKind>,
1304 impl<'hir> Body<'hir> {
1305 pub fn id(&self) -> BodyId {
1306 BodyId { hir_id: self.value.hir_id }
1309 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1314 /// The type of source expression that caused this generator to be created.
1327 pub enum GeneratorKind {
1328 /// An explicit `async` block or the body of an async function.
1329 Async(AsyncGeneratorKind),
1331 /// A generator literal created via a `yield` inside a closure.
1335 impl fmt::Display for GeneratorKind {
1336 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1338 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1339 GeneratorKind::Gen => f.write_str("generator"),
1344 impl GeneratorKind {
1345 pub fn descr(&self) -> &'static str {
1347 GeneratorKind::Async(ask) => ask.descr(),
1348 GeneratorKind::Gen => "generator",
1353 /// In the case of a generator created as part of an async construct,
1354 /// which kind of async construct caused it to be created?
1356 /// This helps error messages but is also used to drive coercions in
1357 /// type-checking (see #60424).
1370 pub enum AsyncGeneratorKind {
1371 /// An explicit `async` block written by the user.
1374 /// An explicit `async` block written by the user.
1377 /// The `async` block generated as the body of an async function.
1381 impl fmt::Display for AsyncGeneratorKind {
1382 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1383 f.write_str(match self {
1384 AsyncGeneratorKind::Block => "`async` block",
1385 AsyncGeneratorKind::Closure => "`async` closure body",
1386 AsyncGeneratorKind::Fn => "`async fn` body",
1391 impl AsyncGeneratorKind {
1392 pub fn descr(&self) -> &'static str {
1394 AsyncGeneratorKind::Block => "`async` block",
1395 AsyncGeneratorKind::Closure => "`async` closure body",
1396 AsyncGeneratorKind::Fn => "`async fn` body",
1401 #[derive(Copy, Clone, Debug)]
1402 pub enum BodyOwnerKind {
1403 /// Functions and methods.
1409 /// Constants and associated constants.
1412 /// Initializer of a `static` item.
1416 impl BodyOwnerKind {
1417 pub fn is_fn_or_closure(self) -> bool {
1419 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1420 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1425 /// The kind of an item that requires const-checking.
1426 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1427 pub enum ConstContext {
1431 /// A `static` or `static mut`.
1434 /// A `const`, associated `const`, or other const context.
1436 /// Other contexts include:
1437 /// - Array length expressions
1438 /// - Enum discriminants
1439 /// - Const generics
1441 /// For the most part, other contexts are treated just like a regular `const`, so they are
1442 /// lumped into the same category.
1447 /// A description of this const context that can appear between backticks in an error message.
1449 /// E.g. `const` or `static mut`.
1450 pub fn keyword_name(self) -> &'static str {
1452 Self::Const => "const",
1453 Self::Static(Mutability::Not) => "static",
1454 Self::Static(Mutability::Mut) => "static mut",
1455 Self::ConstFn => "const fn",
1460 /// A colloquial, trivially pluralizable description of this const context for use in error
1462 impl fmt::Display for ConstContext {
1463 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1465 Self::Const => write!(f, "constant"),
1466 Self::Static(_) => write!(f, "static"),
1467 Self::ConstFn => write!(f, "constant function"),
1473 pub type Lit = Spanned<LitKind>;
1475 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1482 pub fn hir_id(&self) -> HirId {
1484 &ArrayLen::Infer(hir_id, _) | &ArrayLen::Body(AnonConst { hir_id, body: _ }) => hir_id,
1489 /// A constant (expression) that's not an item or associated item,
1490 /// but needs its own `DefId` for type-checking, const-eval, etc.
1491 /// These are usually found nested inside types (e.g., array lengths)
1492 /// or expressions (e.g., repeat counts), and also used to define
1493 /// explicit discriminant values for enum variants.
1495 /// You can check if this anon const is a default in a const param
1496 /// `const N: usize = { ... }` with `tcx.hir().opt_const_param_default_param_hir_id(..)`
1497 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1498 pub struct AnonConst {
1505 pub struct Expr<'hir> {
1507 pub kind: ExprKind<'hir>,
1512 pub fn precedence(&self) -> ExprPrecedence {
1514 ExprKind::Box(_) => ExprPrecedence::Box,
1515 ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1516 ExprKind::Array(_) => ExprPrecedence::Array,
1517 ExprKind::Call(..) => ExprPrecedence::Call,
1518 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1519 ExprKind::Tup(_) => ExprPrecedence::Tup,
1520 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1521 ExprKind::Unary(..) => ExprPrecedence::Unary,
1522 ExprKind::Lit(_) => ExprPrecedence::Lit,
1523 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1524 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1525 ExprKind::If(..) => ExprPrecedence::If,
1526 ExprKind::Let(..) => ExprPrecedence::Let,
1527 ExprKind::Loop(..) => ExprPrecedence::Loop,
1528 ExprKind::Match(..) => ExprPrecedence::Match,
1529 ExprKind::Closure(..) => ExprPrecedence::Closure,
1530 ExprKind::Block(..) => ExprPrecedence::Block,
1531 ExprKind::Assign(..) => ExprPrecedence::Assign,
1532 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1533 ExprKind::Field(..) => ExprPrecedence::Field,
1534 ExprKind::Index(..) => ExprPrecedence::Index,
1535 ExprKind::Path(..) => ExprPrecedence::Path,
1536 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1537 ExprKind::Break(..) => ExprPrecedence::Break,
1538 ExprKind::Continue(..) => ExprPrecedence::Continue,
1539 ExprKind::Ret(..) => ExprPrecedence::Ret,
1540 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1541 ExprKind::Struct(..) => ExprPrecedence::Struct,
1542 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1543 ExprKind::Yield(..) => ExprPrecedence::Yield,
1544 ExprKind::Err => ExprPrecedence::Err,
1548 // Whether this looks like a place expr, without checking for deref
1550 // This will return `true` in some potentially surprising cases such as
1551 // `CONSTANT.field`.
1552 pub fn is_syntactic_place_expr(&self) -> bool {
1553 self.is_place_expr(|_| true)
1556 /// Whether this is a place expression.
1558 /// `allow_projections_from` should return `true` if indexing a field or index expression based
1559 /// on the given expression should be considered a place expression.
1560 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1562 ExprKind::Path(QPath::Resolved(_, ref path)) => {
1563 matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static(_), _) | Res::Err)
1566 // Type ascription inherits its place expression kind from its
1568 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1569 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1571 ExprKind::Unary(UnOp::Deref, _) => true,
1573 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1574 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1577 // Lang item paths cannot currently be local variables or statics.
1578 ExprKind::Path(QPath::LangItem(..)) => false,
1580 // Partially qualified paths in expressions can only legally
1581 // refer to associated items which are always rvalues.
1582 ExprKind::Path(QPath::TypeRelative(..))
1583 | ExprKind::Call(..)
1584 | ExprKind::MethodCall(..)
1585 | ExprKind::Struct(..)
1588 | ExprKind::Match(..)
1589 | ExprKind::Closure(..)
1590 | ExprKind::Block(..)
1591 | ExprKind::Repeat(..)
1592 | ExprKind::Array(..)
1593 | ExprKind::Break(..)
1594 | ExprKind::Continue(..)
1597 | ExprKind::Loop(..)
1598 | ExprKind::Assign(..)
1599 | ExprKind::InlineAsm(..)
1600 | ExprKind::AssignOp(..)
1602 | ExprKind::ConstBlock(..)
1603 | ExprKind::Unary(..)
1605 | ExprKind::AddrOf(..)
1606 | ExprKind::Binary(..)
1607 | ExprKind::Yield(..)
1608 | ExprKind::Cast(..)
1609 | ExprKind::DropTemps(..)
1610 | ExprKind::Err => false,
1614 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1615 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1616 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1617 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1618 /// beyond remembering to call this function before doing analysis on it.
1619 pub fn peel_drop_temps(&self) -> &Self {
1620 let mut expr = self;
1621 while let ExprKind::DropTemps(inner) = &expr.kind {
1627 pub fn peel_blocks(&self) -> &Self {
1628 let mut expr = self;
1629 while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind {
1635 pub fn can_have_side_effects(&self) -> bool {
1636 match self.peel_drop_temps().kind {
1637 ExprKind::Path(_) | ExprKind::Lit(_) => false,
1638 ExprKind::Type(base, _)
1639 | ExprKind::Unary(_, base)
1640 | ExprKind::Field(base, _)
1641 | ExprKind::Index(base, _)
1642 | ExprKind::AddrOf(.., base)
1643 | ExprKind::Cast(base, _) => {
1644 // This isn't exactly true for `Index` and all `Unary`, but we are using this
1645 // method exclusively for diagnostics and there's a *cultural* pressure against
1646 // them being used only for its side-effects.
1647 base.can_have_side_effects()
1649 ExprKind::Struct(_, fields, init) => fields
1651 .map(|field| field.expr)
1652 .chain(init.into_iter())
1653 .all(|e| e.can_have_side_effects()),
1655 ExprKind::Array(args)
1656 | ExprKind::Tup(args)
1660 ExprKind::Path(QPath::Resolved(
1662 Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. },
1667 ) => args.iter().all(|arg| arg.can_have_side_effects()),
1669 | ExprKind::Match(..)
1670 | ExprKind::MethodCall(..)
1671 | ExprKind::Call(..)
1672 | ExprKind::Closure(..)
1673 | ExprKind::Block(..)
1674 | ExprKind::Repeat(..)
1675 | ExprKind::Break(..)
1676 | ExprKind::Continue(..)
1679 | ExprKind::Loop(..)
1680 | ExprKind::Assign(..)
1681 | ExprKind::InlineAsm(..)
1682 | ExprKind::AssignOp(..)
1683 | ExprKind::ConstBlock(..)
1685 | ExprKind::Binary(..)
1686 | ExprKind::Yield(..)
1687 | ExprKind::DropTemps(..)
1688 | ExprKind::Err => true,
1693 /// Checks if the specified expression is a built-in range literal.
1694 /// (See: `LoweringContext::lower_expr()`).
1695 pub fn is_range_literal(expr: &Expr<'_>) -> bool {
1697 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1698 ExprKind::Struct(ref qpath, _, _) => matches!(
1703 | LangItem::RangeFrom
1704 | LangItem::RangeFull
1705 | LangItem::RangeToInclusive,
1710 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1711 ExprKind::Call(ref func, _) => {
1712 matches!(func.kind, ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, ..)))
1719 #[derive(Debug, HashStable_Generic)]
1720 pub enum ExprKind<'hir> {
1721 /// A `box x` expression.
1722 Box(&'hir Expr<'hir>),
1723 /// Allow anonymous constants from an inline `const` block
1724 ConstBlock(AnonConst),
1725 /// An array (e.g., `[a, b, c, d]`).
1726 Array(&'hir [Expr<'hir>]),
1727 /// A function call.
1729 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1730 /// and the second field is the list of arguments.
1731 /// This also represents calling the constructor of
1732 /// tuple-like ADTs such as tuple structs and enum variants.
1733 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1734 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1736 /// The `PathSegment` represents the method name and its generic arguments
1737 /// (within the angle brackets).
1738 /// The first element of the `&[Expr]` is the expression that evaluates
1739 /// to the object on which the method is being called on (the receiver),
1740 /// and the remaining elements are the rest of the arguments.
1741 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1742 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d], span)`.
1743 /// The final `Span` represents the span of the function and arguments
1744 /// (e.g. `foo::<Bar, Baz>(a, b, c, d)` in `x.foo::<Bar, Baz>(a, b, c, d)`
1746 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1747 /// the `hir_id` of the `MethodCall` node itself.
1749 /// [`type_dependent_def_id`]: ../ty/struct.TypeckResults.html#method.type_dependent_def_id
1750 MethodCall(&'hir PathSegment<'hir>, &'hir [Expr<'hir>], Span),
1751 /// A tuple (e.g., `(a, b, c, d)`).
1752 Tup(&'hir [Expr<'hir>]),
1753 /// A binary operation (e.g., `a + b`, `a * b`).
1754 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1755 /// A unary operation (e.g., `!x`, `*x`).
1756 Unary(UnOp, &'hir Expr<'hir>),
1757 /// A literal (e.g., `1`, `"foo"`).
1759 /// A cast (e.g., `foo as f64`).
1760 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1761 /// A type reference (e.g., `Foo`).
1762 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1763 /// Wraps the expression in a terminating scope.
1764 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1766 /// This construct only exists to tweak the drop order in HIR lowering.
1767 /// An example of that is the desugaring of `for` loops.
1768 DropTemps(&'hir Expr<'hir>),
1769 /// A `let $pat = $expr` expression.
1771 /// These are not `Local` and only occur as expressions.
1772 /// The `let Some(x) = foo()` in `if let Some(x) = foo()` is an example of `Let(..)`.
1773 Let(&'hir Let<'hir>),
1774 /// An `if` block, with an optional else block.
1776 /// I.e., `if <expr> { <expr> } else { <expr> }`.
1777 If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
1778 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1780 /// I.e., `'label: loop { <block> }`.
1782 /// The `Span` is the loop header (`for x in y`/`while let pat = expr`).
1783 Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span),
1784 /// A `match` block, with a source that indicates whether or not it is
1785 /// the result of a desugaring, and if so, which kind.
1786 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1787 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1789 /// The `Span` is the argument block `|...|`.
1791 /// This may also be a generator literal or an `async block` as indicated by the
1792 /// `Option<Movability>`.
1793 Closure(CaptureBy, &'hir FnDecl<'hir>, BodyId, Span, Option<Movability>),
1794 /// A block (e.g., `'label: { ... }`).
1795 Block(&'hir Block<'hir>, Option<Label>),
1797 /// An assignment (e.g., `a = foo()`).
1798 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1799 /// An assignment with an operator.
1802 AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1803 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1804 Field(&'hir Expr<'hir>, Ident),
1805 /// An indexing operation (`foo[2]`).
1806 Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1808 /// Path to a definition, possibly containing lifetime or type parameters.
1811 /// A referencing operation (i.e., `&a` or `&mut a`).
1812 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1813 /// A `break`, with an optional label to break.
1814 Break(Destination, Option<&'hir Expr<'hir>>),
1815 /// A `continue`, with an optional label.
1816 Continue(Destination),
1817 /// A `return`, with an optional value to be returned.
1818 Ret(Option<&'hir Expr<'hir>>),
1820 /// Inline assembly (from `asm!`), with its outputs and inputs.
1821 InlineAsm(&'hir InlineAsm<'hir>),
1823 /// A struct or struct-like variant literal expression.
1825 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1826 /// where `base` is the `Option<Expr>`.
1827 Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], Option<&'hir Expr<'hir>>),
1829 /// An array literal constructed from one repeated element.
1831 /// E.g., `[1; 5]`. The first expression is the element
1832 /// to be repeated; the second is the number of times to repeat it.
1833 Repeat(&'hir Expr<'hir>, ArrayLen),
1835 /// A suspension point for generators (i.e., `yield <expr>`).
1836 Yield(&'hir Expr<'hir>, YieldSource),
1838 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1842 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1844 /// To resolve the path to a `DefId`, call [`qpath_res`].
1846 /// [`qpath_res`]: ../rustc_middle/ty/struct.TypeckResults.html#method.qpath_res
1847 #[derive(Debug, HashStable_Generic)]
1848 pub enum QPath<'hir> {
1849 /// Path to a definition, optionally "fully-qualified" with a `Self`
1850 /// type, if the path points to an associated item in a trait.
1852 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1853 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1854 /// even though they both have the same two-segment `Clone::clone` `Path`.
1855 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
1857 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1858 /// Will be resolved by type-checking to an associated item.
1860 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1861 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1862 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1863 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
1865 /// Reference to a `#[lang = "foo"]` item. `HirId` of the inner expr.
1866 LangItem(LangItem, Span, Option<HirId>),
1869 impl<'hir> QPath<'hir> {
1870 /// Returns the span of this `QPath`.
1871 pub fn span(&self) -> Span {
1873 QPath::Resolved(_, path) => path.span,
1874 QPath::TypeRelative(qself, ps) => qself.span.to(ps.ident.span),
1875 QPath::LangItem(_, span, _) => span,
1879 /// Returns the span of the qself of this `QPath`. For example, `()` in
1880 /// `<() as Trait>::method`.
1881 pub fn qself_span(&self) -> Span {
1883 QPath::Resolved(_, path) => path.span,
1884 QPath::TypeRelative(qself, _) => qself.span,
1885 QPath::LangItem(_, span, _) => span,
1889 /// Returns the span of the last segment of this `QPath`. For example, `method` in
1890 /// `<() as Trait>::method`.
1891 pub fn last_segment_span(&self) -> Span {
1893 QPath::Resolved(_, path) => path.segments.last().unwrap().ident.span,
1894 QPath::TypeRelative(_, segment) => segment.ident.span,
1895 QPath::LangItem(_, span, _) => span,
1900 /// Hints at the original code for a let statement.
1901 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1902 pub enum LocalSource {
1903 /// A `match _ { .. }`.
1905 /// When lowering async functions, we create locals within the `async move` so that
1906 /// all parameters are dropped after the future is polled.
1908 /// ```ignore (pseudo-Rust)
1909 /// async fn foo(<pattern> @ x: Type) {
1911 /// let <pattern> = x;
1916 /// A desugared `<expr>.await`.
1918 /// A desugared `expr = expr`, where the LHS is a tuple, struct or array.
1919 /// The span is that of the `=` sign.
1920 AssignDesugar(Span),
1923 /// Hints at the original code for a `match _ { .. }`.
1924 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
1925 #[derive(HashStable_Generic)]
1926 pub enum MatchSource {
1927 /// A `match _ { .. }`.
1929 /// A desugared `for _ in _ { .. }` loop.
1931 /// A desugared `?` operator.
1933 /// A desugared `<expr>.await`.
1939 pub const fn name(self) -> &'static str {
1943 ForLoopDesugar => "for",
1945 AwaitDesugar => ".await",
1950 /// The loop type that yielded an `ExprKind::Loop`.
1951 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1952 pub enum LoopSource {
1953 /// A `loop { .. }` loop.
1955 /// A `while _ { .. }` loop.
1957 /// A `for _ in _ { .. }` loop.
1962 pub fn name(self) -> &'static str {
1964 LoopSource::Loop => "loop",
1965 LoopSource::While => "while",
1966 LoopSource::ForLoop => "for",
1971 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1972 pub enum LoopIdError {
1974 UnlabeledCfInWhileCondition,
1978 impl fmt::Display for LoopIdError {
1979 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1980 f.write_str(match self {
1981 LoopIdError::OutsideLoopScope => "not inside loop scope",
1982 LoopIdError::UnlabeledCfInWhileCondition => {
1983 "unlabeled control flow (break or continue) in while condition"
1985 LoopIdError::UnresolvedLabel => "label not found",
1990 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1991 pub struct Destination {
1992 // This is `Some(_)` iff there is an explicit user-specified `label
1993 pub label: Option<Label>,
1995 // These errors are caught and then reported during the diagnostics pass in
1996 // librustc_passes/loops.rs
1997 pub target_id: Result<HirId, LoopIdError>,
2000 /// The yield kind that caused an `ExprKind::Yield`.
2001 #[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
2002 pub enum YieldSource {
2003 /// An `<expr>.await`.
2004 Await { expr: Option<HirId> },
2005 /// A plain `yield`.
2010 pub fn is_await(&self) -> bool {
2012 YieldSource::Await { .. } => true,
2013 YieldSource::Yield => false,
2018 impl fmt::Display for YieldSource {
2019 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2020 f.write_str(match self {
2021 YieldSource::Await { .. } => "`await`",
2022 YieldSource::Yield => "`yield`",
2027 impl From<GeneratorKind> for YieldSource {
2028 fn from(kind: GeneratorKind) -> Self {
2030 // Guess based on the kind of the current generator.
2031 GeneratorKind::Gen => Self::Yield,
2032 GeneratorKind::Async(_) => Self::Await { expr: None },
2037 // N.B., if you change this, you'll probably want to change the corresponding
2038 // type structure in middle/ty.rs as well.
2039 #[derive(Debug, HashStable_Generic)]
2040 pub struct MutTy<'hir> {
2041 pub ty: &'hir Ty<'hir>,
2042 pub mutbl: Mutability,
2045 /// Represents a function's signature in a trait declaration,
2046 /// trait implementation, or a free function.
2047 #[derive(Debug, HashStable_Generic)]
2048 pub struct FnSig<'hir> {
2049 pub header: FnHeader,
2050 pub decl: &'hir FnDecl<'hir>,
2054 // The bodies for items are stored "out of line", in a separate
2055 // hashmap in the `Crate`. Here we just record the hir-id of the item
2056 // so it can fetched later.
2057 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
2058 pub struct TraitItemId {
2059 pub def_id: LocalDefId,
2064 pub fn hir_id(&self) -> HirId {
2065 // Items are always HIR owners.
2066 HirId::make_owner(self.def_id)
2070 /// Represents an item declaration within a trait declaration,
2071 /// possibly including a default implementation. A trait item is
2072 /// either required (meaning it doesn't have an implementation, just a
2073 /// signature) or provided (meaning it has a default implementation).
2074 #[derive(Debug, HashStable_Generic)]
2075 pub struct TraitItem<'hir> {
2077 pub def_id: LocalDefId,
2078 pub generics: Generics<'hir>,
2079 pub kind: TraitItemKind<'hir>,
2083 impl TraitItem<'_> {
2085 pub fn hir_id(&self) -> HirId {
2086 // Items are always HIR owners.
2087 HirId::make_owner(self.def_id)
2090 pub fn trait_item_id(&self) -> TraitItemId {
2091 TraitItemId { def_id: self.def_id }
2095 /// Represents a trait method's body (or just argument names).
2096 #[derive(Encodable, Debug, HashStable_Generic)]
2097 pub enum TraitFn<'hir> {
2098 /// No default body in the trait, just a signature.
2099 Required(&'hir [Ident]),
2101 /// Both signature and body are provided in the trait.
2105 /// Represents a trait method or associated constant or type
2106 #[derive(Debug, HashStable_Generic)]
2107 pub enum TraitItemKind<'hir> {
2108 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
2109 Const(&'hir Ty<'hir>, Option<BodyId>),
2110 /// An associated function with an optional body.
2111 Fn(FnSig<'hir>, TraitFn<'hir>),
2112 /// An associated type with (possibly empty) bounds and optional concrete
2114 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
2117 // The bodies for items are stored "out of line", in a separate
2118 // hashmap in the `Crate`. Here we just record the hir-id of the item
2119 // so it can fetched later.
2120 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
2121 pub struct ImplItemId {
2122 pub def_id: LocalDefId,
2127 pub fn hir_id(&self) -> HirId {
2128 // Items are always HIR owners.
2129 HirId::make_owner(self.def_id)
2133 /// Represents anything within an `impl` block.
2134 #[derive(Debug, HashStable_Generic)]
2135 pub struct ImplItem<'hir> {
2137 pub def_id: LocalDefId,
2138 pub generics: Generics<'hir>,
2139 pub kind: ImplItemKind<'hir>,
2146 pub fn hir_id(&self) -> HirId {
2147 // Items are always HIR owners.
2148 HirId::make_owner(self.def_id)
2151 pub fn impl_item_id(&self) -> ImplItemId {
2152 ImplItemId { def_id: self.def_id }
2156 /// Represents various kinds of content within an `impl`.
2157 #[derive(Debug, HashStable_Generic)]
2158 pub enum ImplItemKind<'hir> {
2159 /// An associated constant of the given type, set to the constant result
2160 /// of the expression.
2161 Const(&'hir Ty<'hir>, BodyId),
2162 /// An associated function implementation with the given signature and body.
2163 Fn(FnSig<'hir>, BodyId),
2164 /// An associated type.
2165 TyAlias(&'hir Ty<'hir>),
2168 // The name of the associated type for `Fn` return types.
2169 pub const FN_OUTPUT_NAME: Symbol = sym::Output;
2171 /// Bind a type to an associated type (i.e., `A = Foo`).
2173 /// Bindings like `A: Debug` are represented as a special type `A =
2174 /// $::Debug` that is understood by the astconv code.
2176 /// FIXME(alexreg): why have a separate type for the binding case,
2177 /// wouldn't it be better to make the `ty` field an enum like the
2181 /// enum TypeBindingKind {
2186 #[derive(Debug, HashStable_Generic)]
2187 pub struct TypeBinding<'hir> {
2190 pub gen_args: &'hir GenericArgs<'hir>,
2191 pub kind: TypeBindingKind<'hir>,
2195 #[derive(Debug, HashStable_Generic)]
2196 pub enum Term<'hir> {
2201 impl<'hir> From<&'hir Ty<'hir>> for Term<'hir> {
2202 fn from(ty: &'hir Ty<'hir>) -> Self {
2207 impl<'hir> From<AnonConst> for Term<'hir> {
2208 fn from(c: AnonConst) -> Self {
2213 // Represents the two kinds of type bindings.
2214 #[derive(Debug, HashStable_Generic)]
2215 pub enum TypeBindingKind<'hir> {
2216 /// E.g., `Foo<Bar: Send>`.
2217 Constraint { bounds: &'hir [GenericBound<'hir>] },
2218 /// E.g., `Foo<Bar = ()>`, `Foo<Bar = ()>`
2219 Equality { term: Term<'hir> },
2222 impl TypeBinding<'_> {
2223 pub fn ty(&self) -> &Ty<'_> {
2225 TypeBindingKind::Equality { term: Term::Ty(ref ty) } => ty,
2226 _ => panic!("expected equality type binding for parenthesized generic args"),
2229 pub fn opt_const(&self) -> Option<&'_ AnonConst> {
2231 TypeBindingKind::Equality { term: Term::Const(ref c) } => Some(c),
2238 pub struct Ty<'hir> {
2240 pub kind: TyKind<'hir>,
2244 /// Not represented directly in the AST; referred to by name through a `ty_path`.
2245 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
2246 #[derive(HashStable_Generic)]
2257 /// All of the primitive types
2258 pub const ALL: [Self; 17] = [
2259 // any changes here should also be reflected in `PrimTy::from_name`
2260 Self::Int(IntTy::I8),
2261 Self::Int(IntTy::I16),
2262 Self::Int(IntTy::I32),
2263 Self::Int(IntTy::I64),
2264 Self::Int(IntTy::I128),
2265 Self::Int(IntTy::Isize),
2266 Self::Uint(UintTy::U8),
2267 Self::Uint(UintTy::U16),
2268 Self::Uint(UintTy::U32),
2269 Self::Uint(UintTy::U64),
2270 Self::Uint(UintTy::U128),
2271 Self::Uint(UintTy::Usize),
2272 Self::Float(FloatTy::F32),
2273 Self::Float(FloatTy::F64),
2279 /// Like [`PrimTy::name`], but returns a &str instead of a symbol.
2282 pub fn name_str(self) -> &'static str {
2284 PrimTy::Int(i) => i.name_str(),
2285 PrimTy::Uint(u) => u.name_str(),
2286 PrimTy::Float(f) => f.name_str(),
2287 PrimTy::Str => "str",
2288 PrimTy::Bool => "bool",
2289 PrimTy::Char => "char",
2293 pub fn name(self) -> Symbol {
2295 PrimTy::Int(i) => i.name(),
2296 PrimTy::Uint(u) => u.name(),
2297 PrimTy::Float(f) => f.name(),
2298 PrimTy::Str => sym::str,
2299 PrimTy::Bool => sym::bool,
2300 PrimTy::Char => sym::char,
2304 /// Returns the matching `PrimTy` for a `Symbol` such as "str" or "i32".
2305 /// Returns `None` if no matching type is found.
2306 pub fn from_name(name: Symbol) -> Option<Self> {
2307 let ty = match name {
2308 // any changes here should also be reflected in `PrimTy::ALL`
2309 sym::i8 => Self::Int(IntTy::I8),
2310 sym::i16 => Self::Int(IntTy::I16),
2311 sym::i32 => Self::Int(IntTy::I32),
2312 sym::i64 => Self::Int(IntTy::I64),
2313 sym::i128 => Self::Int(IntTy::I128),
2314 sym::isize => Self::Int(IntTy::Isize),
2315 sym::u8 => Self::Uint(UintTy::U8),
2316 sym::u16 => Self::Uint(UintTy::U16),
2317 sym::u32 => Self::Uint(UintTy::U32),
2318 sym::u64 => Self::Uint(UintTy::U64),
2319 sym::u128 => Self::Uint(UintTy::U128),
2320 sym::usize => Self::Uint(UintTy::Usize),
2321 sym::f32 => Self::Float(FloatTy::F32),
2322 sym::f64 => Self::Float(FloatTy::F64),
2323 sym::bool => Self::Bool,
2324 sym::char => Self::Char,
2325 sym::str => Self::Str,
2332 #[derive(Debug, HashStable_Generic)]
2333 pub struct BareFnTy<'hir> {
2334 pub unsafety: Unsafety,
2336 pub generic_params: &'hir [GenericParam<'hir>],
2337 pub decl: &'hir FnDecl<'hir>,
2338 pub param_names: &'hir [Ident],
2341 #[derive(Debug, HashStable_Generic)]
2342 pub struct OpaqueTy<'hir> {
2343 pub generics: Generics<'hir>,
2344 pub bounds: GenericBounds<'hir>,
2345 pub origin: OpaqueTyOrigin,
2348 /// From whence the opaque type came.
2349 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2350 pub enum OpaqueTyOrigin {
2352 FnReturn(LocalDefId),
2354 AsyncFn(LocalDefId),
2355 /// type aliases: `type Foo = impl Trait;`
2359 /// The various kinds of types recognized by the compiler.
2360 #[derive(Debug, HashStable_Generic)]
2361 pub enum TyKind<'hir> {
2362 /// A variable length slice (i.e., `[T]`).
2363 Slice(&'hir Ty<'hir>),
2364 /// A fixed length array (i.e., `[T; n]`).
2365 Array(&'hir Ty<'hir>, ArrayLen),
2366 /// A raw pointer (i.e., `*const T` or `*mut T`).
2368 /// A reference (i.e., `&'a T` or `&'a mut T`).
2369 Rptr(Lifetime, MutTy<'hir>),
2370 /// A bare function (e.g., `fn(usize) -> bool`).
2371 BareFn(&'hir BareFnTy<'hir>),
2372 /// The never type (`!`).
2374 /// A tuple (`(A, B, C, D, ...)`).
2375 Tup(&'hir [Ty<'hir>]),
2376 /// A path to a type definition (`module::module::...::Type`), or an
2377 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2379 /// Type parameters may be stored in each `PathSegment`.
2381 /// An opaque type definition itself. This is only used for `impl Trait`.
2383 /// The generic argument list contains the lifetimes (and in the future
2384 /// possibly parameters) that are actually bound on the `impl Trait`.
2385 OpaqueDef(ItemId, &'hir [GenericArg<'hir>]),
2386 /// A trait object type `Bound1 + Bound2 + Bound3`
2387 /// where `Bound` is a trait or a lifetime.
2388 TraitObject(&'hir [PolyTraitRef<'hir>], Lifetime, TraitObjectSyntax),
2391 /// `TyKind::Infer` means the type should be inferred instead of it having been
2392 /// specified. This can appear anywhere in a type.
2394 /// Placeholder for a type that has failed to be defined.
2398 #[derive(Debug, HashStable_Generic)]
2399 pub enum InlineAsmOperand<'hir> {
2401 reg: InlineAsmRegOrRegClass,
2405 reg: InlineAsmRegOrRegClass,
2407 expr: Option<Expr<'hir>>,
2410 reg: InlineAsmRegOrRegClass,
2415 reg: InlineAsmRegOrRegClass,
2417 in_expr: Expr<'hir>,
2418 out_expr: Option<Expr<'hir>>,
2421 anon_const: AnonConst,
2424 anon_const: AnonConst,
2432 impl<'hir> InlineAsmOperand<'hir> {
2433 pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
2435 Self::In { reg, .. }
2436 | Self::Out { reg, .. }
2437 | Self::InOut { reg, .. }
2438 | Self::SplitInOut { reg, .. } => Some(reg),
2439 Self::Const { .. } | Self::SymFn { .. } | Self::SymStatic { .. } => None,
2443 pub fn is_clobber(&self) -> bool {
2446 InlineAsmOperand::Out { reg: InlineAsmRegOrRegClass::Reg(_), late: _, expr: None }
2451 #[derive(Debug, HashStable_Generic)]
2452 pub struct InlineAsm<'hir> {
2453 pub template: &'hir [InlineAsmTemplatePiece],
2454 pub template_strs: &'hir [(Symbol, Option<Symbol>, Span)],
2455 pub operands: &'hir [(InlineAsmOperand<'hir>, Span)],
2456 pub options: InlineAsmOptions,
2457 pub line_spans: &'hir [Span],
2460 /// Represents a parameter in a function header.
2461 #[derive(Debug, HashStable_Generic)]
2462 pub struct Param<'hir> {
2464 pub pat: &'hir Pat<'hir>,
2469 /// Represents the header (not the body) of a function declaration.
2470 #[derive(Debug, HashStable_Generic)]
2471 pub struct FnDecl<'hir> {
2472 /// The types of the function's parameters.
2474 /// Additional argument data is stored in the function's [body](Body::params).
2475 pub inputs: &'hir [Ty<'hir>],
2476 pub output: FnRetTy<'hir>,
2477 pub c_variadic: bool,
2478 /// Does the function have an implicit self?
2479 pub implicit_self: ImplicitSelfKind,
2482 /// Represents what type of implicit self a function has, if any.
2483 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2484 pub enum ImplicitSelfKind {
2485 /// Represents a `fn x(self);`.
2487 /// Represents a `fn x(mut self);`.
2489 /// Represents a `fn x(&self);`.
2491 /// Represents a `fn x(&mut self);`.
2493 /// Represents when a function does not have a self argument or
2494 /// when a function has a `self: X` argument.
2498 impl ImplicitSelfKind {
2499 /// Does this represent an implicit self?
2500 pub fn has_implicit_self(&self) -> bool {
2501 !matches!(*self, ImplicitSelfKind::None)
2505 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable, Debug)]
2506 #[derive(HashStable_Generic)]
2512 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable, HashStable_Generic)]
2513 pub enum Defaultness {
2514 Default { has_value: bool },
2519 pub fn has_value(&self) -> bool {
2521 Defaultness::Default { has_value } => has_value,
2522 Defaultness::Final => true,
2526 pub fn is_final(&self) -> bool {
2527 *self == Defaultness::Final
2530 pub fn is_default(&self) -> bool {
2531 matches!(*self, Defaultness::Default { .. })
2535 #[derive(Debug, HashStable_Generic)]
2536 pub enum FnRetTy<'hir> {
2537 /// Return type is not specified.
2539 /// Functions default to `()` and
2540 /// closures default to inference. Span points to where return
2541 /// type would be inserted.
2542 DefaultReturn(Span),
2543 /// Everything else.
2544 Return(&'hir Ty<'hir>),
2549 pub fn span(&self) -> Span {
2551 Self::DefaultReturn(span) => span,
2552 Self::Return(ref ty) => ty.span,
2557 #[derive(Encodable, Debug, HashStable_Generic)]
2558 pub struct Mod<'hir> {
2559 pub spans: ModSpans,
2560 pub item_ids: &'hir [ItemId],
2563 #[derive(Copy, Clone, Debug, HashStable_Generic, Encodable)]
2564 pub struct ModSpans {
2565 /// A span from the first token past `{` to the last token until `}`.
2566 /// For `mod foo;`, the inner span ranges from the first token
2567 /// to the last token in the external file.
2568 pub inner_span: Span,
2569 pub inject_use_span: Span,
2572 #[derive(Debug, HashStable_Generic)]
2573 pub struct EnumDef<'hir> {
2574 pub variants: &'hir [Variant<'hir>],
2577 #[derive(Debug, HashStable_Generic)]
2578 pub struct Variant<'hir> {
2579 /// Name of the variant.
2581 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2583 /// Fields and constructor id of the variant.
2584 pub data: VariantData<'hir>,
2585 /// Explicit discriminant (e.g., `Foo = 1`).
2586 pub disr_expr: Option<AnonConst>,
2591 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2593 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2594 /// Also produced for each element of a list `use`, e.g.
2595 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2598 /// Glob import, e.g., `use foo::*`.
2601 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2602 /// an additional `use foo::{}` for performing checks such as
2603 /// unstable feature gating. May be removed in the future.
2607 /// References to traits in impls.
2609 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2610 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2611 /// trait being referred to but just a unique `HirId` that serves as a key
2612 /// within the resolution map.
2613 #[derive(Clone, Debug, HashStable_Generic)]
2614 pub struct TraitRef<'hir> {
2615 pub path: &'hir Path<'hir>,
2616 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2617 #[stable_hasher(ignore)]
2618 pub hir_ref_id: HirId,
2622 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2623 pub fn trait_def_id(&self) -> Option<DefId> {
2624 match self.path.res {
2625 Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
2627 _ => unreachable!(),
2632 #[derive(Clone, Debug, HashStable_Generic)]
2633 pub struct PolyTraitRef<'hir> {
2634 /// The `'a` in `for<'a> Foo<&'a T>`.
2635 pub bound_generic_params: &'hir [GenericParam<'hir>],
2637 /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
2638 pub trait_ref: TraitRef<'hir>,
2643 #[derive(Debug, HashStable_Generic)]
2644 pub struct FieldDef<'hir> {
2649 pub ty: &'hir Ty<'hir>,
2653 // Still necessary in couple of places
2654 pub fn is_positional(&self) -> bool {
2655 let first = self.ident.as_str().as_bytes()[0];
2656 (b'0'..=b'9').contains(&first)
2660 /// Fields and constructor IDs of enum variants and structs.
2661 #[derive(Debug, HashStable_Generic)]
2662 pub enum VariantData<'hir> {
2663 /// A struct variant.
2665 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2666 Struct(&'hir [FieldDef<'hir>], /* recovered */ bool),
2667 /// A tuple variant.
2669 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2670 Tuple(&'hir [FieldDef<'hir>], HirId),
2673 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2677 impl<'hir> VariantData<'hir> {
2678 /// Return the fields of this variant.
2679 pub fn fields(&self) -> &'hir [FieldDef<'hir>] {
2681 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2686 /// Return the `HirId` of this variant's constructor, if it has one.
2687 pub fn ctor_hir_id(&self) -> Option<HirId> {
2689 VariantData::Struct(_, _) => None,
2690 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2695 // The bodies for items are stored "out of line", in a separate
2696 // hashmap in the `Crate`. Here we just record the hir-id of the item
2697 // so it can fetched later.
2698 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, Hash, HashStable_Generic)]
2700 pub def_id: LocalDefId,
2705 pub fn hir_id(&self) -> HirId {
2706 // Items are always HIR owners.
2707 HirId::make_owner(self.def_id)
2713 /// The name might be a dummy name in case of anonymous items
2714 #[derive(Debug, HashStable_Generic)]
2715 pub struct Item<'hir> {
2717 pub def_id: LocalDefId,
2718 pub kind: ItemKind<'hir>,
2725 pub fn hir_id(&self) -> HirId {
2726 // Items are always HIR owners.
2727 HirId::make_owner(self.def_id)
2730 pub fn item_id(&self) -> ItemId {
2731 ItemId { def_id: self.def_id }
2735 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2736 #[derive(Encodable, Decodable, HashStable_Generic)]
2743 pub fn prefix_str(&self) -> &'static str {
2745 Self::Unsafe => "unsafe ",
2751 impl fmt::Display for Unsafety {
2752 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2753 f.write_str(match *self {
2754 Self::Unsafe => "unsafe",
2755 Self::Normal => "normal",
2760 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2761 #[derive(Encodable, Decodable, HashStable_Generic)]
2762 pub enum Constness {
2767 impl fmt::Display for Constness {
2768 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2769 f.write_str(match *self {
2770 Self::Const => "const",
2771 Self::NotConst => "non-const",
2776 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2777 pub struct FnHeader {
2778 pub unsafety: Unsafety,
2779 pub constness: Constness,
2780 pub asyncness: IsAsync,
2785 pub fn is_async(&self) -> bool {
2786 matches!(&self.asyncness, IsAsync::Async)
2789 pub fn is_const(&self) -> bool {
2790 matches!(&self.constness, Constness::Const)
2793 pub fn is_unsafe(&self) -> bool {
2794 matches!(&self.unsafety, Unsafety::Unsafe)
2798 #[derive(Debug, HashStable_Generic)]
2799 pub enum ItemKind<'hir> {
2800 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2802 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2803 ExternCrate(Option<Symbol>),
2805 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2809 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2810 Use(&'hir Path<'hir>, UseKind),
2812 /// A `static` item.
2813 Static(&'hir Ty<'hir>, Mutability, BodyId),
2815 Const(&'hir Ty<'hir>, BodyId),
2816 /// A function declaration.
2817 Fn(FnSig<'hir>, Generics<'hir>, BodyId),
2818 /// A MBE macro definition (`macro_rules!` or `macro`).
2819 Macro(ast::MacroDef, MacroKind),
2822 /// An external module, e.g. `extern { .. }`.
2823 ForeignMod { abi: Abi, items: &'hir [ForeignItemRef] },
2824 /// Module-level inline assembly (from `global_asm!`).
2825 GlobalAsm(&'hir InlineAsm<'hir>),
2826 /// A type alias, e.g., `type Foo = Bar<u8>`.
2827 TyAlias(&'hir Ty<'hir>, Generics<'hir>),
2828 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2829 OpaqueTy(OpaqueTy<'hir>),
2830 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2831 Enum(EnumDef<'hir>, Generics<'hir>),
2832 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2833 Struct(VariantData<'hir>, Generics<'hir>),
2834 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2835 Union(VariantData<'hir>, Generics<'hir>),
2836 /// A trait definition.
2837 Trait(IsAuto, Unsafety, Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
2839 TraitAlias(Generics<'hir>, GenericBounds<'hir>),
2841 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2845 #[derive(Debug, HashStable_Generic)]
2846 pub struct Impl<'hir> {
2847 pub unsafety: Unsafety,
2848 pub polarity: ImplPolarity,
2849 pub defaultness: Defaultness,
2850 // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata
2851 // decoding as `Span`s cannot be decoded when a `Session` is not available.
2852 pub defaultness_span: Option<Span>,
2853 pub constness: Constness,
2854 pub generics: Generics<'hir>,
2856 /// The trait being implemented, if any.
2857 pub of_trait: Option<TraitRef<'hir>>,
2859 pub self_ty: &'hir Ty<'hir>,
2860 pub items: &'hir [ImplItemRef],
2864 pub fn generics(&self) -> Option<&Generics<'_>> {
2866 ItemKind::Fn(_, ref generics, _)
2867 | ItemKind::TyAlias(_, ref generics)
2868 | ItemKind::OpaqueTy(OpaqueTy {
2869 ref generics, origin: OpaqueTyOrigin::TyAlias, ..
2871 | ItemKind::Enum(_, ref generics)
2872 | ItemKind::Struct(_, ref generics)
2873 | ItemKind::Union(_, ref generics)
2874 | ItemKind::Trait(_, _, ref generics, _, _)
2875 | ItemKind::Impl(Impl { ref generics, .. }) => generics,
2880 pub fn descr(&self) -> &'static str {
2882 ItemKind::ExternCrate(..) => "extern crate",
2883 ItemKind::Use(..) => "`use` import",
2884 ItemKind::Static(..) => "static item",
2885 ItemKind::Const(..) => "constant item",
2886 ItemKind::Fn(..) => "function",
2887 ItemKind::Macro(..) => "macro",
2888 ItemKind::Mod(..) => "module",
2889 ItemKind::ForeignMod { .. } => "extern block",
2890 ItemKind::GlobalAsm(..) => "global asm item",
2891 ItemKind::TyAlias(..) => "type alias",
2892 ItemKind::OpaqueTy(..) => "opaque type",
2893 ItemKind::Enum(..) => "enum",
2894 ItemKind::Struct(..) => "struct",
2895 ItemKind::Union(..) => "union",
2896 ItemKind::Trait(..) => "trait",
2897 ItemKind::TraitAlias(..) => "trait alias",
2898 ItemKind::Impl(..) => "implementation",
2903 /// A reference from an trait to one of its associated items. This
2904 /// contains the item's id, naturally, but also the item's name and
2905 /// some other high-level details (like whether it is an associated
2906 /// type or method, and whether it is public). This allows other
2907 /// passes to find the impl they want without loading the ID (which
2908 /// means fewer edges in the incremental compilation graph).
2909 #[derive(Encodable, Debug, HashStable_Generic)]
2910 pub struct TraitItemRef {
2911 pub id: TraitItemId,
2913 pub kind: AssocItemKind,
2915 pub defaultness: Defaultness,
2918 /// A reference from an impl to one of its associated items. This
2919 /// contains the item's ID, naturally, but also the item's name and
2920 /// some other high-level details (like whether it is an associated
2921 /// type or method, and whether it is public). This allows other
2922 /// passes to find the impl they want without loading the ID (which
2923 /// means fewer edges in the incremental compilation graph).
2924 #[derive(Debug, HashStable_Generic)]
2925 pub struct ImplItemRef {
2928 pub kind: AssocItemKind,
2930 pub defaultness: Defaultness,
2931 /// When we are in a trait impl, link to the trait-item's id.
2932 pub trait_item_def_id: Option<DefId>,
2935 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2936 pub enum AssocItemKind {
2938 Fn { has_self: bool },
2942 // The bodies for items are stored "out of line", in a separate
2943 // hashmap in the `Crate`. Here we just record the hir-id of the item
2944 // so it can fetched later.
2945 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
2946 pub struct ForeignItemId {
2947 pub def_id: LocalDefId,
2950 impl ForeignItemId {
2952 pub fn hir_id(&self) -> HirId {
2953 // Items are always HIR owners.
2954 HirId::make_owner(self.def_id)
2958 /// A reference from a foreign block to one of its items. This
2959 /// contains the item's ID, naturally, but also the item's name and
2960 /// some other high-level details (like whether it is an associated
2961 /// type or method, and whether it is public). This allows other
2962 /// passes to find the impl they want without loading the ID (which
2963 /// means fewer edges in the incremental compilation graph).
2964 #[derive(Debug, HashStable_Generic)]
2965 pub struct ForeignItemRef {
2966 pub id: ForeignItemId,
2971 #[derive(Debug, HashStable_Generic)]
2972 pub struct ForeignItem<'hir> {
2974 pub kind: ForeignItemKind<'hir>,
2975 pub def_id: LocalDefId,
2980 impl ForeignItem<'_> {
2982 pub fn hir_id(&self) -> HirId {
2983 // Items are always HIR owners.
2984 HirId::make_owner(self.def_id)
2987 pub fn foreign_item_id(&self) -> ForeignItemId {
2988 ForeignItemId { def_id: self.def_id }
2992 /// An item within an `extern` block.
2993 #[derive(Debug, HashStable_Generic)]
2994 pub enum ForeignItemKind<'hir> {
2995 /// A foreign function.
2996 Fn(&'hir FnDecl<'hir>, &'hir [Ident], Generics<'hir>),
2997 /// A foreign static item (`static ext: u8`).
2998 Static(&'hir Ty<'hir>, Mutability),
3003 /// A variable captured by a closure.
3004 #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)]
3006 // First span where it is accessed (there can be multiple).
3010 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
3011 // has length > 0 if the trait is found through an chain of imports, starting with the
3012 // import/use statement in the scope where the trait is used.
3013 #[derive(Encodable, Decodable, Clone, Debug, HashStable_Generic)]
3014 pub struct TraitCandidate {
3016 pub import_ids: SmallVec<[LocalDefId; 1]>,
3019 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3020 pub enum OwnerNode<'hir> {
3021 Item(&'hir Item<'hir>),
3022 ForeignItem(&'hir ForeignItem<'hir>),
3023 TraitItem(&'hir TraitItem<'hir>),
3024 ImplItem(&'hir ImplItem<'hir>),
3025 Crate(&'hir Mod<'hir>),
3028 impl<'hir> OwnerNode<'hir> {
3029 pub fn ident(&self) -> Option<Ident> {
3031 OwnerNode::Item(Item { ident, .. })
3032 | OwnerNode::ForeignItem(ForeignItem { ident, .. })
3033 | OwnerNode::ImplItem(ImplItem { ident, .. })
3034 | OwnerNode::TraitItem(TraitItem { ident, .. }) => Some(*ident),
3035 OwnerNode::Crate(..) => None,
3039 pub fn span(&self) -> Span {
3041 OwnerNode::Item(Item { span, .. })
3042 | OwnerNode::ForeignItem(ForeignItem { span, .. })
3043 | OwnerNode::ImplItem(ImplItem { span, .. })
3044 | OwnerNode::TraitItem(TraitItem { span, .. }) => *span,
3045 OwnerNode::Crate(Mod { spans: ModSpans { inner_span, .. }, .. }) => *inner_span,
3049 pub fn fn_decl(&self) -> Option<&FnDecl<'hir>> {
3051 OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3052 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3053 | OwnerNode::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3054 OwnerNode::ForeignItem(ForeignItem {
3055 kind: ForeignItemKind::Fn(fn_decl, _, _),
3057 }) => Some(fn_decl),
3062 pub fn body_id(&self) -> Option<BodyId> {
3064 OwnerNode::TraitItem(TraitItem {
3065 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3068 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3069 | OwnerNode::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3074 pub fn generics(&self) -> Option<&'hir Generics<'hir>> {
3076 OwnerNode::TraitItem(TraitItem { generics, .. })
3077 | OwnerNode::ImplItem(ImplItem { generics, .. }) => Some(generics),
3078 OwnerNode::Item(item) => item.kind.generics(),
3083 pub fn def_id(self) -> LocalDefId {
3085 OwnerNode::Item(Item { def_id, .. })
3086 | OwnerNode::TraitItem(TraitItem { def_id, .. })
3087 | OwnerNode::ImplItem(ImplItem { def_id, .. })
3088 | OwnerNode::ForeignItem(ForeignItem { def_id, .. }) => *def_id,
3089 OwnerNode::Crate(..) => crate::CRATE_HIR_ID.owner,
3093 pub fn expect_item(self) -> &'hir Item<'hir> {
3095 OwnerNode::Item(n) => n,
3100 pub fn expect_foreign_item(self) -> &'hir ForeignItem<'hir> {
3102 OwnerNode::ForeignItem(n) => n,
3107 pub fn expect_impl_item(self) -> &'hir ImplItem<'hir> {
3109 OwnerNode::ImplItem(n) => n,
3114 pub fn expect_trait_item(self) -> &'hir TraitItem<'hir> {
3116 OwnerNode::TraitItem(n) => n,
3122 impl<'hir> Into<OwnerNode<'hir>> for &'hir Item<'hir> {
3123 fn into(self) -> OwnerNode<'hir> {
3124 OwnerNode::Item(self)
3128 impl<'hir> Into<OwnerNode<'hir>> for &'hir ForeignItem<'hir> {
3129 fn into(self) -> OwnerNode<'hir> {
3130 OwnerNode::ForeignItem(self)
3134 impl<'hir> Into<OwnerNode<'hir>> for &'hir ImplItem<'hir> {
3135 fn into(self) -> OwnerNode<'hir> {
3136 OwnerNode::ImplItem(self)
3140 impl<'hir> Into<OwnerNode<'hir>> for &'hir TraitItem<'hir> {
3141 fn into(self) -> OwnerNode<'hir> {
3142 OwnerNode::TraitItem(self)
3146 impl<'hir> Into<Node<'hir>> for OwnerNode<'hir> {
3147 fn into(self) -> Node<'hir> {
3149 OwnerNode::Item(n) => Node::Item(n),
3150 OwnerNode::ForeignItem(n) => Node::ForeignItem(n),
3151 OwnerNode::ImplItem(n) => Node::ImplItem(n),
3152 OwnerNode::TraitItem(n) => Node::TraitItem(n),
3153 OwnerNode::Crate(n) => Node::Crate(n),
3158 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3159 pub enum Node<'hir> {
3160 Param(&'hir Param<'hir>),
3161 Item(&'hir Item<'hir>),
3162 ForeignItem(&'hir ForeignItem<'hir>),
3163 TraitItem(&'hir TraitItem<'hir>),
3164 ImplItem(&'hir ImplItem<'hir>),
3165 Variant(&'hir Variant<'hir>),
3166 Field(&'hir FieldDef<'hir>),
3167 AnonConst(&'hir AnonConst),
3168 Expr(&'hir Expr<'hir>),
3169 Stmt(&'hir Stmt<'hir>),
3170 PathSegment(&'hir PathSegment<'hir>),
3172 TraitRef(&'hir TraitRef<'hir>),
3173 Binding(&'hir Pat<'hir>),
3174 Pat(&'hir Pat<'hir>),
3175 Arm(&'hir Arm<'hir>),
3176 Block(&'hir Block<'hir>),
3177 Local(&'hir Local<'hir>),
3179 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
3180 /// with synthesized constructors.
3181 Ctor(&'hir VariantData<'hir>),
3183 Lifetime(&'hir Lifetime),
3184 GenericParam(&'hir GenericParam<'hir>),
3186 Crate(&'hir Mod<'hir>),
3188 Infer(&'hir InferArg),
3191 impl<'hir> Node<'hir> {
3192 /// Get the identifier of this `Node`, if applicable.
3196 /// Calling `.ident()` on a [`Node::Ctor`] will return `None`
3197 /// because `Ctor`s do not have identifiers themselves.
3198 /// Instead, call `.ident()` on the parent struct/variant, like so:
3200 /// ```ignore (illustrative)
3203 /// .and_then(|ctor_id| tcx.hir().find(tcx.hir().get_parent_node(ctor_id)))
3204 /// .and_then(|parent| parent.ident())
3206 pub fn ident(&self) -> Option<Ident> {
3208 Node::TraitItem(TraitItem { ident, .. })
3209 | Node::ImplItem(ImplItem { ident, .. })
3210 | Node::ForeignItem(ForeignItem { ident, .. })
3211 | Node::Field(FieldDef { ident, .. })
3212 | Node::Variant(Variant { ident, .. })
3213 | Node::Item(Item { ident, .. })
3214 | Node::PathSegment(PathSegment { ident, .. }) => Some(*ident),
3215 Node::Lifetime(lt) => Some(lt.name.ident()),
3216 Node::GenericParam(p) => Some(p.name.ident()),
3218 | Node::AnonConst(..)
3229 | Node::TraitRef(..)
3230 | Node::Infer(..) => None,
3234 pub fn fn_decl(&self) -> Option<&'hir FnDecl<'hir>> {
3236 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3237 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3238 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3239 Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
3246 pub fn fn_sig(&self) -> Option<&'hir FnSig<'hir>> {
3248 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3249 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3250 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig),
3255 pub fn body_id(&self) -> Option<BodyId> {
3257 Node::TraitItem(TraitItem {
3258 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3261 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3262 | Node::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3267 pub fn generics(&self) -> Option<&'hir Generics<'hir>> {
3269 Node::TraitItem(TraitItem { generics, .. })
3270 | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
3271 Node::Item(item) => item.kind.generics(),
3276 pub fn as_owner(self) -> Option<OwnerNode<'hir>> {
3278 Node::Item(i) => Some(OwnerNode::Item(i)),
3279 Node::ForeignItem(i) => Some(OwnerNode::ForeignItem(i)),
3280 Node::TraitItem(i) => Some(OwnerNode::TraitItem(i)),
3281 Node::ImplItem(i) => Some(OwnerNode::ImplItem(i)),
3282 Node::Crate(i) => Some(OwnerNode::Crate(i)),
3287 pub fn fn_kind(self) -> Option<FnKind<'hir>> {
3289 Node::Item(i) => match i.kind {
3290 ItemKind::Fn(ref sig, ref generics, _) => {
3291 Some(FnKind::ItemFn(i.ident, generics, sig.header))
3295 Node::TraitItem(ti) => match ti.kind {
3296 TraitItemKind::Fn(ref sig, TraitFn::Provided(_)) => {
3297 Some(FnKind::Method(ti.ident, sig))
3301 Node::ImplItem(ii) => match ii.kind {
3302 ImplItemKind::Fn(ref sig, _) => Some(FnKind::Method(ii.ident, sig)),
3305 Node::Expr(e) => match e.kind {
3306 ExprKind::Closure(..) => Some(FnKind::Closure),
3313 /// Get the fields for the tuple-constructor,
3314 /// if this node is a tuple constructor, otherwise None
3315 pub fn tuple_fields(&self) -> Option<&'hir [FieldDef<'hir>]> {
3316 if let Node::Ctor(&VariantData::Tuple(fields, _)) = self { Some(fields) } else { None }
3320 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3321 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
3323 rustc_data_structures::static_assert_size!(super::Block<'static>, 48);
3324 rustc_data_structures::static_assert_size!(super::Expr<'static>, 56);
3325 rustc_data_structures::static_assert_size!(super::Pat<'static>, 88);
3326 rustc_data_structures::static_assert_size!(super::QPath<'static>, 24);
3327 rustc_data_structures::static_assert_size!(super::Ty<'static>, 72);
3328 rustc_data_structures::static_assert_size!(super::GenericBound<'_>, 48);
3330 rustc_data_structures::static_assert_size!(super::Item<'static>, 160);
3331 rustc_data_structures::static_assert_size!(super::TraitItem<'static>, 128);
3332 rustc_data_structures::static_assert_size!(super::ImplItem<'static>, 120);
3333 rustc_data_structures::static_assert_size!(super::ForeignItem<'static>, 112);