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;
7 use rustc_ast::util::parser::ExprPrecedence;
8 use rustc_ast::{self as ast, CrateSugar};
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_index::vec::IndexVec;
17 use rustc_macros::HashStable_Generic;
18 use rustc_span::hygiene::MacroKind;
19 use rustc_span::source_map::Spanned;
20 use rustc_span::symbol::{kw, sym, Ident, Symbol};
21 use rustc_span::{def_id::LocalDefId, BytePos, MultiSpan, Span, DUMMY_SP};
22 use rustc_target::asm::InlineAsmRegOrRegClass;
23 use rustc_target::spec::abi::Abi;
25 use smallvec::SmallVec;
28 #[derive(Copy, Clone, Encodable, HashStable_Generic)]
33 /// Either "`'a`", referring to a named lifetime definition,
34 /// or "``" (i.e., `kw::Empty`), for elision placeholders.
36 /// HIR lowering inserts these placeholders in type paths that
37 /// refer to type definitions needing lifetime parameters,
38 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
39 pub name: LifetimeName,
42 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
43 #[derive(HashStable_Generic)]
45 /// Some user-given name like `T` or `'x`.
48 /// Synthetic name generated when user elided a lifetime in an impl header.
50 /// E.g., the lifetimes in cases like these:
53 /// impl Foo<'_> for u32
55 /// in that case, we rewrite to
57 /// impl<'f> Foo for &'f u32
58 /// impl<'f> Foo<'f> for u32
60 /// where `'f` is something like `Fresh(0)`. The indices are
61 /// unique per impl, but not necessarily continuous.
64 /// Indicates an illegal name was given and an error has been
65 /// reported (so we should squelch other derived errors). Occurs
66 /// when, e.g., `'_` is used in the wrong place.
71 pub fn ident(&self) -> Ident {
73 ParamName::Plain(ident) => ident,
74 ParamName::Fresh(_) | ParamName::Error => {
75 Ident::with_dummy_span(kw::UnderscoreLifetime)
80 pub fn normalize_to_macros_2_0(&self) -> ParamName {
82 ParamName::Plain(ident) => ParamName::Plain(ident.normalize_to_macros_2_0()),
83 param_name => param_name,
88 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
89 #[derive(HashStable_Generic)]
90 pub enum LifetimeName {
91 /// User-given names or fresh (synthetic) names.
94 /// User wrote nothing (e.g., the lifetime in `&u32`).
96 /// The bool indicates whether the user should have written something.
99 /// Implicit lifetime in a context like `dyn Foo`. This is
100 /// distinguished from implicit lifetimes elsewhere because the
101 /// lifetime that they default to must appear elsewhere within the
102 /// enclosing type. This means that, in an `impl Trait` context, we
103 /// don't have to create a parameter for them. That is, `impl
104 /// Trait<Item = &u32>` expands to an opaque type like `type
105 /// Foo<'a> = impl Trait<Item = &'a u32>`, but `impl Trait<item =
106 /// dyn Bar>` expands to `type Foo = impl Trait<Item = dyn Bar +
107 /// 'static>`. The latter uses `ImplicitObjectLifetimeDefault` so
108 /// that surrounding code knows not to create a lifetime
110 ImplicitObjectLifetimeDefault,
112 /// Indicates an error during lowering (usually `'_` in wrong place)
113 /// that was already reported.
116 /// User wrote specifies `'_`.
119 /// User wrote `'static`.
124 pub fn ident(&self) -> Ident {
126 LifetimeName::ImplicitObjectLifetimeDefault
127 | LifetimeName::Implicit(_)
128 | LifetimeName::Error => Ident::empty(),
129 LifetimeName::Underscore => Ident::with_dummy_span(kw::UnderscoreLifetime),
130 LifetimeName::Static => Ident::with_dummy_span(kw::StaticLifetime),
131 LifetimeName::Param(param_name) => param_name.ident(),
135 pub fn is_elided(&self) -> bool {
137 LifetimeName::ImplicitObjectLifetimeDefault
138 | LifetimeName::Implicit(_)
139 | LifetimeName::Underscore => true,
141 // It might seem surprising that `Fresh(_)` counts as
142 // *not* elided -- but this is because, as far as the code
143 // in the compiler is concerned -- `Fresh(_)` variants act
144 // equivalently to "some fresh name". They correspond to
145 // early-bound regions on an impl, in other words.
146 LifetimeName::Error | LifetimeName::Param(_) | LifetimeName::Static => false,
150 fn is_static(&self) -> bool {
151 self == &LifetimeName::Static
154 pub fn normalize_to_macros_2_0(&self) -> LifetimeName {
156 LifetimeName::Param(param_name) => {
157 LifetimeName::Param(param_name.normalize_to_macros_2_0())
159 lifetime_name => lifetime_name,
164 impl fmt::Display for Lifetime {
165 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166 self.name.ident().fmt(f)
170 impl fmt::Debug for Lifetime {
171 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
172 write!(f, "lifetime({}: {})", self.hir_id, self.name.ident())
177 pub fn is_elided(&self) -> bool {
178 self.name.is_elided()
181 pub fn is_static(&self) -> bool {
182 self.name.is_static()
186 /// A `Path` is essentially Rust's notion of a name; for instance,
187 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
188 /// along with a bunch of supporting information.
189 #[derive(Debug, HashStable_Generic)]
190 pub struct Path<'hir> {
192 /// The resolution for the path.
194 /// The segments in the path: the things separated by `::`.
195 pub segments: &'hir [PathSegment<'hir>],
199 pub fn is_global(&self) -> bool {
200 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
204 /// A segment of a path: an identifier, an optional lifetime, and a set of
206 #[derive(Debug, HashStable_Generic)]
207 pub struct PathSegment<'hir> {
208 /// The identifier portion of this path segment.
210 // `id` and `res` are optional. We currently only use these in save-analysis,
211 // any path segments without these will not have save-analysis info and
212 // therefore will not have 'jump to def' in IDEs, but otherwise will not be
213 // affected. (In general, we don't bother to get the defs for synthesized
214 // segments, only for segments which have come from the AST).
215 pub hir_id: Option<HirId>,
216 pub res: Option<Res>,
218 /// Type/lifetime parameters attached to this path. They come in
219 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
220 /// this is more than just simple syntactic sugar; the use of
221 /// parens affects the region binding rules, so we preserve the
223 pub args: Option<&'hir GenericArgs<'hir>>,
225 /// Whether to infer remaining type parameters, if any.
226 /// This only applies to expression and pattern paths, and
227 /// out of those only the segments with no type parameters
228 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
229 pub infer_args: bool,
232 impl<'hir> PathSegment<'hir> {
233 /// Converts an identifier to the corresponding segment.
234 pub fn from_ident(ident: Ident) -> PathSegment<'hir> {
235 PathSegment { ident, hir_id: None, res: None, infer_args: true, args: None }
238 pub fn invalid() -> Self {
239 Self::from_ident(Ident::empty())
242 pub fn args(&self) -> &GenericArgs<'hir> {
243 if let Some(ref args) = self.args {
246 const DUMMY: &GenericArgs<'_> = &GenericArgs::none();
252 #[derive(Encodable, Debug, HashStable_Generic)]
253 pub struct ConstArg {
254 pub value: AnonConst,
258 #[derive(Encodable, Debug, HashStable_Generic)]
259 pub struct InferArg {
265 pub fn to_ty(&self) -> Ty<'_> {
266 Ty { kind: TyKind::Infer, span: self.span, hir_id: self.hir_id }
270 #[derive(Debug, HashStable_Generic)]
271 pub enum GenericArg<'hir> {
278 impl GenericArg<'_> {
279 pub fn span(&self) -> Span {
281 GenericArg::Lifetime(l) => l.span,
282 GenericArg::Type(t) => t.span,
283 GenericArg::Const(c) => c.span,
284 GenericArg::Infer(i) => i.span,
288 pub fn id(&self) -> HirId {
290 GenericArg::Lifetime(l) => l.hir_id,
291 GenericArg::Type(t) => t.hir_id,
292 GenericArg::Const(c) => c.value.hir_id,
293 GenericArg::Infer(i) => i.hir_id,
297 pub fn is_synthetic(&self) -> bool {
298 matches!(self, GenericArg::Lifetime(lifetime) if lifetime.name.ident() == Ident::empty())
301 pub fn descr(&self) -> &'static str {
303 GenericArg::Lifetime(_) => "lifetime",
304 GenericArg::Type(_) => "type",
305 GenericArg::Const(_) => "constant",
306 GenericArg::Infer(_) => "inferred",
310 pub fn to_ord(&self) -> ast::ParamKindOrd {
312 GenericArg::Lifetime(_) => ast::ParamKindOrd::Lifetime,
313 GenericArg::Type(_) => ast::ParamKindOrd::Type,
314 GenericArg::Const(_) => ast::ParamKindOrd::Const,
315 GenericArg::Infer(_) => ast::ParamKindOrd::Infer,
319 pub fn is_ty_or_const(&self) -> bool {
321 GenericArg::Lifetime(_) => false,
322 GenericArg::Type(_) | GenericArg::Const(_) | GenericArg::Infer(_) => true,
327 #[derive(Debug, HashStable_Generic)]
328 pub struct GenericArgs<'hir> {
329 /// The generic arguments for this path segment.
330 pub args: &'hir [GenericArg<'hir>],
331 /// Bindings (equality constraints) on associated types, if present.
332 /// E.g., `Foo<A = Bar>`.
333 pub bindings: &'hir [TypeBinding<'hir>],
334 /// Were arguments written in parenthesized form `Fn(T) -> U`?
335 /// This is required mostly for pretty-printing and diagnostics,
336 /// but also for changing lifetime elision rules to be "function-like".
337 pub parenthesized: bool,
338 /// The span encompassing arguments and the surrounding brackets `<>` or `()`
339 /// Foo<A, B, AssocTy = D> Fn(T, U, V) -> W
340 /// ^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^
341 /// Note that this may be:
342 /// - empty, if there are no generic brackets (but there may be hidden lifetimes)
343 /// - dummy, if this was generated while desugaring
347 impl GenericArgs<'_> {
348 pub const fn none() -> Self {
349 Self { args: &[], bindings: &[], parenthesized: false, span_ext: DUMMY_SP }
352 pub fn inputs(&self) -> &[Ty<'_>] {
353 if self.parenthesized {
354 for arg in self.args {
356 GenericArg::Lifetime(_) => {}
357 GenericArg::Type(ref ty) => {
358 if let TyKind::Tup(ref tys) = ty.kind {
363 GenericArg::Const(_) => {}
364 GenericArg::Infer(_) => {}
368 panic!("GenericArgs::inputs: not a `Fn(T) -> U`");
372 pub fn has_type_params(&self) -> bool {
373 self.args.iter().any(|arg| matches!(arg, GenericArg::Type(_)))
376 pub fn has_err(&self) -> bool {
377 self.args.iter().any(|arg| match arg {
378 GenericArg::Type(ty) => matches!(ty.kind, TyKind::Err),
380 }) || self.bindings.iter().any(|arg| match arg.kind {
381 TypeBindingKind::Equality { term: Term::Ty(ty) } => matches!(ty.kind, TyKind::Err),
387 pub fn num_type_params(&self) -> usize {
388 self.args.iter().filter(|arg| matches!(arg, GenericArg::Type(_))).count()
392 pub fn num_lifetime_params(&self) -> usize {
393 self.args.iter().filter(|arg| matches!(arg, GenericArg::Lifetime(_))).count()
397 pub fn has_lifetime_params(&self) -> bool {
398 self.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)))
402 pub fn num_generic_params(&self) -> usize {
403 self.args.iter().filter(|arg| !matches!(arg, GenericArg::Lifetime(_))).count()
406 /// The span encompassing the text inside the surrounding brackets.
407 /// It will also include bindings if they aren't in the form `-> Ret`
408 /// Returns `None` if the span is empty (e.g. no brackets) or dummy
409 pub fn span(&self) -> Option<Span> {
410 let span_ext = self.span_ext()?;
411 Some(span_ext.with_lo(span_ext.lo() + BytePos(1)).with_hi(span_ext.hi() - BytePos(1)))
414 /// Returns span encompassing arguments and their surrounding `<>` or `()`
415 pub fn span_ext(&self) -> Option<Span> {
416 Some(self.span_ext).filter(|span| !span.is_empty())
419 pub fn is_empty(&self) -> bool {
424 /// A modifier on a bound, currently this is only used for `?Sized`, where the
425 /// modifier is `Maybe`. Negative bounds should also be handled here.
426 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
427 #[derive(HashStable_Generic)]
428 pub enum TraitBoundModifier {
434 /// The AST represents all type param bounds as types.
435 /// `typeck::collect::compute_bounds` matches these against
436 /// the "special" built-in traits (see `middle::lang_items`) and
437 /// detects `Copy`, `Send` and `Sync`.
438 #[derive(Clone, Debug, HashStable_Generic)]
439 pub enum GenericBound<'hir> {
440 Trait(PolyTraitRef<'hir>, TraitBoundModifier),
441 // FIXME(davidtwco): Introduce `PolyTraitRef::LangItem`
442 LangItemTrait(LangItem, Span, HirId, &'hir GenericArgs<'hir>),
446 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
447 rustc_data_structures::static_assert_size!(GenericBound<'_>, 48);
449 impl GenericBound<'_> {
450 pub fn trait_ref(&self) -> Option<&TraitRef<'_>> {
452 GenericBound::Trait(data, _) => Some(&data.trait_ref),
457 pub fn span(&self) -> Span {
459 GenericBound::Trait(t, ..) => t.span,
460 GenericBound::LangItemTrait(_, span, ..) => *span,
461 GenericBound::Outlives(l) => l.span,
466 pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
468 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
469 pub enum LifetimeParamKind {
470 // Indicates that the lifetime definition was explicitly declared (e.g., in
471 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
474 // Indicates that the lifetime definition was synthetically added
475 // as a result of an in-band lifetime usage (e.g., in
476 // `fn foo(x: &'a u8) -> &'a u8 { x }`).
479 // Indication that the lifetime was elided (e.g., in both cases in
480 // `fn foo(x: &u8) -> &'_ u8 { x }`).
483 // Indication that the lifetime name was somehow in error.
487 #[derive(Debug, HashStable_Generic)]
488 pub enum GenericParamKind<'hir> {
489 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
491 kind: LifetimeParamKind,
494 default: Option<&'hir Ty<'hir>>,
499 /// Optional default value for the const generic param
500 default: Option<AnonConst>,
504 #[derive(Debug, HashStable_Generic)]
505 pub struct GenericParam<'hir> {
508 pub bounds: GenericBounds<'hir>,
510 pub pure_wrt_drop: bool,
511 pub kind: GenericParamKind<'hir>,
514 impl<'hir> GenericParam<'hir> {
515 pub fn bounds_span_for_suggestions(&self) -> Option<Span> {
518 .fold(None, |span: Option<Span>, bound| {
519 // We include bounds that come from a `#[derive(_)]` but point at the user's code,
520 // as we use this method to get a span appropriate for suggestions.
521 if !bound.span().can_be_used_for_suggestions() {
524 let span = span.map(|s| s.to(bound.span())).unwrap_or_else(|| bound.span());
528 .map(|sp| sp.shrink_to_hi())
533 pub struct GenericParamCount {
534 pub lifetimes: usize,
540 /// Represents lifetimes and type parameters attached to a declaration
541 /// of a function, enum, trait, etc.
542 #[derive(Debug, HashStable_Generic)]
543 pub struct Generics<'hir> {
544 pub params: &'hir [GenericParam<'hir>],
545 pub where_clause: WhereClause<'hir>,
549 impl<'hir> Generics<'hir> {
550 pub const fn empty() -> Generics<'hir> {
553 where_clause: WhereClause { predicates: &[], span: DUMMY_SP },
558 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'_>> {
559 for param in self.params {
560 if name == param.name.ident().name {
567 pub fn spans(&self) -> MultiSpan {
568 if self.params.is_empty() {
571 self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
576 /// A where-clause in a definition.
577 #[derive(Debug, HashStable_Generic)]
578 pub struct WhereClause<'hir> {
579 pub predicates: &'hir [WherePredicate<'hir>],
580 // Only valid if predicates aren't empty.
584 impl WhereClause<'_> {
585 pub fn span(&self) -> Option<Span> {
586 if self.predicates.is_empty() { None } else { Some(self.span) }
589 /// The `WhereClause` under normal circumstances points at either the predicates or the empty
590 /// space where the `where` clause should be. Only of use for diagnostic suggestions.
591 pub fn span_for_predicates_or_empty_place(&self) -> Span {
595 /// `Span` where further predicates would be suggested, accounting for trailing commas, like
596 /// in `fn foo<T>(t: T) where T: Foo,` so we don't suggest two trailing commas.
597 pub fn tail_span_for_suggestion(&self) -> Span {
598 let end = self.span_for_predicates_or_empty_place().shrink_to_hi();
599 self.predicates.last().map_or(end, |p| p.span()).shrink_to_hi().to(end)
603 /// A single predicate in a where-clause.
604 #[derive(Debug, HashStable_Generic)]
605 pub enum WherePredicate<'hir> {
606 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
607 BoundPredicate(WhereBoundPredicate<'hir>),
608 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
609 RegionPredicate(WhereRegionPredicate<'hir>),
610 /// An equality predicate (unsupported).
611 EqPredicate(WhereEqPredicate<'hir>),
614 impl<'hir> WherePredicate<'hir> {
615 pub fn span(&self) -> Span {
617 WherePredicate::BoundPredicate(p) => p.span,
618 WherePredicate::RegionPredicate(p) => p.span,
619 WherePredicate::EqPredicate(p) => p.span,
624 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
625 #[derive(Debug, HashStable_Generic)]
626 pub struct WhereBoundPredicate<'hir> {
628 /// Any generics from a `for` binding.
629 pub bound_generic_params: &'hir [GenericParam<'hir>],
630 /// The type being bounded.
631 pub bounded_ty: &'hir Ty<'hir>,
632 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
633 pub bounds: GenericBounds<'hir>,
636 impl<'hir> WhereBoundPredicate<'hir> {
637 /// Returns `true` if `param_def_id` matches the `bounded_ty` of this predicate.
638 pub fn is_param_bound(&self, param_def_id: DefId) -> bool {
639 let TyKind::Path(QPath::Resolved(None, path)) = self.bounded_ty.kind else {
643 Res::Def(DefKind::TyParam, def_id)
644 | Res::SelfTy { trait_: Some(def_id), alias_to: None } => def_id == param_def_id,
650 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
651 #[derive(Debug, HashStable_Generic)]
652 pub struct WhereRegionPredicate<'hir> {
654 pub lifetime: Lifetime,
655 pub bounds: GenericBounds<'hir>,
658 /// An equality predicate (e.g., `T = int`); currently unsupported.
659 #[derive(Debug, HashStable_Generic)]
660 pub struct WhereEqPredicate<'hir> {
663 pub lhs_ty: &'hir Ty<'hir>,
664 pub rhs_ty: &'hir Ty<'hir>,
667 /// HIR node coupled with its parent's id in the same HIR owner.
669 /// The parent is trash when the node is a HIR owner.
670 #[derive(Clone, Debug)]
671 pub struct ParentedNode<'tcx> {
672 pub parent: ItemLocalId,
673 pub node: Node<'tcx>,
676 /// Attributes owned by a HIR owner.
678 pub struct AttributeMap<'tcx> {
679 pub map: SortedMap<ItemLocalId, &'tcx [Attribute]>,
680 pub hash: Fingerprint,
683 impl<'tcx> AttributeMap<'tcx> {
684 pub const EMPTY: &'static AttributeMap<'static> =
685 &AttributeMap { map: SortedMap::new(), hash: Fingerprint::ZERO };
688 pub fn get(&self, id: ItemLocalId) -> &'tcx [Attribute] {
689 self.map.get(&id).copied().unwrap_or(&[])
693 /// Map of all HIR nodes inside the current owner.
694 /// These nodes are mapped by `ItemLocalId` alongside the index of their parent node.
695 /// The HIR tree, including bodies, is pre-hashed.
697 pub struct OwnerNodes<'tcx> {
698 /// Pre-computed hash of the full HIR.
699 pub hash_including_bodies: Fingerprint,
700 /// Pre-computed hash of the item signature, sithout recursing into the body.
701 pub hash_without_bodies: Fingerprint,
702 /// Full HIR for the current owner.
703 // The zeroth node's parent should never be accessed: the owner's parent is computed by the
704 // hir_owner_parent query. It is set to `ItemLocalId::INVALID` to force an ICE if accidentally
706 pub nodes: IndexVec<ItemLocalId, Option<ParentedNode<'tcx>>>,
707 /// Content of local bodies.
708 pub bodies: SortedMap<ItemLocalId, &'tcx Body<'tcx>>,
709 /// Non-owning definitions contained in this owner.
710 pub local_id_to_def_id: SortedMap<ItemLocalId, LocalDefId>,
713 impl<'tcx> OwnerNodes<'tcx> {
714 pub fn node(&self) -> OwnerNode<'tcx> {
715 use rustc_index::vec::Idx;
716 let node = self.nodes[ItemLocalId::new(0)].as_ref().unwrap().node;
717 let node = node.as_owner().unwrap(); // Indexing must ensure it is an OwnerNode.
722 /// Full information resulting from lowering an AST node.
723 #[derive(Debug, HashStable_Generic)]
724 pub struct OwnerInfo<'hir> {
725 /// Contents of the HIR.
726 pub nodes: OwnerNodes<'hir>,
727 /// Map from each nested owner to its parent's local id.
728 pub parenting: FxHashMap<LocalDefId, ItemLocalId>,
729 /// Collected attributes of the HIR nodes.
730 pub attrs: AttributeMap<'hir>,
731 /// Map indicating what traits are in scope for places where this
732 /// is relevant; generated by resolve.
733 pub trait_map: FxHashMap<ItemLocalId, Box<[TraitCandidate]>>,
736 impl<'tcx> OwnerInfo<'tcx> {
738 pub fn node(&self) -> OwnerNode<'tcx> {
743 #[derive(Copy, Clone, Debug, HashStable_Generic)]
744 pub enum MaybeOwner<T> {
747 /// Used as a placeholder for unused LocalDefId.
751 impl<T> MaybeOwner<T> {
752 pub fn as_owner(self) -> Option<T> {
754 MaybeOwner::Owner(i) => Some(i),
755 MaybeOwner::NonOwner(_) | MaybeOwner::Phantom => None,
759 pub fn map<U>(self, f: impl FnOnce(T) -> U) -> MaybeOwner<U> {
761 MaybeOwner::Owner(i) => MaybeOwner::Owner(f(i)),
762 MaybeOwner::NonOwner(hir_id) => MaybeOwner::NonOwner(hir_id),
763 MaybeOwner::Phantom => MaybeOwner::Phantom,
767 pub fn unwrap(self) -> T {
769 MaybeOwner::Owner(i) => i,
770 MaybeOwner::NonOwner(_) | MaybeOwner::Phantom => panic!("Not a HIR owner"),
775 /// The top-level data structure that stores the entire contents of
776 /// the crate currently being compiled.
778 /// For more details, see the [rustc dev guide].
780 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
782 pub struct Crate<'hir> {
783 pub owners: IndexVec<LocalDefId, MaybeOwner<&'hir OwnerInfo<'hir>>>,
784 pub hir_hash: Fingerprint,
787 /// A block of statements `{ .. }`, which may have a label (in this case the
788 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
789 /// the `rules` being anything but `DefaultBlock`.
790 #[derive(Debug, HashStable_Generic)]
791 pub struct Block<'hir> {
792 /// Statements in a block.
793 pub stmts: &'hir [Stmt<'hir>],
794 /// An expression at the end of the block
795 /// without a semicolon, if any.
796 pub expr: Option<&'hir Expr<'hir>>,
797 #[stable_hasher(ignore)]
799 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
800 pub rules: BlockCheckMode,
802 /// If true, then there may exist `break 'a` values that aim to
803 /// break out of this block early.
804 /// Used by `'label: {}` blocks and by `try {}` blocks.
805 pub targeted_by_break: bool,
808 #[derive(Debug, HashStable_Generic)]
809 pub struct Pat<'hir> {
810 #[stable_hasher(ignore)]
812 pub kind: PatKind<'hir>,
814 // Whether to use default binding modes.
815 // At present, this is false only for destructuring assignment.
816 pub default_binding_modes: bool,
819 impl<'hir> Pat<'hir> {
820 // FIXME(#19596) this is a workaround, but there should be a better way
821 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) -> bool {
828 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
829 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
830 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
831 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
832 Slice(before, slice, after) => {
833 before.iter().chain(slice).chain(after.iter()).all(|p| p.walk_short_(it))
838 /// Walk the pattern in left-to-right order,
839 /// short circuiting (with `.all(..)`) if `false` is returned.
841 /// Note that when visiting e.g. `Tuple(ps)`,
842 /// if visiting `ps[0]` returns `false`,
843 /// then `ps[1]` will not be visited.
844 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) -> bool {
845 self.walk_short_(&mut it)
848 // FIXME(#19596) this is a workaround, but there should be a better way
849 fn walk_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) {
856 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
857 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
858 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
859 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
860 Slice(before, slice, after) => {
861 before.iter().chain(slice).chain(after.iter()).for_each(|p| p.walk_(it))
866 /// Walk the pattern in left-to-right order.
868 /// If `it(pat)` returns `false`, the children are not visited.
869 pub fn walk(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) {
873 /// Walk the pattern in left-to-right order.
875 /// If you always want to recurse, prefer this method over `walk`.
876 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
884 /// A single field in a struct pattern.
886 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
887 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
888 /// except `is_shorthand` is true.
889 #[derive(Debug, HashStable_Generic)]
890 pub struct PatField<'hir> {
891 #[stable_hasher(ignore)]
893 /// The identifier for the field.
895 /// The pattern the field is destructured to.
896 pub pat: &'hir Pat<'hir>,
897 pub is_shorthand: bool,
901 /// Explicit binding annotations given in the HIR for a binding. Note
902 /// that this is not the final binding *mode* that we infer after type
904 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
905 pub enum BindingAnnotation {
906 /// No binding annotation given: this means that the final binding mode
907 /// will depend on whether we have skipped through a `&` reference
908 /// when matching. For example, the `x` in `Some(x)` will have binding
909 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
910 /// ultimately be inferred to be by-reference.
912 /// Note that implicit reference skipping is not implemented yet (#42640).
915 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
918 /// Annotated as `ref`, like `ref x`
921 /// Annotated as `ref mut x`.
925 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
931 impl fmt::Display for RangeEnd {
932 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
933 f.write_str(match self {
934 RangeEnd::Included => "..=",
935 RangeEnd::Excluded => "..",
940 #[derive(Debug, HashStable_Generic)]
941 pub enum PatKind<'hir> {
942 /// Represents a wildcard pattern (i.e., `_`).
945 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
946 /// The `HirId` is the canonical ID for the variable being bound,
947 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
948 /// which is the pattern ID of the first `x`.
949 Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
951 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
952 /// The `bool` is `true` in the presence of a `..`.
953 Struct(QPath<'hir>, &'hir [PatField<'hir>], bool),
955 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
956 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
957 /// `0 <= position <= subpats.len()`
958 TupleStruct(QPath<'hir>, &'hir [Pat<'hir>], Option<usize>),
960 /// An or-pattern `A | B | C`.
961 /// Invariant: `pats.len() >= 2`.
962 Or(&'hir [Pat<'hir>]),
964 /// A path pattern for a unit struct/variant or a (maybe-associated) constant.
967 /// A tuple pattern (e.g., `(a, b)`).
968 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
969 /// `0 <= position <= subpats.len()`
970 Tuple(&'hir [Pat<'hir>], Option<usize>),
973 Box(&'hir Pat<'hir>),
975 /// A reference pattern (e.g., `&mut (a, b)`).
976 Ref(&'hir Pat<'hir>, Mutability),
979 Lit(&'hir Expr<'hir>),
981 /// A range pattern (e.g., `1..=2` or `1..2`).
982 Range(Option<&'hir Expr<'hir>>, Option<&'hir Expr<'hir>>, RangeEnd),
984 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
986 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
987 /// If `slice` exists, then `after` can be non-empty.
989 /// The representation for e.g., `[a, b, .., c, d]` is:
991 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
993 Slice(&'hir [Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [Pat<'hir>]),
996 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
998 /// The `+` operator (addition).
1000 /// The `-` operator (subtraction).
1002 /// The `*` operator (multiplication).
1004 /// The `/` operator (division).
1006 /// The `%` operator (modulus).
1008 /// The `&&` operator (logical and).
1010 /// The `||` operator (logical or).
1012 /// The `^` operator (bitwise xor).
1014 /// The `&` operator (bitwise and).
1016 /// The `|` operator (bitwise or).
1018 /// The `<<` operator (shift left).
1020 /// The `>>` operator (shift right).
1022 /// The `==` operator (equality).
1024 /// The `<` operator (less than).
1026 /// The `<=` operator (less than or equal to).
1028 /// The `!=` operator (not equal to).
1030 /// The `>=` operator (greater than or equal to).
1032 /// The `>` operator (greater than).
1037 pub fn as_str(self) -> &'static str {
1039 BinOpKind::Add => "+",
1040 BinOpKind::Sub => "-",
1041 BinOpKind::Mul => "*",
1042 BinOpKind::Div => "/",
1043 BinOpKind::Rem => "%",
1044 BinOpKind::And => "&&",
1045 BinOpKind::Or => "||",
1046 BinOpKind::BitXor => "^",
1047 BinOpKind::BitAnd => "&",
1048 BinOpKind::BitOr => "|",
1049 BinOpKind::Shl => "<<",
1050 BinOpKind::Shr => ">>",
1051 BinOpKind::Eq => "==",
1052 BinOpKind::Lt => "<",
1053 BinOpKind::Le => "<=",
1054 BinOpKind::Ne => "!=",
1055 BinOpKind::Ge => ">=",
1056 BinOpKind::Gt => ">",
1060 pub fn is_lazy(self) -> bool {
1061 matches!(self, BinOpKind::And | BinOpKind::Or)
1064 pub fn is_shift(self) -> bool {
1065 matches!(self, BinOpKind::Shl | BinOpKind::Shr)
1068 pub fn is_comparison(self) -> bool {
1075 | BinOpKind::Ge => true,
1087 | BinOpKind::Shr => false,
1091 /// Returns `true` if the binary operator takes its arguments by value.
1092 pub fn is_by_value(self) -> bool {
1093 !self.is_comparison()
1097 impl Into<ast::BinOpKind> for BinOpKind {
1098 fn into(self) -> ast::BinOpKind {
1100 BinOpKind::Add => ast::BinOpKind::Add,
1101 BinOpKind::Sub => ast::BinOpKind::Sub,
1102 BinOpKind::Mul => ast::BinOpKind::Mul,
1103 BinOpKind::Div => ast::BinOpKind::Div,
1104 BinOpKind::Rem => ast::BinOpKind::Rem,
1105 BinOpKind::And => ast::BinOpKind::And,
1106 BinOpKind::Or => ast::BinOpKind::Or,
1107 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1108 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1109 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1110 BinOpKind::Shl => ast::BinOpKind::Shl,
1111 BinOpKind::Shr => ast::BinOpKind::Shr,
1112 BinOpKind::Eq => ast::BinOpKind::Eq,
1113 BinOpKind::Lt => ast::BinOpKind::Lt,
1114 BinOpKind::Le => ast::BinOpKind::Le,
1115 BinOpKind::Ne => ast::BinOpKind::Ne,
1116 BinOpKind::Ge => ast::BinOpKind::Ge,
1117 BinOpKind::Gt => ast::BinOpKind::Gt,
1122 pub type BinOp = Spanned<BinOpKind>;
1124 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1126 /// The `*` operator (deferencing).
1128 /// The `!` operator (logical negation).
1130 /// The `-` operator (negation).
1135 pub fn as_str(self) -> &'static str {
1143 /// Returns `true` if the unary operator takes its argument by value.
1144 pub fn is_by_value(self) -> bool {
1145 matches!(self, Self::Neg | Self::Not)
1150 #[derive(Debug, HashStable_Generic)]
1151 pub struct Stmt<'hir> {
1153 pub kind: StmtKind<'hir>,
1157 /// The contents of a statement.
1158 #[derive(Debug, HashStable_Generic)]
1159 pub enum StmtKind<'hir> {
1160 /// A local (`let`) binding.
1161 Local(&'hir Local<'hir>),
1163 /// An item binding.
1166 /// An expression without a trailing semi-colon (must have unit type).
1167 Expr(&'hir Expr<'hir>),
1169 /// An expression with a trailing semi-colon (may have any type).
1170 Semi(&'hir Expr<'hir>),
1173 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1174 #[derive(Debug, HashStable_Generic)]
1175 pub struct Local<'hir> {
1176 pub pat: &'hir Pat<'hir>,
1177 /// Type annotation, if any (otherwise the type will be inferred).
1178 pub ty: Option<&'hir Ty<'hir>>,
1179 /// Initializer expression to set the value, if any.
1180 pub init: Option<&'hir Expr<'hir>>,
1183 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1184 /// desugaring. Otherwise will be `Normal`.
1185 pub source: LocalSource,
1188 /// Represents a single arm of a `match` expression, e.g.
1189 /// `<pat> (if <guard>) => <body>`.
1190 #[derive(Debug, HashStable_Generic)]
1191 pub struct Arm<'hir> {
1192 #[stable_hasher(ignore)]
1195 /// If this pattern and the optional guard matches, then `body` is evaluated.
1196 pub pat: &'hir Pat<'hir>,
1197 /// Optional guard clause.
1198 pub guard: Option<Guard<'hir>>,
1199 /// The expression the arm evaluates to if this arm matches.
1200 pub body: &'hir Expr<'hir>,
1203 /// Represents a `let <pat>[: <ty>] = <expr>` expression (not a Local), occurring in an `if-let` or
1204 /// `let-else`, evaluating to a boolean. Typically the pattern is refutable.
1206 /// In an if-let, imagine it as `if (let <pat> = <expr>) { ... }`; in a let-else, it is part of the
1207 /// desugaring to if-let. Only let-else supports the type annotation at present.
1208 #[derive(Debug, HashStable_Generic)]
1209 pub struct Let<'hir> {
1212 pub pat: &'hir Pat<'hir>,
1213 pub ty: Option<&'hir Ty<'hir>>,
1214 pub init: &'hir Expr<'hir>,
1217 #[derive(Debug, HashStable_Generic)]
1218 pub enum Guard<'hir> {
1219 If(&'hir Expr<'hir>),
1220 // FIXME use hir::Let for this.
1221 IfLet(&'hir Pat<'hir>, &'hir Expr<'hir>),
1224 #[derive(Debug, HashStable_Generic)]
1225 pub struct ExprField<'hir> {
1226 #[stable_hasher(ignore)]
1229 pub expr: &'hir Expr<'hir>,
1231 pub is_shorthand: bool,
1234 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1235 pub enum BlockCheckMode {
1237 UnsafeBlock(UnsafeSource),
1240 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1241 pub enum UnsafeSource {
1246 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
1251 /// The body of a function, closure, or constant value. In the case of
1252 /// a function, the body contains not only the function body itself
1253 /// (which is an expression), but also the argument patterns, since
1254 /// those are something that the caller doesn't really care about.
1259 /// fn foo((x, y): (u32, u32)) -> u32 {
1264 /// Here, the `Body` associated with `foo()` would contain:
1266 /// - an `params` array containing the `(x, y)` pattern
1267 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1268 /// - `generator_kind` would be `None`
1270 /// All bodies have an **owner**, which can be accessed via the HIR
1271 /// map using `body_owner_def_id()`.
1273 pub struct Body<'hir> {
1274 pub params: &'hir [Param<'hir>],
1275 pub value: Expr<'hir>,
1276 pub generator_kind: Option<GeneratorKind>,
1279 impl<'hir> Body<'hir> {
1280 pub fn id(&self) -> BodyId {
1281 BodyId { hir_id: self.value.hir_id }
1284 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1289 /// The type of source expression that caused this generator to be created.
1302 pub enum GeneratorKind {
1303 /// An explicit `async` block or the body of an async function.
1304 Async(AsyncGeneratorKind),
1306 /// A generator literal created via a `yield` inside a closure.
1310 impl fmt::Display for GeneratorKind {
1311 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1313 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1314 GeneratorKind::Gen => f.write_str("generator"),
1319 impl GeneratorKind {
1320 pub fn descr(&self) -> &'static str {
1322 GeneratorKind::Async(ask) => ask.descr(),
1323 GeneratorKind::Gen => "generator",
1328 /// In the case of a generator created as part of an async construct,
1329 /// which kind of async construct caused it to be created?
1331 /// This helps error messages but is also used to drive coercions in
1332 /// type-checking (see #60424).
1345 pub enum AsyncGeneratorKind {
1346 /// An explicit `async` block written by the user.
1349 /// An explicit `async` block written by the user.
1352 /// The `async` block generated as the body of an async function.
1356 impl fmt::Display for AsyncGeneratorKind {
1357 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1358 f.write_str(match self {
1359 AsyncGeneratorKind::Block => "`async` block",
1360 AsyncGeneratorKind::Closure => "`async` closure body",
1361 AsyncGeneratorKind::Fn => "`async fn` body",
1366 impl AsyncGeneratorKind {
1367 pub fn descr(&self) -> &'static str {
1369 AsyncGeneratorKind::Block => "`async` block",
1370 AsyncGeneratorKind::Closure => "`async` closure body",
1371 AsyncGeneratorKind::Fn => "`async fn` body",
1376 #[derive(Copy, Clone, Debug)]
1377 pub enum BodyOwnerKind {
1378 /// Functions and methods.
1384 /// Constants and associated constants.
1387 /// Initializer of a `static` item.
1391 impl BodyOwnerKind {
1392 pub fn is_fn_or_closure(self) -> bool {
1394 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1395 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1400 /// The kind of an item that requires const-checking.
1401 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1402 pub enum ConstContext {
1406 /// A `static` or `static mut`.
1409 /// A `const`, associated `const`, or other const context.
1411 /// Other contexts include:
1412 /// - Array length expressions
1413 /// - Enum discriminants
1414 /// - Const generics
1416 /// For the most part, other contexts are treated just like a regular `const`, so they are
1417 /// lumped into the same category.
1422 /// A description of this const context that can appear between backticks in an error message.
1424 /// E.g. `const` or `static mut`.
1425 pub fn keyword_name(self) -> &'static str {
1427 Self::Const => "const",
1428 Self::Static(Mutability::Not) => "static",
1429 Self::Static(Mutability::Mut) => "static mut",
1430 Self::ConstFn => "const fn",
1435 /// A colloquial, trivially pluralizable description of this const context for use in error
1437 impl fmt::Display for ConstContext {
1438 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1440 Self::Const => write!(f, "constant"),
1441 Self::Static(_) => write!(f, "static"),
1442 Self::ConstFn => write!(f, "constant function"),
1448 pub type Lit = Spanned<LitKind>;
1450 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1457 pub fn hir_id(&self) -> HirId {
1459 &ArrayLen::Infer(hir_id, _) | &ArrayLen::Body(AnonConst { hir_id, body: _ }) => hir_id,
1464 /// A constant (expression) that's not an item or associated item,
1465 /// but needs its own `DefId` for type-checking, const-eval, etc.
1466 /// These are usually found nested inside types (e.g., array lengths)
1467 /// or expressions (e.g., repeat counts), and also used to define
1468 /// explicit discriminant values for enum variants.
1470 /// You can check if this anon const is a default in a const param
1471 /// `const N: usize = { ... }` with `tcx.hir().opt_const_param_default_param_hir_id(..)`
1472 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1473 pub struct AnonConst {
1480 pub struct Expr<'hir> {
1482 pub kind: ExprKind<'hir>,
1487 pub fn precedence(&self) -> ExprPrecedence {
1489 ExprKind::Box(_) => ExprPrecedence::Box,
1490 ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1491 ExprKind::Array(_) => ExprPrecedence::Array,
1492 ExprKind::Call(..) => ExprPrecedence::Call,
1493 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1494 ExprKind::Tup(_) => ExprPrecedence::Tup,
1495 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1496 ExprKind::Unary(..) => ExprPrecedence::Unary,
1497 ExprKind::Lit(_) => ExprPrecedence::Lit,
1498 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1499 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1500 ExprKind::If(..) => ExprPrecedence::If,
1501 ExprKind::Let(..) => ExprPrecedence::Let,
1502 ExprKind::Loop(..) => ExprPrecedence::Loop,
1503 ExprKind::Match(..) => ExprPrecedence::Match,
1504 ExprKind::Closure(..) => ExprPrecedence::Closure,
1505 ExprKind::Block(..) => ExprPrecedence::Block,
1506 ExprKind::Assign(..) => ExprPrecedence::Assign,
1507 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1508 ExprKind::Field(..) => ExprPrecedence::Field,
1509 ExprKind::Index(..) => ExprPrecedence::Index,
1510 ExprKind::Path(..) => ExprPrecedence::Path,
1511 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1512 ExprKind::Break(..) => ExprPrecedence::Break,
1513 ExprKind::Continue(..) => ExprPrecedence::Continue,
1514 ExprKind::Ret(..) => ExprPrecedence::Ret,
1515 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1516 ExprKind::Struct(..) => ExprPrecedence::Struct,
1517 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1518 ExprKind::Yield(..) => ExprPrecedence::Yield,
1519 ExprKind::Err => ExprPrecedence::Err,
1523 // Whether this looks like a place expr, without checking for deref
1525 // This will return `true` in some potentially surprising cases such as
1526 // `CONSTANT.field`.
1527 pub fn is_syntactic_place_expr(&self) -> bool {
1528 self.is_place_expr(|_| true)
1531 /// Whether this is a place expression.
1533 /// `allow_projections_from` should return `true` if indexing a field or index expression based
1534 /// on the given expression should be considered a place expression.
1535 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1537 ExprKind::Path(QPath::Resolved(_, ref path)) => {
1538 matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static, _) | Res::Err)
1541 // Type ascription inherits its place expression kind from its
1543 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1544 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1546 ExprKind::Unary(UnOp::Deref, _) => true,
1548 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1549 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1552 // Lang item paths cannot currently be local variables or statics.
1553 ExprKind::Path(QPath::LangItem(..)) => false,
1555 // Partially qualified paths in expressions can only legally
1556 // refer to associated items which are always rvalues.
1557 ExprKind::Path(QPath::TypeRelative(..))
1558 | ExprKind::Call(..)
1559 | ExprKind::MethodCall(..)
1560 | ExprKind::Struct(..)
1563 | ExprKind::Match(..)
1564 | ExprKind::Closure(..)
1565 | ExprKind::Block(..)
1566 | ExprKind::Repeat(..)
1567 | ExprKind::Array(..)
1568 | ExprKind::Break(..)
1569 | ExprKind::Continue(..)
1572 | ExprKind::Loop(..)
1573 | ExprKind::Assign(..)
1574 | ExprKind::InlineAsm(..)
1575 | ExprKind::AssignOp(..)
1577 | ExprKind::ConstBlock(..)
1578 | ExprKind::Unary(..)
1580 | ExprKind::AddrOf(..)
1581 | ExprKind::Binary(..)
1582 | ExprKind::Yield(..)
1583 | ExprKind::Cast(..)
1584 | ExprKind::DropTemps(..)
1585 | ExprKind::Err => false,
1589 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1590 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1591 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1592 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1593 /// beyond remembering to call this function before doing analysis on it.
1594 pub fn peel_drop_temps(&self) -> &Self {
1595 let mut expr = self;
1596 while let ExprKind::DropTemps(inner) = &expr.kind {
1602 pub fn peel_blocks(&self) -> &Self {
1603 let mut expr = self;
1604 while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind {
1610 pub fn can_have_side_effects(&self) -> bool {
1611 match self.peel_drop_temps().kind {
1612 ExprKind::Path(_) | ExprKind::Lit(_) => false,
1613 ExprKind::Type(base, _)
1614 | ExprKind::Unary(_, base)
1615 | ExprKind::Field(base, _)
1616 | ExprKind::Index(base, _)
1617 | ExprKind::AddrOf(.., base)
1618 | ExprKind::Cast(base, _) => {
1619 // This isn't exactly true for `Index` and all `Unnary`, but we are using this
1620 // method exclusively for diagnostics and there's a *cultural* pressure against
1621 // them being used only for its side-effects.
1622 base.can_have_side_effects()
1624 ExprKind::Struct(_, fields, init) => fields
1626 .map(|field| field.expr)
1627 .chain(init.into_iter())
1628 .all(|e| e.can_have_side_effects()),
1630 ExprKind::Array(args)
1631 | ExprKind::Tup(args)
1635 ExprKind::Path(QPath::Resolved(
1637 Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. },
1642 ) => args.iter().all(|arg| arg.can_have_side_effects()),
1644 | ExprKind::Match(..)
1645 | ExprKind::MethodCall(..)
1646 | ExprKind::Call(..)
1647 | ExprKind::Closure(..)
1648 | ExprKind::Block(..)
1649 | ExprKind::Repeat(..)
1650 | ExprKind::Break(..)
1651 | ExprKind::Continue(..)
1654 | ExprKind::Loop(..)
1655 | ExprKind::Assign(..)
1656 | ExprKind::InlineAsm(..)
1657 | ExprKind::AssignOp(..)
1658 | ExprKind::ConstBlock(..)
1660 | ExprKind::Binary(..)
1661 | ExprKind::Yield(..)
1662 | ExprKind::DropTemps(..)
1663 | ExprKind::Err => true,
1668 /// Checks if the specified expression is a built-in range literal.
1669 /// (See: `LoweringContext::lower_expr()`).
1670 pub fn is_range_literal(expr: &Expr<'_>) -> bool {
1672 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1673 ExprKind::Struct(ref qpath, _, _) => matches!(
1678 | LangItem::RangeFrom
1679 | LangItem::RangeFull
1680 | LangItem::RangeToInclusive,
1685 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1686 ExprKind::Call(ref func, _) => {
1687 matches!(func.kind, ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, ..)))
1694 #[derive(Debug, HashStable_Generic)]
1695 pub enum ExprKind<'hir> {
1696 /// A `box x` expression.
1697 Box(&'hir Expr<'hir>),
1698 /// Allow anonymous constants from an inline `const` block
1699 ConstBlock(AnonConst),
1700 /// An array (e.g., `[a, b, c, d]`).
1701 Array(&'hir [Expr<'hir>]),
1702 /// A function call.
1704 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1705 /// and the second field is the list of arguments.
1706 /// This also represents calling the constructor of
1707 /// tuple-like ADTs such as tuple structs and enum variants.
1708 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1709 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1711 /// The `PathSegment` represents the method name and its generic arguments
1712 /// (within the angle brackets).
1713 /// The first element of the `&[Expr]` is the expression that evaluates
1714 /// to the object on which the method is being called on (the receiver),
1715 /// and the remaining elements are the rest of the arguments.
1716 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1717 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d], span)`.
1718 /// The final `Span` represents the span of the function and arguments
1719 /// (e.g. `foo::<Bar, Baz>(a, b, c, d)` in `x.foo::<Bar, Baz>(a, b, c, d)`
1721 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1722 /// the `hir_id` of the `MethodCall` node itself.
1724 /// [`type_dependent_def_id`]: ../ty/struct.TypeckResults.html#method.type_dependent_def_id
1725 MethodCall(&'hir PathSegment<'hir>, &'hir [Expr<'hir>], Span),
1726 /// A tuple (e.g., `(a, b, c, d)`).
1727 Tup(&'hir [Expr<'hir>]),
1728 /// A binary operation (e.g., `a + b`, `a * b`).
1729 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1730 /// A unary operation (e.g., `!x`, `*x`).
1731 Unary(UnOp, &'hir Expr<'hir>),
1732 /// A literal (e.g., `1`, `"foo"`).
1734 /// A cast (e.g., `foo as f64`).
1735 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1736 /// A type reference (e.g., `Foo`).
1737 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1738 /// Wraps the expression in a terminating scope.
1739 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1741 /// This construct only exists to tweak the drop order in HIR lowering.
1742 /// An example of that is the desugaring of `for` loops.
1743 DropTemps(&'hir Expr<'hir>),
1744 /// A `let $pat = $expr` expression.
1746 /// These are not `Local` and only occur as expressions.
1747 /// The `let Some(x) = foo()` in `if let Some(x) = foo()` is an example of `Let(..)`.
1748 Let(&'hir Let<'hir>),
1749 /// An `if` block, with an optional else block.
1751 /// I.e., `if <expr> { <expr> } else { <expr> }`.
1752 If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
1753 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1755 /// I.e., `'label: loop { <block> }`.
1757 /// The `Span` is the loop header (`for x in y`/`while let pat = expr`).
1758 Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span),
1759 /// A `match` block, with a source that indicates whether or not it is
1760 /// the result of a desugaring, and if so, which kind.
1761 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1762 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1764 /// The `Span` is the argument block `|...|`.
1766 /// This may also be a generator literal or an `async block` as indicated by the
1767 /// `Option<Movability>`.
1768 Closure(CaptureBy, &'hir FnDecl<'hir>, BodyId, Span, Option<Movability>),
1769 /// A block (e.g., `'label: { ... }`).
1770 Block(&'hir Block<'hir>, Option<Label>),
1772 /// An assignment (e.g., `a = foo()`).
1773 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1774 /// An assignment with an operator.
1777 AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1778 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1779 Field(&'hir Expr<'hir>, Ident),
1780 /// An indexing operation (`foo[2]`).
1781 Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1783 /// Path to a definition, possibly containing lifetime or type parameters.
1786 /// A referencing operation (i.e., `&a` or `&mut a`).
1787 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1788 /// A `break`, with an optional label to break.
1789 Break(Destination, Option<&'hir Expr<'hir>>),
1790 /// A `continue`, with an optional label.
1791 Continue(Destination),
1792 /// A `return`, with an optional value to be returned.
1793 Ret(Option<&'hir Expr<'hir>>),
1795 /// Inline assembly (from `asm!`), with its outputs and inputs.
1796 InlineAsm(&'hir InlineAsm<'hir>),
1798 /// A struct or struct-like variant literal expression.
1800 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1801 /// where `base` is the `Option<Expr>`.
1802 Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], Option<&'hir Expr<'hir>>),
1804 /// An array literal constructed from one repeated element.
1806 /// E.g., `[1; 5]`. The first expression is the element
1807 /// to be repeated; the second is the number of times to repeat it.
1808 Repeat(&'hir Expr<'hir>, ArrayLen),
1810 /// A suspension point for generators (i.e., `yield <expr>`).
1811 Yield(&'hir Expr<'hir>, YieldSource),
1813 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1817 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1819 /// To resolve the path to a `DefId`, call [`qpath_res`].
1821 /// [`qpath_res`]: ../rustc_middle/ty/struct.TypeckResults.html#method.qpath_res
1822 #[derive(Debug, HashStable_Generic)]
1823 pub enum QPath<'hir> {
1824 /// Path to a definition, optionally "fully-qualified" with a `Self`
1825 /// type, if the path points to an associated item in a trait.
1827 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1828 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1829 /// even though they both have the same two-segment `Clone::clone` `Path`.
1830 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
1832 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1833 /// Will be resolved by type-checking to an associated item.
1835 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1836 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1837 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1838 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
1840 /// Reference to a `#[lang = "foo"]` item. `HirId` of the inner expr.
1841 LangItem(LangItem, Span, Option<HirId>),
1844 impl<'hir> QPath<'hir> {
1845 /// Returns the span of this `QPath`.
1846 pub fn span(&self) -> Span {
1848 QPath::Resolved(_, path) => path.span,
1849 QPath::TypeRelative(qself, ps) => qself.span.to(ps.ident.span),
1850 QPath::LangItem(_, span, _) => span,
1854 /// Returns the span of the qself of this `QPath`. For example, `()` in
1855 /// `<() as Trait>::method`.
1856 pub fn qself_span(&self) -> Span {
1858 QPath::Resolved(_, path) => path.span,
1859 QPath::TypeRelative(qself, _) => qself.span,
1860 QPath::LangItem(_, span, _) => span,
1864 /// Returns the span of the last segment of this `QPath`. For example, `method` in
1865 /// `<() as Trait>::method`.
1866 pub fn last_segment_span(&self) -> Span {
1868 QPath::Resolved(_, path) => path.segments.last().unwrap().ident.span,
1869 QPath::TypeRelative(_, segment) => segment.ident.span,
1870 QPath::LangItem(_, span, _) => span,
1875 /// Hints at the original code for a let statement.
1876 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1877 pub enum LocalSource {
1878 /// A `match _ { .. }`.
1880 /// When lowering async functions, we create locals within the `async move` so that
1881 /// all parameters are dropped after the future is polled.
1883 /// ```ignore (pseudo-Rust)
1884 /// async fn foo(<pattern> @ x: Type) {
1886 /// let <pattern> = x;
1891 /// A desugared `<expr>.await`.
1893 /// A desugared `expr = expr`, where the LHS is a tuple, struct or array.
1894 /// The span is that of the `=` sign.
1895 AssignDesugar(Span),
1898 /// Hints at the original code for a `match _ { .. }`.
1899 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
1900 #[derive(HashStable_Generic)]
1901 pub enum MatchSource {
1902 /// A `match _ { .. }`.
1904 /// A desugared `for _ in _ { .. }` loop.
1906 /// A desugared `?` operator.
1908 /// A desugared `<expr>.await`.
1914 pub const fn name(self) -> &'static str {
1918 ForLoopDesugar => "for",
1920 AwaitDesugar => ".await",
1925 /// The loop type that yielded an `ExprKind::Loop`.
1926 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1927 pub enum LoopSource {
1928 /// A `loop { .. }` loop.
1930 /// A `while _ { .. }` loop.
1932 /// A `for _ in _ { .. }` loop.
1937 pub fn name(self) -> &'static str {
1939 LoopSource::Loop => "loop",
1940 LoopSource::While => "while",
1941 LoopSource::ForLoop => "for",
1946 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1947 pub enum LoopIdError {
1949 UnlabeledCfInWhileCondition,
1953 impl fmt::Display for LoopIdError {
1954 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1955 f.write_str(match self {
1956 LoopIdError::OutsideLoopScope => "not inside loop scope",
1957 LoopIdError::UnlabeledCfInWhileCondition => {
1958 "unlabeled control flow (break or continue) in while condition"
1960 LoopIdError::UnresolvedLabel => "label not found",
1965 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1966 pub struct Destination {
1967 // This is `Some(_)` iff there is an explicit user-specified `label
1968 pub label: Option<Label>,
1970 // These errors are caught and then reported during the diagnostics pass in
1971 // librustc_passes/loops.rs
1972 pub target_id: Result<HirId, LoopIdError>,
1975 /// The yield kind that caused an `ExprKind::Yield`.
1976 #[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
1977 pub enum YieldSource {
1978 /// An `<expr>.await`.
1979 Await { expr: Option<HirId> },
1980 /// A plain `yield`.
1985 pub fn is_await(&self) -> bool {
1987 YieldSource::Await { .. } => true,
1988 YieldSource::Yield => false,
1993 impl fmt::Display for YieldSource {
1994 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1995 f.write_str(match self {
1996 YieldSource::Await { .. } => "`await`",
1997 YieldSource::Yield => "`yield`",
2002 impl From<GeneratorKind> for YieldSource {
2003 fn from(kind: GeneratorKind) -> Self {
2005 // Guess based on the kind of the current generator.
2006 GeneratorKind::Gen => Self::Yield,
2007 GeneratorKind::Async(_) => Self::Await { expr: None },
2012 // N.B., if you change this, you'll probably want to change the corresponding
2013 // type structure in middle/ty.rs as well.
2014 #[derive(Debug, HashStable_Generic)]
2015 pub struct MutTy<'hir> {
2016 pub ty: &'hir Ty<'hir>,
2017 pub mutbl: Mutability,
2020 /// Represents a function's signature in a trait declaration,
2021 /// trait implementation, or a free function.
2022 #[derive(Debug, HashStable_Generic)]
2023 pub struct FnSig<'hir> {
2024 pub header: FnHeader,
2025 pub decl: &'hir FnDecl<'hir>,
2029 // The bodies for items are stored "out of line", in a separate
2030 // hashmap in the `Crate`. Here we just record the hir-id of the item
2031 // so it can fetched later.
2032 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug)]
2033 pub struct TraitItemId {
2034 pub def_id: LocalDefId,
2039 pub fn hir_id(&self) -> HirId {
2040 // Items are always HIR owners.
2041 HirId::make_owner(self.def_id)
2045 /// Represents an item declaration within a trait declaration,
2046 /// possibly including a default implementation. A trait item is
2047 /// either required (meaning it doesn't have an implementation, just a
2048 /// signature) or provided (meaning it has a default implementation).
2050 pub struct TraitItem<'hir> {
2052 pub def_id: LocalDefId,
2053 pub generics: Generics<'hir>,
2054 pub kind: TraitItemKind<'hir>,
2058 impl TraitItem<'_> {
2060 pub fn hir_id(&self) -> HirId {
2061 // Items are always HIR owners.
2062 HirId::make_owner(self.def_id)
2065 pub fn trait_item_id(&self) -> TraitItemId {
2066 TraitItemId { def_id: self.def_id }
2070 /// Represents a trait method's body (or just argument names).
2071 #[derive(Encodable, Debug, HashStable_Generic)]
2072 pub enum TraitFn<'hir> {
2073 /// No default body in the trait, just a signature.
2074 Required(&'hir [Ident]),
2076 /// Both signature and body are provided in the trait.
2080 /// Represents a trait method or associated constant or type
2081 #[derive(Debug, HashStable_Generic)]
2082 pub enum TraitItemKind<'hir> {
2083 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
2084 Const(&'hir Ty<'hir>, Option<BodyId>),
2085 /// An associated function with an optional body.
2086 Fn(FnSig<'hir>, TraitFn<'hir>),
2087 /// An associated type with (possibly empty) bounds and optional concrete
2089 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
2092 // The bodies for items are stored "out of line", in a separate
2093 // hashmap in the `Crate`. Here we just record the hir-id of the item
2094 // so it can fetched later.
2095 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug)]
2096 pub struct ImplItemId {
2097 pub def_id: LocalDefId,
2102 pub fn hir_id(&self) -> HirId {
2103 // Items are always HIR owners.
2104 HirId::make_owner(self.def_id)
2108 /// Represents anything within an `impl` block.
2110 pub struct ImplItem<'hir> {
2112 pub def_id: LocalDefId,
2113 pub vis: Visibility<'hir>,
2114 pub generics: Generics<'hir>,
2115 pub kind: ImplItemKind<'hir>,
2121 pub fn hir_id(&self) -> HirId {
2122 // Items are always HIR owners.
2123 HirId::make_owner(self.def_id)
2126 pub fn impl_item_id(&self) -> ImplItemId {
2127 ImplItemId { def_id: self.def_id }
2131 /// Represents various kinds of content within an `impl`.
2132 #[derive(Debug, HashStable_Generic)]
2133 pub enum ImplItemKind<'hir> {
2134 /// An associated constant of the given type, set to the constant result
2135 /// of the expression.
2136 Const(&'hir Ty<'hir>, BodyId),
2137 /// An associated function implementation with the given signature and body.
2138 Fn(FnSig<'hir>, BodyId),
2139 /// An associated type.
2140 TyAlias(&'hir Ty<'hir>),
2143 // The name of the associated type for `Fn` return types.
2144 pub const FN_OUTPUT_NAME: Symbol = sym::Output;
2146 /// Bind a type to an associated type (i.e., `A = Foo`).
2148 /// Bindings like `A: Debug` are represented as a special type `A =
2149 /// $::Debug` that is understood by the astconv code.
2151 /// FIXME(alexreg): why have a separate type for the binding case,
2152 /// wouldn't it be better to make the `ty` field an enum like the
2156 /// enum TypeBindingKind {
2161 #[derive(Debug, HashStable_Generic)]
2162 pub struct TypeBinding<'hir> {
2165 pub gen_args: &'hir GenericArgs<'hir>,
2166 pub kind: TypeBindingKind<'hir>,
2170 #[derive(Debug, HashStable_Generic)]
2171 pub enum Term<'hir> {
2176 impl<'hir> From<&'hir Ty<'hir>> for Term<'hir> {
2177 fn from(ty: &'hir Ty<'hir>) -> Self {
2182 impl<'hir> From<AnonConst> for Term<'hir> {
2183 fn from(c: AnonConst) -> Self {
2188 // Represents the two kinds of type bindings.
2189 #[derive(Debug, HashStable_Generic)]
2190 pub enum TypeBindingKind<'hir> {
2191 /// E.g., `Foo<Bar: Send>`.
2192 Constraint { bounds: &'hir [GenericBound<'hir>] },
2193 /// E.g., `Foo<Bar = ()>`, `Foo<Bar = ()>`
2194 Equality { term: Term<'hir> },
2197 impl TypeBinding<'_> {
2198 pub fn ty(&self) -> &Ty<'_> {
2200 TypeBindingKind::Equality { term: Term::Ty(ref ty) } => ty,
2201 _ => panic!("expected equality type binding for parenthesized generic args"),
2204 pub fn opt_const(&self) -> Option<&'_ AnonConst> {
2206 TypeBindingKind::Equality { term: Term::Const(ref c) } => Some(c),
2213 pub struct Ty<'hir> {
2215 pub kind: TyKind<'hir>,
2219 /// Not represented directly in the AST; referred to by name through a `ty_path`.
2220 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
2221 #[derive(HashStable_Generic)]
2232 /// All of the primitive types
2233 pub const ALL: [Self; 17] = [
2234 // any changes here should also be reflected in `PrimTy::from_name`
2235 Self::Int(IntTy::I8),
2236 Self::Int(IntTy::I16),
2237 Self::Int(IntTy::I32),
2238 Self::Int(IntTy::I64),
2239 Self::Int(IntTy::I128),
2240 Self::Int(IntTy::Isize),
2241 Self::Uint(UintTy::U8),
2242 Self::Uint(UintTy::U16),
2243 Self::Uint(UintTy::U32),
2244 Self::Uint(UintTy::U64),
2245 Self::Uint(UintTy::U128),
2246 Self::Uint(UintTy::Usize),
2247 Self::Float(FloatTy::F32),
2248 Self::Float(FloatTy::F64),
2254 /// Like [`PrimTy::name`], but returns a &str instead of a symbol.
2257 pub fn name_str(self) -> &'static str {
2259 PrimTy::Int(i) => i.name_str(),
2260 PrimTy::Uint(u) => u.name_str(),
2261 PrimTy::Float(f) => f.name_str(),
2262 PrimTy::Str => "str",
2263 PrimTy::Bool => "bool",
2264 PrimTy::Char => "char",
2268 pub fn name(self) -> Symbol {
2270 PrimTy::Int(i) => i.name(),
2271 PrimTy::Uint(u) => u.name(),
2272 PrimTy::Float(f) => f.name(),
2273 PrimTy::Str => sym::str,
2274 PrimTy::Bool => sym::bool,
2275 PrimTy::Char => sym::char,
2279 /// Returns the matching `PrimTy` for a `Symbol` such as "str" or "i32".
2280 /// Returns `None` if no matching type is found.
2281 pub fn from_name(name: Symbol) -> Option<Self> {
2282 let ty = match name {
2283 // any changes here should also be reflected in `PrimTy::ALL`
2284 sym::i8 => Self::Int(IntTy::I8),
2285 sym::i16 => Self::Int(IntTy::I16),
2286 sym::i32 => Self::Int(IntTy::I32),
2287 sym::i64 => Self::Int(IntTy::I64),
2288 sym::i128 => Self::Int(IntTy::I128),
2289 sym::isize => Self::Int(IntTy::Isize),
2290 sym::u8 => Self::Uint(UintTy::U8),
2291 sym::u16 => Self::Uint(UintTy::U16),
2292 sym::u32 => Self::Uint(UintTy::U32),
2293 sym::u64 => Self::Uint(UintTy::U64),
2294 sym::u128 => Self::Uint(UintTy::U128),
2295 sym::usize => Self::Uint(UintTy::Usize),
2296 sym::f32 => Self::Float(FloatTy::F32),
2297 sym::f64 => Self::Float(FloatTy::F64),
2298 sym::bool => Self::Bool,
2299 sym::char => Self::Char,
2300 sym::str => Self::Str,
2307 #[derive(Debug, HashStable_Generic)]
2308 pub struct BareFnTy<'hir> {
2309 pub unsafety: Unsafety,
2311 pub generic_params: &'hir [GenericParam<'hir>],
2312 pub decl: &'hir FnDecl<'hir>,
2313 pub param_names: &'hir [Ident],
2316 #[derive(Debug, HashStable_Generic)]
2317 pub struct OpaqueTy<'hir> {
2318 pub generics: Generics<'hir>,
2319 pub bounds: GenericBounds<'hir>,
2320 pub origin: OpaqueTyOrigin,
2323 /// From whence the opaque type came.
2324 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2325 pub enum OpaqueTyOrigin {
2327 FnReturn(LocalDefId),
2329 AsyncFn(LocalDefId),
2330 /// type aliases: `type Foo = impl Trait;`
2334 /// The various kinds of types recognized by the compiler.
2335 #[derive(Debug, HashStable_Generic)]
2336 pub enum TyKind<'hir> {
2337 /// A variable length slice (i.e., `[T]`).
2338 Slice(&'hir Ty<'hir>),
2339 /// A fixed length array (i.e., `[T; n]`).
2340 Array(&'hir Ty<'hir>, ArrayLen),
2341 /// A raw pointer (i.e., `*const T` or `*mut T`).
2343 /// A reference (i.e., `&'a T` or `&'a mut T`).
2344 Rptr(Lifetime, MutTy<'hir>),
2345 /// A bare function (e.g., `fn(usize) -> bool`).
2346 BareFn(&'hir BareFnTy<'hir>),
2347 /// The never type (`!`).
2349 /// A tuple (`(A, B, C, D, ...)`).
2350 Tup(&'hir [Ty<'hir>]),
2351 /// A path to a type definition (`module::module::...::Type`), or an
2352 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2354 /// Type parameters may be stored in each `PathSegment`.
2356 /// An opaque type definition itself. This is only used for `impl Trait`.
2358 /// The generic argument list contains the lifetimes (and in the future
2359 /// possibly parameters) that are actually bound on the `impl Trait`.
2360 OpaqueDef(ItemId, &'hir [GenericArg<'hir>]),
2361 /// A trait object type `Bound1 + Bound2 + Bound3`
2362 /// where `Bound` is a trait or a lifetime.
2363 TraitObject(&'hir [PolyTraitRef<'hir>], Lifetime, TraitObjectSyntax),
2366 /// `TyKind::Infer` means the type should be inferred instead of it having been
2367 /// specified. This can appear anywhere in a type.
2369 /// Placeholder for a type that has failed to be defined.
2373 #[derive(Debug, HashStable_Generic)]
2374 pub enum InlineAsmOperand<'hir> {
2376 reg: InlineAsmRegOrRegClass,
2380 reg: InlineAsmRegOrRegClass,
2382 expr: Option<Expr<'hir>>,
2385 reg: InlineAsmRegOrRegClass,
2390 reg: InlineAsmRegOrRegClass,
2392 in_expr: Expr<'hir>,
2393 out_expr: Option<Expr<'hir>>,
2396 anon_const: AnonConst,
2403 impl<'hir> InlineAsmOperand<'hir> {
2404 pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
2406 Self::In { reg, .. }
2407 | Self::Out { reg, .. }
2408 | Self::InOut { reg, .. }
2409 | Self::SplitInOut { reg, .. } => Some(reg),
2410 Self::Const { .. } | Self::Sym { .. } => None,
2414 pub fn is_clobber(&self) -> bool {
2417 InlineAsmOperand::Out { reg: InlineAsmRegOrRegClass::Reg(_), late: _, expr: None }
2422 #[derive(Debug, HashStable_Generic)]
2423 pub struct InlineAsm<'hir> {
2424 pub template: &'hir [InlineAsmTemplatePiece],
2425 pub template_strs: &'hir [(Symbol, Option<Symbol>, Span)],
2426 pub operands: &'hir [(InlineAsmOperand<'hir>, Span)],
2427 pub options: InlineAsmOptions,
2428 pub line_spans: &'hir [Span],
2431 /// Represents a parameter in a function header.
2432 #[derive(Debug, HashStable_Generic)]
2433 pub struct Param<'hir> {
2435 pub pat: &'hir Pat<'hir>,
2440 /// Represents the header (not the body) of a function declaration.
2441 #[derive(Debug, HashStable_Generic)]
2442 pub struct FnDecl<'hir> {
2443 /// The types of the function's parameters.
2445 /// Additional argument data is stored in the function's [body](Body::params).
2446 pub inputs: &'hir [Ty<'hir>],
2447 pub output: FnRetTy<'hir>,
2448 pub c_variadic: bool,
2449 /// Does the function have an implicit self?
2450 pub implicit_self: ImplicitSelfKind,
2453 /// Represents what type of implicit self a function has, if any.
2454 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2455 pub enum ImplicitSelfKind {
2456 /// Represents a `fn x(self);`.
2458 /// Represents a `fn x(mut self);`.
2460 /// Represents a `fn x(&self);`.
2462 /// Represents a `fn x(&mut self);`.
2464 /// Represents when a function does not have a self argument or
2465 /// when a function has a `self: X` argument.
2469 impl ImplicitSelfKind {
2470 /// Does this represent an implicit self?
2471 pub fn has_implicit_self(&self) -> bool {
2472 !matches!(*self, ImplicitSelfKind::None)
2476 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable, Debug)]
2477 #[derive(HashStable_Generic)]
2483 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable, HashStable_Generic)]
2484 pub enum Defaultness {
2485 Default { has_value: bool },
2490 pub fn has_value(&self) -> bool {
2492 Defaultness::Default { has_value } => has_value,
2493 Defaultness::Final => true,
2497 pub fn is_final(&self) -> bool {
2498 *self == Defaultness::Final
2501 pub fn is_default(&self) -> bool {
2502 matches!(*self, Defaultness::Default { .. })
2506 #[derive(Debug, HashStable_Generic)]
2507 pub enum FnRetTy<'hir> {
2508 /// Return type is not specified.
2510 /// Functions default to `()` and
2511 /// closures default to inference. Span points to where return
2512 /// type would be inserted.
2513 DefaultReturn(Span),
2514 /// Everything else.
2515 Return(&'hir Ty<'hir>),
2520 pub fn span(&self) -> Span {
2522 Self::DefaultReturn(span) => span,
2523 Self::Return(ref ty) => ty.span,
2528 #[derive(Encodable, Debug, HashStable_Generic)]
2529 pub struct Mod<'hir> {
2530 /// A span from the first token past `{` to the last token until `}`.
2531 /// For `mod foo;`, the inner span ranges from the first token
2532 /// to the last token in the external file.
2534 pub item_ids: &'hir [ItemId],
2537 #[derive(Debug, HashStable_Generic)]
2538 pub struct EnumDef<'hir> {
2539 pub variants: &'hir [Variant<'hir>],
2542 #[derive(Debug, HashStable_Generic)]
2543 pub struct Variant<'hir> {
2544 /// Name of the variant.
2546 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2548 /// Fields and constructor id of the variant.
2549 pub data: VariantData<'hir>,
2550 /// Explicit discriminant (e.g., `Foo = 1`).
2551 pub disr_expr: Option<AnonConst>,
2556 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2558 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2559 /// Also produced for each element of a list `use`, e.g.
2560 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2563 /// Glob import, e.g., `use foo::*`.
2566 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2567 /// an additional `use foo::{}` for performing checks such as
2568 /// unstable feature gating. May be removed in the future.
2572 /// References to traits in impls.
2574 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2575 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2576 /// trait being referred to but just a unique `HirId` that serves as a key
2577 /// within the resolution map.
2578 #[derive(Clone, Debug, HashStable_Generic)]
2579 pub struct TraitRef<'hir> {
2580 pub path: &'hir Path<'hir>,
2581 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2582 #[stable_hasher(ignore)]
2583 pub hir_ref_id: HirId,
2587 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2588 pub fn trait_def_id(&self) -> Option<DefId> {
2589 match self.path.res {
2590 Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
2592 _ => unreachable!(),
2597 #[derive(Clone, Debug, HashStable_Generic)]
2598 pub struct PolyTraitRef<'hir> {
2599 /// The `'a` in `for<'a> Foo<&'a T>`.
2600 pub bound_generic_params: &'hir [GenericParam<'hir>],
2602 /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
2603 pub trait_ref: TraitRef<'hir>,
2608 pub type Visibility<'hir> = Spanned<VisibilityKind<'hir>>;
2610 #[derive(Copy, Clone, Debug)]
2611 pub enum VisibilityKind<'hir> {
2614 Restricted { path: &'hir Path<'hir>, hir_id: HirId },
2618 impl VisibilityKind<'_> {
2619 pub fn is_pub(&self) -> bool {
2620 matches!(*self, VisibilityKind::Public)
2623 pub fn is_pub_restricted(&self) -> bool {
2625 VisibilityKind::Public | VisibilityKind::Inherited => false,
2626 VisibilityKind::Crate(..) | VisibilityKind::Restricted { .. } => true,
2631 #[derive(Debug, HashStable_Generic)]
2632 pub struct FieldDef<'hir> {
2635 pub vis: Visibility<'hir>,
2637 pub ty: &'hir Ty<'hir>,
2641 // Still necessary in couple of places
2642 pub fn is_positional(&self) -> bool {
2643 let first = self.ident.as_str().as_bytes()[0];
2644 (b'0'..=b'9').contains(&first)
2648 /// Fields and constructor IDs of enum variants and structs.
2649 #[derive(Debug, HashStable_Generic)]
2650 pub enum VariantData<'hir> {
2651 /// A struct variant.
2653 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2654 Struct(&'hir [FieldDef<'hir>], /* recovered */ bool),
2655 /// A tuple variant.
2657 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2658 Tuple(&'hir [FieldDef<'hir>], HirId),
2661 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2665 impl<'hir> VariantData<'hir> {
2666 /// Return the fields of this variant.
2667 pub fn fields(&self) -> &'hir [FieldDef<'hir>] {
2669 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2674 /// Return the `HirId` of this variant's constructor, if it has one.
2675 pub fn ctor_hir_id(&self) -> Option<HirId> {
2677 VariantData::Struct(_, _) => None,
2678 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2683 // The bodies for items are stored "out of line", in a separate
2684 // hashmap in the `Crate`. Here we just record the hir-id of the item
2685 // so it can fetched later.
2686 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, Hash)]
2688 pub def_id: LocalDefId,
2693 pub fn hir_id(&self) -> HirId {
2694 // Items are always HIR owners.
2695 HirId::make_owner(self.def_id)
2701 /// The name might be a dummy name in case of anonymous items
2703 pub struct Item<'hir> {
2705 pub def_id: LocalDefId,
2706 pub kind: ItemKind<'hir>,
2707 pub vis: Visibility<'hir>,
2713 pub fn hir_id(&self) -> HirId {
2714 // Items are always HIR owners.
2715 HirId::make_owner(self.def_id)
2718 pub fn item_id(&self) -> ItemId {
2719 ItemId { def_id: self.def_id }
2723 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2724 #[derive(Encodable, Decodable, HashStable_Generic)]
2731 pub fn prefix_str(&self) -> &'static str {
2733 Self::Unsafe => "unsafe ",
2739 impl fmt::Display for Unsafety {
2740 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2741 f.write_str(match *self {
2742 Self::Unsafe => "unsafe",
2743 Self::Normal => "normal",
2748 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2749 #[derive(Encodable, Decodable, HashStable_Generic)]
2750 pub enum Constness {
2755 impl fmt::Display for Constness {
2756 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2757 f.write_str(match *self {
2758 Self::Const => "const",
2759 Self::NotConst => "non-const",
2764 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2765 pub struct FnHeader {
2766 pub unsafety: Unsafety,
2767 pub constness: Constness,
2768 pub asyncness: IsAsync,
2773 pub fn is_async(&self) -> bool {
2774 matches!(&self.asyncness, IsAsync::Async)
2777 pub fn is_const(&self) -> bool {
2778 matches!(&self.constness, Constness::Const)
2781 pub fn is_unsafe(&self) -> bool {
2782 matches!(&self.unsafety, Unsafety::Unsafe)
2786 #[derive(Debug, HashStable_Generic)]
2787 pub enum ItemKind<'hir> {
2788 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2790 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2791 ExternCrate(Option<Symbol>),
2793 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2797 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2798 Use(&'hir Path<'hir>, UseKind),
2800 /// A `static` item.
2801 Static(&'hir Ty<'hir>, Mutability, BodyId),
2803 Const(&'hir Ty<'hir>, BodyId),
2804 /// A function declaration.
2805 Fn(FnSig<'hir>, Generics<'hir>, BodyId),
2806 /// A MBE macro definition (`macro_rules!` or `macro`).
2807 Macro(ast::MacroDef, MacroKind),
2810 /// An external module, e.g. `extern { .. }`.
2811 ForeignMod { abi: Abi, items: &'hir [ForeignItemRef] },
2812 /// Module-level inline assembly (from `global_asm!`).
2813 GlobalAsm(&'hir InlineAsm<'hir>),
2814 /// A type alias, e.g., `type Foo = Bar<u8>`.
2815 TyAlias(&'hir Ty<'hir>, Generics<'hir>),
2816 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2817 OpaqueTy(OpaqueTy<'hir>),
2818 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2819 Enum(EnumDef<'hir>, Generics<'hir>),
2820 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2821 Struct(VariantData<'hir>, Generics<'hir>),
2822 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2823 Union(VariantData<'hir>, Generics<'hir>),
2824 /// A trait definition.
2825 Trait(IsAuto, Unsafety, Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
2827 TraitAlias(Generics<'hir>, GenericBounds<'hir>),
2829 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2833 #[derive(Debug, HashStable_Generic)]
2834 pub struct Impl<'hir> {
2835 pub unsafety: Unsafety,
2836 pub polarity: ImplPolarity,
2837 pub defaultness: Defaultness,
2838 // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata
2839 // decoding as `Span`s cannot be decoded when a `Session` is not available.
2840 pub defaultness_span: Option<Span>,
2841 pub constness: Constness,
2842 pub generics: Generics<'hir>,
2844 /// The trait being implemented, if any.
2845 pub of_trait: Option<TraitRef<'hir>>,
2847 pub self_ty: &'hir Ty<'hir>,
2848 pub items: &'hir [ImplItemRef],
2852 pub fn generics(&self) -> Option<&Generics<'_>> {
2854 ItemKind::Fn(_, ref generics, _)
2855 | ItemKind::TyAlias(_, ref generics)
2856 | ItemKind::OpaqueTy(OpaqueTy {
2857 ref generics, origin: OpaqueTyOrigin::TyAlias, ..
2859 | ItemKind::Enum(_, ref generics)
2860 | ItemKind::Struct(_, ref generics)
2861 | ItemKind::Union(_, ref generics)
2862 | ItemKind::Trait(_, _, ref generics, _, _)
2863 | ItemKind::Impl(Impl { ref generics, .. }) => generics,
2868 pub fn descr(&self) -> &'static str {
2870 ItemKind::ExternCrate(..) => "extern crate",
2871 ItemKind::Use(..) => "`use` import",
2872 ItemKind::Static(..) => "static item",
2873 ItemKind::Const(..) => "constant item",
2874 ItemKind::Fn(..) => "function",
2875 ItemKind::Macro(..) => "macro",
2876 ItemKind::Mod(..) => "module",
2877 ItemKind::ForeignMod { .. } => "extern block",
2878 ItemKind::GlobalAsm(..) => "global asm item",
2879 ItemKind::TyAlias(..) => "type alias",
2880 ItemKind::OpaqueTy(..) => "opaque type",
2881 ItemKind::Enum(..) => "enum",
2882 ItemKind::Struct(..) => "struct",
2883 ItemKind::Union(..) => "union",
2884 ItemKind::Trait(..) => "trait",
2885 ItemKind::TraitAlias(..) => "trait alias",
2886 ItemKind::Impl(..) => "implementation",
2891 /// A reference from an trait to one of its associated items. This
2892 /// contains the item's id, naturally, but also the item's name and
2893 /// some other high-level details (like whether it is an associated
2894 /// type or method, and whether it is public). This allows other
2895 /// passes to find the impl they want without loading the ID (which
2896 /// means fewer edges in the incremental compilation graph).
2897 #[derive(Encodable, Debug, HashStable_Generic)]
2898 pub struct TraitItemRef {
2899 pub id: TraitItemId,
2901 pub kind: AssocItemKind,
2903 pub defaultness: Defaultness,
2906 /// A reference from an impl to one of its associated items. This
2907 /// contains the item's ID, naturally, but also the item's name and
2908 /// some other high-level details (like whether it is an associated
2909 /// type or method, and whether it is public). This allows other
2910 /// passes to find the impl they want without loading the ID (which
2911 /// means fewer edges in the incremental compilation graph).
2912 #[derive(Debug, HashStable_Generic)]
2913 pub struct ImplItemRef {
2916 pub kind: AssocItemKind,
2918 pub defaultness: Defaultness,
2919 /// When we are in a trait impl, link to the trait-item's id.
2920 pub trait_item_def_id: Option<DefId>,
2923 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2924 pub enum AssocItemKind {
2926 Fn { has_self: bool },
2930 // The bodies for items are stored "out of line", in a separate
2931 // hashmap in the `Crate`. Here we just record the hir-id of the item
2932 // so it can fetched later.
2933 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug)]
2934 pub struct ForeignItemId {
2935 pub def_id: LocalDefId,
2938 impl ForeignItemId {
2940 pub fn hir_id(&self) -> HirId {
2941 // Items are always HIR owners.
2942 HirId::make_owner(self.def_id)
2946 /// A reference from a foreign block to one of its items. This
2947 /// contains the item's ID, naturally, but also the item's name and
2948 /// some other high-level details (like whether it is an associated
2949 /// type or method, and whether it is public). This allows other
2950 /// passes to find the impl they want without loading the ID (which
2951 /// means fewer edges in the incremental compilation graph).
2952 #[derive(Debug, HashStable_Generic)]
2953 pub struct ForeignItemRef {
2954 pub id: ForeignItemId,
2960 pub struct ForeignItem<'hir> {
2962 pub kind: ForeignItemKind<'hir>,
2963 pub def_id: LocalDefId,
2965 pub vis: Visibility<'hir>,
2968 impl ForeignItem<'_> {
2970 pub fn hir_id(&self) -> HirId {
2971 // Items are always HIR owners.
2972 HirId::make_owner(self.def_id)
2975 pub fn foreign_item_id(&self) -> ForeignItemId {
2976 ForeignItemId { def_id: self.def_id }
2980 /// An item within an `extern` block.
2981 #[derive(Debug, HashStable_Generic)]
2982 pub enum ForeignItemKind<'hir> {
2983 /// A foreign function.
2984 Fn(&'hir FnDecl<'hir>, &'hir [Ident], Generics<'hir>),
2985 /// A foreign static item (`static ext: u8`).
2986 Static(&'hir Ty<'hir>, Mutability),
2991 /// A variable captured by a closure.
2992 #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)]
2994 // First span where it is accessed (there can be multiple).
2998 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2999 // has length > 0 if the trait is found through an chain of imports, starting with the
3000 // import/use statement in the scope where the trait is used.
3001 #[derive(Encodable, Decodable, Clone, Debug)]
3002 pub struct TraitCandidate {
3004 pub import_ids: SmallVec<[LocalDefId; 1]>,
3007 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3008 pub enum OwnerNode<'hir> {
3009 Item(&'hir Item<'hir>),
3010 ForeignItem(&'hir ForeignItem<'hir>),
3011 TraitItem(&'hir TraitItem<'hir>),
3012 ImplItem(&'hir ImplItem<'hir>),
3013 Crate(&'hir Mod<'hir>),
3016 impl<'hir> OwnerNode<'hir> {
3017 pub fn ident(&self) -> Option<Ident> {
3019 OwnerNode::Item(Item { ident, .. })
3020 | OwnerNode::ForeignItem(ForeignItem { ident, .. })
3021 | OwnerNode::ImplItem(ImplItem { ident, .. })
3022 | OwnerNode::TraitItem(TraitItem { ident, .. }) => Some(*ident),
3023 OwnerNode::Crate(..) => None,
3027 pub fn span(&self) -> Span {
3029 OwnerNode::Item(Item { span, .. })
3030 | OwnerNode::ForeignItem(ForeignItem { span, .. })
3031 | OwnerNode::ImplItem(ImplItem { span, .. })
3032 | OwnerNode::TraitItem(TraitItem { span, .. })
3033 | OwnerNode::Crate(Mod { inner: span, .. }) => *span,
3037 pub fn fn_decl(&self) -> Option<&FnDecl<'hir>> {
3039 OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3040 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3041 | OwnerNode::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3042 OwnerNode::ForeignItem(ForeignItem {
3043 kind: ForeignItemKind::Fn(fn_decl, _, _),
3045 }) => Some(fn_decl),
3050 pub fn body_id(&self) -> Option<BodyId> {
3052 OwnerNode::TraitItem(TraitItem {
3053 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3056 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3057 | OwnerNode::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3062 pub fn generics(&self) -> Option<&'hir Generics<'hir>> {
3064 OwnerNode::TraitItem(TraitItem { generics, .. })
3065 | OwnerNode::ImplItem(ImplItem { generics, .. }) => Some(generics),
3066 OwnerNode::Item(item) => item.kind.generics(),
3071 pub fn def_id(self) -> LocalDefId {
3073 OwnerNode::Item(Item { def_id, .. })
3074 | OwnerNode::TraitItem(TraitItem { def_id, .. })
3075 | OwnerNode::ImplItem(ImplItem { def_id, .. })
3076 | OwnerNode::ForeignItem(ForeignItem { def_id, .. }) => *def_id,
3077 OwnerNode::Crate(..) => crate::CRATE_HIR_ID.owner,
3081 pub fn expect_item(self) -> &'hir Item<'hir> {
3083 OwnerNode::Item(n) => n,
3088 pub fn expect_foreign_item(self) -> &'hir ForeignItem<'hir> {
3090 OwnerNode::ForeignItem(n) => n,
3095 pub fn expect_impl_item(self) -> &'hir ImplItem<'hir> {
3097 OwnerNode::ImplItem(n) => n,
3102 pub fn expect_trait_item(self) -> &'hir TraitItem<'hir> {
3104 OwnerNode::TraitItem(n) => n,
3110 impl<'hir> Into<OwnerNode<'hir>> for &'hir Item<'hir> {
3111 fn into(self) -> OwnerNode<'hir> {
3112 OwnerNode::Item(self)
3116 impl<'hir> Into<OwnerNode<'hir>> for &'hir ForeignItem<'hir> {
3117 fn into(self) -> OwnerNode<'hir> {
3118 OwnerNode::ForeignItem(self)
3122 impl<'hir> Into<OwnerNode<'hir>> for &'hir ImplItem<'hir> {
3123 fn into(self) -> OwnerNode<'hir> {
3124 OwnerNode::ImplItem(self)
3128 impl<'hir> Into<OwnerNode<'hir>> for &'hir TraitItem<'hir> {
3129 fn into(self) -> OwnerNode<'hir> {
3130 OwnerNode::TraitItem(self)
3134 impl<'hir> Into<Node<'hir>> for OwnerNode<'hir> {
3135 fn into(self) -> Node<'hir> {
3137 OwnerNode::Item(n) => Node::Item(n),
3138 OwnerNode::ForeignItem(n) => Node::ForeignItem(n),
3139 OwnerNode::ImplItem(n) => Node::ImplItem(n),
3140 OwnerNode::TraitItem(n) => Node::TraitItem(n),
3141 OwnerNode::Crate(n) => Node::Crate(n),
3146 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3147 pub enum Node<'hir> {
3148 Param(&'hir Param<'hir>),
3149 Item(&'hir Item<'hir>),
3150 ForeignItem(&'hir ForeignItem<'hir>),
3151 TraitItem(&'hir TraitItem<'hir>),
3152 ImplItem(&'hir ImplItem<'hir>),
3153 Variant(&'hir Variant<'hir>),
3154 Field(&'hir FieldDef<'hir>),
3155 AnonConst(&'hir AnonConst),
3156 Expr(&'hir Expr<'hir>),
3157 Stmt(&'hir Stmt<'hir>),
3158 PathSegment(&'hir PathSegment<'hir>),
3160 TraitRef(&'hir TraitRef<'hir>),
3161 Binding(&'hir Pat<'hir>),
3162 Pat(&'hir Pat<'hir>),
3163 Arm(&'hir Arm<'hir>),
3164 Block(&'hir Block<'hir>),
3165 Local(&'hir Local<'hir>),
3167 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
3168 /// with synthesized constructors.
3169 Ctor(&'hir VariantData<'hir>),
3171 Lifetime(&'hir Lifetime),
3172 GenericParam(&'hir GenericParam<'hir>),
3173 Visibility(&'hir Visibility<'hir>),
3175 Crate(&'hir Mod<'hir>),
3177 Infer(&'hir InferArg),
3180 impl<'hir> Node<'hir> {
3181 /// Get the identifier of this `Node`, if applicable.
3185 /// Calling `.ident()` on a [`Node::Ctor`] will return `None`
3186 /// because `Ctor`s do not have identifiers themselves.
3187 /// Instead, call `.ident()` on the parent struct/variant, like so:
3189 /// ```ignore (illustrative)
3192 /// .and_then(|ctor_id| tcx.hir().find(tcx.hir().get_parent_node(ctor_id)))
3193 /// .and_then(|parent| parent.ident())
3195 pub fn ident(&self) -> Option<Ident> {
3197 Node::TraitItem(TraitItem { ident, .. })
3198 | Node::ImplItem(ImplItem { ident, .. })
3199 | Node::ForeignItem(ForeignItem { ident, .. })
3200 | Node::Field(FieldDef { ident, .. })
3201 | Node::Variant(Variant { ident, .. })
3202 | Node::Item(Item { ident, .. })
3203 | Node::PathSegment(PathSegment { ident, .. }) => Some(*ident),
3204 Node::Lifetime(lt) => Some(lt.name.ident()),
3205 Node::GenericParam(p) => Some(p.name.ident()),
3207 | Node::AnonConst(..)
3216 | Node::Visibility(..)
3219 | Node::TraitRef(..)
3220 | Node::Infer(..) => None,
3224 pub fn fn_decl(&self) -> Option<&'hir FnDecl<'hir>> {
3226 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3227 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3228 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3229 Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
3236 pub fn fn_sig(&self) -> Option<&'hir FnSig<'hir>> {
3238 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3239 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3240 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig),
3245 pub fn body_id(&self) -> Option<BodyId> {
3247 Node::TraitItem(TraitItem {
3248 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3251 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3252 | Node::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3257 pub fn generics(&self) -> Option<&'hir Generics<'hir>> {
3259 Node::TraitItem(TraitItem { generics, .. })
3260 | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
3261 Node::Item(item) => item.kind.generics(),
3266 pub fn as_owner(self) -> Option<OwnerNode<'hir>> {
3268 Node::Item(i) => Some(OwnerNode::Item(i)),
3269 Node::ForeignItem(i) => Some(OwnerNode::ForeignItem(i)),
3270 Node::TraitItem(i) => Some(OwnerNode::TraitItem(i)),
3271 Node::ImplItem(i) => Some(OwnerNode::ImplItem(i)),
3272 Node::Crate(i) => Some(OwnerNode::Crate(i)),
3277 pub fn fn_kind(self) -> Option<FnKind<'hir>> {
3279 Node::Item(i) => match i.kind {
3280 ItemKind::Fn(ref sig, ref generics, _) => {
3281 Some(FnKind::ItemFn(i.ident, generics, sig.header, &i.vis))
3285 Node::TraitItem(ti) => match ti.kind {
3286 TraitItemKind::Fn(ref sig, TraitFn::Provided(_)) => {
3287 Some(FnKind::Method(ti.ident, sig, None))
3291 Node::ImplItem(ii) => match ii.kind {
3292 ImplItemKind::Fn(ref sig, _) => Some(FnKind::Method(ii.ident, sig, Some(&ii.vis))),
3295 Node::Expr(e) => match e.kind {
3296 ExprKind::Closure(..) => Some(FnKind::Closure),
3304 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3305 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
3307 rustc_data_structures::static_assert_size!(super::Block<'static>, 48);
3308 rustc_data_structures::static_assert_size!(super::Expr<'static>, 56);
3309 rustc_data_structures::static_assert_size!(super::Pat<'static>, 88);
3310 rustc_data_structures::static_assert_size!(super::QPath<'static>, 24);
3311 rustc_data_structures::static_assert_size!(super::Ty<'static>, 80);
3313 rustc_data_structures::static_assert_size!(super::Item<'static>, 184);
3314 rustc_data_structures::static_assert_size!(super::TraitItem<'static>, 128);
3315 rustc_data_structures::static_assert_size!(super::ImplItem<'static>, 144);
3316 rustc_data_structures::static_assert_size!(super::ForeignItem<'static>, 136);