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`).
97 /// The bool indicates whether the user should have written something.
100 /// Implicit lifetime in a context like `dyn Foo`. This is
101 /// distinguished from implicit lifetimes elsewhere because the
102 /// lifetime that they default to must appear elsewhere within the
103 /// enclosing type. This means that, in an `impl Trait` context, we
104 /// don't have to create a parameter for them. That is, `impl
105 /// Trait<Item = &u32>` expands to an opaque type like `type
106 /// Foo<'a> = impl Trait<Item = &'a u32>`, but `impl Trait<item =
107 /// dyn Bar>` expands to `type Foo = impl Trait<Item = dyn Bar +
108 /// 'static>`. The latter uses `ImplicitObjectLifetimeDefault` so
109 /// that surrounding code knows not to create a lifetime
111 ImplicitObjectLifetimeDefault,
113 /// Indicates an error during lowering (usually `'_` in wrong place)
114 /// that was already reported.
117 /// User wrote specifies `'_`.
120 /// User wrote `'static`.
125 pub fn ident(&self) -> Ident {
127 LifetimeName::ImplicitObjectLifetimeDefault
128 | LifetimeName::Implicit
129 | LifetimeName::Error => Ident::empty(),
130 LifetimeName::Underscore => Ident::with_dummy_span(kw::UnderscoreLifetime),
131 LifetimeName::Static => Ident::with_dummy_span(kw::StaticLifetime),
132 LifetimeName::Param(param_name) => param_name.ident(),
136 pub fn is_elided(&self) -> bool {
138 LifetimeName::ImplicitObjectLifetimeDefault
139 | LifetimeName::Implicit
140 | LifetimeName::Underscore => true,
142 // It might seem surprising that `Fresh(_)` counts as
143 // *not* elided -- but this is because, as far as the code
144 // in the compiler is concerned -- `Fresh(_)` variants act
145 // equivalently to "some fresh name". They correspond to
146 // early-bound regions on an impl, in other words.
147 LifetimeName::Error | LifetimeName::Param(_) | LifetimeName::Static => false,
151 fn is_static(&self) -> bool {
152 self == &LifetimeName::Static
155 pub fn normalize_to_macros_2_0(&self) -> LifetimeName {
157 LifetimeName::Param(param_name) => {
158 LifetimeName::Param(param_name.normalize_to_macros_2_0())
160 lifetime_name => lifetime_name,
165 impl fmt::Display for Lifetime {
166 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167 self.name.ident().fmt(f)
171 impl fmt::Debug for Lifetime {
172 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
173 write!(f, "lifetime({}: {})", self.hir_id, self.name.ident())
178 pub fn is_elided(&self) -> bool {
179 self.name.is_elided()
182 pub fn is_static(&self) -> bool {
183 self.name.is_static()
187 /// A `Path` is essentially Rust's notion of a name; for instance,
188 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
189 /// along with a bunch of supporting information.
190 #[derive(Debug, HashStable_Generic)]
191 pub struct Path<'hir> {
193 /// The resolution for the path.
195 /// The segments in the path: the things separated by `::`.
196 pub segments: &'hir [PathSegment<'hir>],
200 pub fn is_global(&self) -> bool {
201 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
205 /// A segment of a path: an identifier, an optional lifetime, and a set of
207 #[derive(Debug, HashStable_Generic)]
208 pub struct PathSegment<'hir> {
209 /// The identifier portion of this path segment.
211 // `id` and `res` are optional. We currently only use these in save-analysis,
212 // any path segments without these will not have save-analysis info and
213 // therefore will not have 'jump to def' in IDEs, but otherwise will not be
214 // affected. (In general, we don't bother to get the defs for synthesized
215 // segments, only for segments which have come from the AST).
216 pub hir_id: Option<HirId>,
217 pub res: Option<Res>,
219 /// Type/lifetime parameters attached to this path. They come in
220 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
221 /// this is more than just simple syntactic sugar; the use of
222 /// parens affects the region binding rules, so we preserve the
224 pub args: Option<&'hir GenericArgs<'hir>>,
226 /// Whether to infer remaining type parameters, if any.
227 /// This only applies to expression and pattern paths, and
228 /// out of those only the segments with no type parameters
229 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
230 pub infer_args: bool,
233 impl<'hir> PathSegment<'hir> {
234 /// Converts an identifier to the corresponding segment.
235 pub fn from_ident(ident: Ident) -> PathSegment<'hir> {
236 PathSegment { ident, hir_id: None, res: None, infer_args: true, args: None }
239 pub fn invalid() -> Self {
240 Self::from_ident(Ident::empty())
243 pub fn args(&self) -> &GenericArgs<'hir> {
244 if let Some(ref args) = self.args {
247 const DUMMY: &GenericArgs<'_> = &GenericArgs::none();
253 #[derive(Encodable, Debug, HashStable_Generic)]
254 pub struct ConstArg {
255 pub value: AnonConst,
259 #[derive(Encodable, Debug, HashStable_Generic)]
260 pub struct InferArg {
266 pub fn to_ty(&self) -> Ty<'_> {
267 Ty { kind: TyKind::Infer, span: self.span, hir_id: self.hir_id }
271 #[derive(Debug, HashStable_Generic)]
272 pub enum GenericArg<'hir> {
279 impl GenericArg<'_> {
280 pub fn span(&self) -> Span {
282 GenericArg::Lifetime(l) => l.span,
283 GenericArg::Type(t) => t.span,
284 GenericArg::Const(c) => c.span,
285 GenericArg::Infer(i) => i.span,
289 pub fn id(&self) -> HirId {
291 GenericArg::Lifetime(l) => l.hir_id,
292 GenericArg::Type(t) => t.hir_id,
293 GenericArg::Const(c) => c.value.hir_id,
294 GenericArg::Infer(i) => i.hir_id,
298 pub fn is_synthetic(&self) -> bool {
299 matches!(self, GenericArg::Lifetime(lifetime) if lifetime.name.ident() == Ident::empty())
302 pub fn descr(&self) -> &'static str {
304 GenericArg::Lifetime(_) => "lifetime",
305 GenericArg::Type(_) => "type",
306 GenericArg::Const(_) => "constant",
307 GenericArg::Infer(_) => "inferred",
311 pub fn to_ord(&self) -> ast::ParamKindOrd {
313 GenericArg::Lifetime(_) => ast::ParamKindOrd::Lifetime,
314 GenericArg::Type(_) => ast::ParamKindOrd::Type,
315 GenericArg::Const(_) => ast::ParamKindOrd::Const,
316 GenericArg::Infer(_) => ast::ParamKindOrd::Infer,
320 pub fn is_ty_or_const(&self) -> bool {
322 GenericArg::Lifetime(_) => false,
323 GenericArg::Type(_) | GenericArg::Const(_) | GenericArg::Infer(_) => true,
328 #[derive(Debug, HashStable_Generic)]
329 pub struct GenericArgs<'hir> {
330 /// The generic arguments for this path segment.
331 pub args: &'hir [GenericArg<'hir>],
332 /// Bindings (equality constraints) on associated types, if present.
333 /// E.g., `Foo<A = Bar>`.
334 pub bindings: &'hir [TypeBinding<'hir>],
335 /// Were arguments written in parenthesized form `Fn(T) -> U`?
336 /// This is required mostly for pretty-printing and diagnostics,
337 /// but also for changing lifetime elision rules to be "function-like".
338 pub parenthesized: bool,
339 /// The span encompassing arguments and the surrounding brackets `<>` or `()`
340 /// Foo<A, B, AssocTy = D> Fn(T, U, V) -> W
341 /// ^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^
342 /// Note that this may be:
343 /// - empty, if there are no generic brackets (but there may be hidden lifetimes)
344 /// - dummy, if this was generated while desugaring
348 impl GenericArgs<'_> {
349 pub const fn none() -> Self {
350 Self { args: &[], bindings: &[], parenthesized: false, span_ext: DUMMY_SP }
353 pub fn inputs(&self) -> &[Ty<'_>] {
354 if self.parenthesized {
355 for arg in self.args {
357 GenericArg::Lifetime(_) => {}
358 GenericArg::Type(ref ty) => {
359 if let TyKind::Tup(ref tys) = ty.kind {
364 GenericArg::Const(_) => {}
365 GenericArg::Infer(_) => {}
369 panic!("GenericArgs::inputs: not a `Fn(T) -> U`");
373 pub fn has_type_params(&self) -> bool {
374 self.args.iter().any(|arg| matches!(arg, GenericArg::Type(_)))
377 pub fn has_err(&self) -> bool {
378 self.args.iter().any(|arg| match arg {
379 GenericArg::Type(ty) => matches!(ty.kind, TyKind::Err),
381 }) || self.bindings.iter().any(|arg| match arg.kind {
382 TypeBindingKind::Equality { term: Term::Ty(ty) } => matches!(ty.kind, TyKind::Err),
388 pub fn num_type_params(&self) -> usize {
389 self.args.iter().filter(|arg| matches!(arg, GenericArg::Type(_))).count()
393 pub fn num_lifetime_params(&self) -> usize {
394 self.args.iter().filter(|arg| matches!(arg, GenericArg::Lifetime(_))).count()
398 pub fn has_lifetime_params(&self) -> bool {
399 self.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)))
403 pub fn num_generic_params(&self) -> usize {
404 self.args.iter().filter(|arg| !matches!(arg, GenericArg::Lifetime(_))).count()
407 /// The span encompassing the text inside the surrounding brackets.
408 /// It will also include bindings if they aren't in the form `-> Ret`
409 /// Returns `None` if the span is empty (e.g. no brackets) or dummy
410 pub fn span(&self) -> Option<Span> {
411 let span_ext = self.span_ext()?;
412 Some(span_ext.with_lo(span_ext.lo() + BytePos(1)).with_hi(span_ext.hi() - BytePos(1)))
415 /// Returns span encompassing arguments and their surrounding `<>` or `()`
416 pub fn span_ext(&self) -> Option<Span> {
417 Some(self.span_ext).filter(|span| !span.is_empty())
420 pub fn is_empty(&self) -> bool {
425 /// A modifier on a bound, currently this is only used for `?Sized`, where the
426 /// modifier is `Maybe`. Negative bounds should also be handled here.
427 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
428 #[derive(HashStable_Generic)]
429 pub enum TraitBoundModifier {
435 /// The AST represents all type param bounds as types.
436 /// `typeck::collect::compute_bounds` matches these against
437 /// the "special" built-in traits (see `middle::lang_items`) and
438 /// detects `Copy`, `Send` and `Sync`.
439 #[derive(Clone, Debug, HashStable_Generic)]
440 pub enum GenericBound<'hir> {
441 Trait(PolyTraitRef<'hir>, TraitBoundModifier),
442 // FIXME(davidtwco): Introduce `PolyTraitRef::LangItem`
443 LangItemTrait(LangItem, Span, HirId, &'hir GenericArgs<'hir>),
447 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
448 rustc_data_structures::static_assert_size!(GenericBound<'_>, 48);
450 impl GenericBound<'_> {
451 pub fn trait_ref(&self) -> Option<&TraitRef<'_>> {
453 GenericBound::Trait(data, _) => Some(&data.trait_ref),
458 pub fn span(&self) -> Span {
460 GenericBound::Trait(t, ..) => t.span,
461 GenericBound::LangItemTrait(_, span, ..) => *span,
462 GenericBound::Outlives(l) => l.span,
467 pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
469 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
470 pub enum LifetimeParamKind {
471 // Indicates that the lifetime definition was explicitly declared (e.g., in
472 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
475 // Indication that the lifetime was elided (e.g., in both cases in
476 // `fn foo(x: &u8) -> &'_ u8 { x }`).
479 // Indication that the lifetime name was somehow in error.
483 #[derive(Debug, HashStable_Generic)]
484 pub enum GenericParamKind<'hir> {
485 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
487 kind: LifetimeParamKind,
490 default: Option<&'hir Ty<'hir>>,
495 /// Optional default value for the const generic param
496 default: Option<AnonConst>,
500 #[derive(Debug, HashStable_Generic)]
501 pub struct GenericParam<'hir> {
504 pub bounds: GenericBounds<'hir>,
506 pub pure_wrt_drop: bool,
507 pub kind: GenericParamKind<'hir>,
510 impl<'hir> GenericParam<'hir> {
511 pub fn bounds_span_for_suggestions(&self) -> Option<Span> {
514 .fold(None, |span: Option<Span>, bound| {
515 // We include bounds that come from a `#[derive(_)]` but point at the user's code,
516 // as we use this method to get a span appropriate for suggestions.
517 if !bound.span().can_be_used_for_suggestions() {
520 let span = span.map(|s| s.to(bound.span())).unwrap_or_else(|| bound.span());
524 .map(|sp| sp.shrink_to_hi())
527 /// Returns the span of `:` after a generic parameter.
546 pub fn colon_span_for_suggestions(&self, source_map: &SourceMap) -> Option<Span> {
548 .span_extend_while(self.span.shrink_to_hi(), |c| c.is_whitespace() || c == ':')
551 let snippet = source_map.span_to_snippet(sp).ok()?;
552 let offset = snippet.find(':')?;
555 .with_lo(BytePos(sp.lo().0 + offset as u32))
556 .with_hi(BytePos(sp.lo().0 + (offset + ':'.len_utf8()) as u32));
563 pub struct GenericParamCount {
564 pub lifetimes: usize,
570 /// Represents lifetimes and type parameters attached to a declaration
571 /// of a function, enum, trait, etc.
572 #[derive(Debug, HashStable_Generic)]
573 pub struct Generics<'hir> {
574 pub params: &'hir [GenericParam<'hir>],
575 pub where_clause: WhereClause<'hir>,
579 impl<'hir> Generics<'hir> {
580 pub const fn empty() -> Generics<'hir> {
583 where_clause: WhereClause { predicates: &[], span: DUMMY_SP },
588 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'_>> {
589 for param in self.params {
590 if name == param.name.ident().name {
597 pub fn spans(&self) -> MultiSpan {
598 if self.params.is_empty() {
601 self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
606 /// A where-clause in a definition.
607 #[derive(Debug, HashStable_Generic)]
608 pub struct WhereClause<'hir> {
609 pub predicates: &'hir [WherePredicate<'hir>],
610 // Only valid if predicates aren't empty.
614 impl WhereClause<'_> {
615 pub fn span(&self) -> Option<Span> {
616 if self.predicates.is_empty() { None } else { Some(self.span) }
619 /// The `WhereClause` under normal circumstances points at either the predicates or the empty
620 /// space where the `where` clause should be. Only of use for diagnostic suggestions.
621 pub fn span_for_predicates_or_empty_place(&self) -> Span {
625 /// `Span` where further predicates would be suggested, accounting for trailing commas, like
626 /// in `fn foo<T>(t: T) where T: Foo,` so we don't suggest two trailing commas.
627 pub fn tail_span_for_suggestion(&self) -> Span {
628 let end = self.span_for_predicates_or_empty_place().shrink_to_hi();
629 self.predicates.last().map_or(end, |p| p.span()).shrink_to_hi().to(end)
633 /// A single predicate in a where-clause.
634 #[derive(Debug, HashStable_Generic)]
635 pub enum WherePredicate<'hir> {
636 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
637 BoundPredicate(WhereBoundPredicate<'hir>),
638 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
639 RegionPredicate(WhereRegionPredicate<'hir>),
640 /// An equality predicate (unsupported).
641 EqPredicate(WhereEqPredicate<'hir>),
644 impl<'hir> WherePredicate<'hir> {
645 pub fn span(&self) -> Span {
647 WherePredicate::BoundPredicate(p) => p.span,
648 WherePredicate::RegionPredicate(p) => p.span,
649 WherePredicate::EqPredicate(p) => p.span,
654 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
655 #[derive(Debug, HashStable_Generic)]
656 pub struct WhereBoundPredicate<'hir> {
658 /// Any generics from a `for` binding.
659 pub bound_generic_params: &'hir [GenericParam<'hir>],
660 /// The type being bounded.
661 pub bounded_ty: &'hir Ty<'hir>,
662 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
663 pub bounds: GenericBounds<'hir>,
666 impl<'hir> WhereBoundPredicate<'hir> {
667 /// Returns `true` if `param_def_id` matches the `bounded_ty` of this predicate.
668 pub fn is_param_bound(&self, param_def_id: DefId) -> bool {
669 let TyKind::Path(QPath::Resolved(None, path)) = self.bounded_ty.kind else {
673 Res::Def(DefKind::TyParam, def_id)
674 | Res::SelfTy { trait_: Some(def_id), alias_to: None } => def_id == param_def_id,
680 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
681 #[derive(Debug, HashStable_Generic)]
682 pub struct WhereRegionPredicate<'hir> {
684 pub lifetime: Lifetime,
685 pub bounds: GenericBounds<'hir>,
688 /// An equality predicate (e.g., `T = int`); currently unsupported.
689 #[derive(Debug, HashStable_Generic)]
690 pub struct WhereEqPredicate<'hir> {
693 pub lhs_ty: &'hir Ty<'hir>,
694 pub rhs_ty: &'hir Ty<'hir>,
697 /// HIR node coupled with its parent's id in the same HIR owner.
699 /// The parent is trash when the node is a HIR owner.
700 #[derive(Clone, Debug)]
701 pub struct ParentedNode<'tcx> {
702 pub parent: ItemLocalId,
703 pub node: Node<'tcx>,
706 /// Attributes owned by a HIR owner.
708 pub struct AttributeMap<'tcx> {
709 pub map: SortedMap<ItemLocalId, &'tcx [Attribute]>,
710 pub hash: Fingerprint,
713 impl<'tcx> AttributeMap<'tcx> {
714 pub const EMPTY: &'static AttributeMap<'static> =
715 &AttributeMap { map: SortedMap::new(), hash: Fingerprint::ZERO };
718 pub fn get(&self, id: ItemLocalId) -> &'tcx [Attribute] {
719 self.map.get(&id).copied().unwrap_or(&[])
723 /// Map of all HIR nodes inside the current owner.
724 /// These nodes are mapped by `ItemLocalId` alongside the index of their parent node.
725 /// The HIR tree, including bodies, is pre-hashed.
727 pub struct OwnerNodes<'tcx> {
728 /// Pre-computed hash of the full HIR.
729 pub hash_including_bodies: Fingerprint,
730 /// Pre-computed hash of the item signature, sithout recursing into the body.
731 pub hash_without_bodies: Fingerprint,
732 /// Full HIR for the current owner.
733 // The zeroth node's parent should never be accessed: the owner's parent is computed by the
734 // hir_owner_parent query. It is set to `ItemLocalId::INVALID` to force an ICE if accidentally
736 pub nodes: IndexVec<ItemLocalId, Option<ParentedNode<'tcx>>>,
737 /// Content of local bodies.
738 pub bodies: SortedMap<ItemLocalId, &'tcx Body<'tcx>>,
739 /// Non-owning definitions contained in this owner.
740 pub local_id_to_def_id: SortedMap<ItemLocalId, LocalDefId>,
743 impl<'tcx> OwnerNodes<'tcx> {
744 pub fn node(&self) -> OwnerNode<'tcx> {
745 use rustc_index::vec::Idx;
746 let node = self.nodes[ItemLocalId::new(0)].as_ref().unwrap().node;
747 let node = node.as_owner().unwrap(); // Indexing must ensure it is an OwnerNode.
752 /// Full information resulting from lowering an AST node.
753 #[derive(Debug, HashStable_Generic)]
754 pub struct OwnerInfo<'hir> {
755 /// Contents of the HIR.
756 pub nodes: OwnerNodes<'hir>,
757 /// Map from each nested owner to its parent's local id.
758 pub parenting: FxHashMap<LocalDefId, ItemLocalId>,
759 /// Collected attributes of the HIR nodes.
760 pub attrs: AttributeMap<'hir>,
761 /// Map indicating what traits are in scope for places where this
762 /// is relevant; generated by resolve.
763 pub trait_map: FxHashMap<ItemLocalId, Box<[TraitCandidate]>>,
766 impl<'tcx> OwnerInfo<'tcx> {
768 pub fn node(&self) -> OwnerNode<'tcx> {
773 #[derive(Copy, Clone, Debug, HashStable_Generic)]
774 pub enum MaybeOwner<T> {
777 /// Used as a placeholder for unused LocalDefId.
781 impl<T> MaybeOwner<T> {
782 pub fn as_owner(self) -> Option<T> {
784 MaybeOwner::Owner(i) => Some(i),
785 MaybeOwner::NonOwner(_) | MaybeOwner::Phantom => None,
789 pub fn map<U>(self, f: impl FnOnce(T) -> U) -> MaybeOwner<U> {
791 MaybeOwner::Owner(i) => MaybeOwner::Owner(f(i)),
792 MaybeOwner::NonOwner(hir_id) => MaybeOwner::NonOwner(hir_id),
793 MaybeOwner::Phantom => MaybeOwner::Phantom,
797 pub fn unwrap(self) -> T {
799 MaybeOwner::Owner(i) => i,
800 MaybeOwner::NonOwner(_) | MaybeOwner::Phantom => panic!("Not a HIR owner"),
805 /// The top-level data structure that stores the entire contents of
806 /// the crate currently being compiled.
808 /// For more details, see the [rustc dev guide].
810 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
812 pub struct Crate<'hir> {
813 pub owners: IndexVec<LocalDefId, MaybeOwner<&'hir OwnerInfo<'hir>>>,
814 pub hir_hash: Fingerprint,
817 /// A block of statements `{ .. }`, which may have a label (in this case the
818 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
819 /// the `rules` being anything but `DefaultBlock`.
820 #[derive(Debug, HashStable_Generic)]
821 pub struct Block<'hir> {
822 /// Statements in a block.
823 pub stmts: &'hir [Stmt<'hir>],
824 /// An expression at the end of the block
825 /// without a semicolon, if any.
826 pub expr: Option<&'hir Expr<'hir>>,
827 #[stable_hasher(ignore)]
829 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
830 pub rules: BlockCheckMode,
832 /// If true, then there may exist `break 'a` values that aim to
833 /// break out of this block early.
834 /// Used by `'label: {}` blocks and by `try {}` blocks.
835 pub targeted_by_break: bool,
838 #[derive(Debug, HashStable_Generic)]
839 pub struct Pat<'hir> {
840 #[stable_hasher(ignore)]
842 pub kind: PatKind<'hir>,
844 // Whether to use default binding modes.
845 // At present, this is false only for destructuring assignment.
846 pub default_binding_modes: bool,
849 impl<'hir> Pat<'hir> {
850 // FIXME(#19596) this is a workaround, but there should be a better way
851 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) -> bool {
858 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
859 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
860 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
861 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
862 Slice(before, slice, after) => {
863 before.iter().chain(slice).chain(after.iter()).all(|p| p.walk_short_(it))
868 /// Walk the pattern in left-to-right order,
869 /// short circuiting (with `.all(..)`) if `false` is returned.
871 /// Note that when visiting e.g. `Tuple(ps)`,
872 /// if visiting `ps[0]` returns `false`,
873 /// then `ps[1]` will not be visited.
874 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) -> bool {
875 self.walk_short_(&mut it)
878 // FIXME(#19596) this is a workaround, but there should be a better way
879 fn walk_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) {
886 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
887 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
888 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
889 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
890 Slice(before, slice, after) => {
891 before.iter().chain(slice).chain(after.iter()).for_each(|p| p.walk_(it))
896 /// Walk the pattern in left-to-right order.
898 /// If `it(pat)` returns `false`, the children are not visited.
899 pub fn walk(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) {
903 /// Walk the pattern in left-to-right order.
905 /// If you always want to recurse, prefer this method over `walk`.
906 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
914 /// A single field in a struct pattern.
916 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
917 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
918 /// except `is_shorthand` is true.
919 #[derive(Debug, HashStable_Generic)]
920 pub struct PatField<'hir> {
921 #[stable_hasher(ignore)]
923 /// The identifier for the field.
925 /// The pattern the field is destructured to.
926 pub pat: &'hir Pat<'hir>,
927 pub is_shorthand: bool,
931 /// Explicit binding annotations given in the HIR for a binding. Note
932 /// that this is not the final binding *mode* that we infer after type
934 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
935 pub enum BindingAnnotation {
936 /// No binding annotation given: this means that the final binding mode
937 /// will depend on whether we have skipped through a `&` reference
938 /// when matching. For example, the `x` in `Some(x)` will have binding
939 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
940 /// ultimately be inferred to be by-reference.
942 /// Note that implicit reference skipping is not implemented yet (#42640).
945 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
948 /// Annotated as `ref`, like `ref x`
951 /// Annotated as `ref mut x`.
955 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
961 impl fmt::Display for RangeEnd {
962 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
963 f.write_str(match self {
964 RangeEnd::Included => "..=",
965 RangeEnd::Excluded => "..",
970 #[derive(Debug, HashStable_Generic)]
971 pub enum PatKind<'hir> {
972 /// Represents a wildcard pattern (i.e., `_`).
975 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
976 /// The `HirId` is the canonical ID for the variable being bound,
977 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
978 /// which is the pattern ID of the first `x`.
979 Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
981 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
982 /// The `bool` is `true` in the presence of a `..`.
983 Struct(QPath<'hir>, &'hir [PatField<'hir>], bool),
985 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
986 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
987 /// `0 <= position <= subpats.len()`
988 TupleStruct(QPath<'hir>, &'hir [Pat<'hir>], Option<usize>),
990 /// An or-pattern `A | B | C`.
991 /// Invariant: `pats.len() >= 2`.
992 Or(&'hir [Pat<'hir>]),
994 /// A path pattern for a unit struct/variant or a (maybe-associated) constant.
997 /// A tuple pattern (e.g., `(a, b)`).
998 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
999 /// `0 <= position <= subpats.len()`
1000 Tuple(&'hir [Pat<'hir>], Option<usize>),
1002 /// A `box` pattern.
1003 Box(&'hir Pat<'hir>),
1005 /// A reference pattern (e.g., `&mut (a, b)`).
1006 Ref(&'hir Pat<'hir>, Mutability),
1009 Lit(&'hir Expr<'hir>),
1011 /// A range pattern (e.g., `1..=2` or `1..2`).
1012 Range(Option<&'hir Expr<'hir>>, Option<&'hir Expr<'hir>>, RangeEnd),
1014 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
1016 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
1017 /// If `slice` exists, then `after` can be non-empty.
1019 /// The representation for e.g., `[a, b, .., c, d]` is:
1021 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
1023 Slice(&'hir [Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [Pat<'hir>]),
1026 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1027 pub enum BinOpKind {
1028 /// The `+` operator (addition).
1030 /// The `-` operator (subtraction).
1032 /// The `*` operator (multiplication).
1034 /// The `/` operator (division).
1036 /// The `%` operator (modulus).
1038 /// The `&&` operator (logical and).
1040 /// The `||` operator (logical or).
1042 /// The `^` operator (bitwise xor).
1044 /// The `&` operator (bitwise and).
1046 /// The `|` operator (bitwise or).
1048 /// The `<<` operator (shift left).
1050 /// The `>>` operator (shift right).
1052 /// The `==` operator (equality).
1054 /// The `<` operator (less than).
1056 /// The `<=` operator (less than or equal to).
1058 /// The `!=` operator (not equal to).
1060 /// The `>=` operator (greater than or equal to).
1062 /// The `>` operator (greater than).
1067 pub fn as_str(self) -> &'static str {
1069 BinOpKind::Add => "+",
1070 BinOpKind::Sub => "-",
1071 BinOpKind::Mul => "*",
1072 BinOpKind::Div => "/",
1073 BinOpKind::Rem => "%",
1074 BinOpKind::And => "&&",
1075 BinOpKind::Or => "||",
1076 BinOpKind::BitXor => "^",
1077 BinOpKind::BitAnd => "&",
1078 BinOpKind::BitOr => "|",
1079 BinOpKind::Shl => "<<",
1080 BinOpKind::Shr => ">>",
1081 BinOpKind::Eq => "==",
1082 BinOpKind::Lt => "<",
1083 BinOpKind::Le => "<=",
1084 BinOpKind::Ne => "!=",
1085 BinOpKind::Ge => ">=",
1086 BinOpKind::Gt => ">",
1090 pub fn is_lazy(self) -> bool {
1091 matches!(self, BinOpKind::And | BinOpKind::Or)
1094 pub fn is_shift(self) -> bool {
1095 matches!(self, BinOpKind::Shl | BinOpKind::Shr)
1098 pub fn is_comparison(self) -> bool {
1105 | BinOpKind::Ge => true,
1117 | BinOpKind::Shr => false,
1121 /// Returns `true` if the binary operator takes its arguments by value.
1122 pub fn is_by_value(self) -> bool {
1123 !self.is_comparison()
1127 impl Into<ast::BinOpKind> for BinOpKind {
1128 fn into(self) -> ast::BinOpKind {
1130 BinOpKind::Add => ast::BinOpKind::Add,
1131 BinOpKind::Sub => ast::BinOpKind::Sub,
1132 BinOpKind::Mul => ast::BinOpKind::Mul,
1133 BinOpKind::Div => ast::BinOpKind::Div,
1134 BinOpKind::Rem => ast::BinOpKind::Rem,
1135 BinOpKind::And => ast::BinOpKind::And,
1136 BinOpKind::Or => ast::BinOpKind::Or,
1137 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1138 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1139 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1140 BinOpKind::Shl => ast::BinOpKind::Shl,
1141 BinOpKind::Shr => ast::BinOpKind::Shr,
1142 BinOpKind::Eq => ast::BinOpKind::Eq,
1143 BinOpKind::Lt => ast::BinOpKind::Lt,
1144 BinOpKind::Le => ast::BinOpKind::Le,
1145 BinOpKind::Ne => ast::BinOpKind::Ne,
1146 BinOpKind::Ge => ast::BinOpKind::Ge,
1147 BinOpKind::Gt => ast::BinOpKind::Gt,
1152 pub type BinOp = Spanned<BinOpKind>;
1154 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1156 /// The `*` operator (dereferencing).
1158 /// The `!` operator (logical negation).
1160 /// The `-` operator (negation).
1165 pub fn as_str(self) -> &'static str {
1173 /// Returns `true` if the unary operator takes its argument by value.
1174 pub fn is_by_value(self) -> bool {
1175 matches!(self, Self::Neg | Self::Not)
1180 #[derive(Debug, HashStable_Generic)]
1181 pub struct Stmt<'hir> {
1183 pub kind: StmtKind<'hir>,
1187 /// The contents of a statement.
1188 #[derive(Debug, HashStable_Generic)]
1189 pub enum StmtKind<'hir> {
1190 /// A local (`let`) binding.
1191 Local(&'hir Local<'hir>),
1193 /// An item binding.
1196 /// An expression without a trailing semi-colon (must have unit type).
1197 Expr(&'hir Expr<'hir>),
1199 /// An expression with a trailing semi-colon (may have any type).
1200 Semi(&'hir Expr<'hir>),
1203 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1204 #[derive(Debug, HashStable_Generic)]
1205 pub struct Local<'hir> {
1206 pub pat: &'hir Pat<'hir>,
1207 /// Type annotation, if any (otherwise the type will be inferred).
1208 pub ty: Option<&'hir Ty<'hir>>,
1209 /// Initializer expression to set the value, if any.
1210 pub init: Option<&'hir Expr<'hir>>,
1213 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1214 /// desugaring. Otherwise will be `Normal`.
1215 pub source: LocalSource,
1218 /// Represents a single arm of a `match` expression, e.g.
1219 /// `<pat> (if <guard>) => <body>`.
1220 #[derive(Debug, HashStable_Generic)]
1221 pub struct Arm<'hir> {
1222 #[stable_hasher(ignore)]
1225 /// If this pattern and the optional guard matches, then `body` is evaluated.
1226 pub pat: &'hir Pat<'hir>,
1227 /// Optional guard clause.
1228 pub guard: Option<Guard<'hir>>,
1229 /// The expression the arm evaluates to if this arm matches.
1230 pub body: &'hir Expr<'hir>,
1233 /// Represents a `let <pat>[: <ty>] = <expr>` expression (not a Local), occurring in an `if-let` or
1234 /// `let-else`, evaluating to a boolean. Typically the pattern is refutable.
1236 /// In an if-let, imagine it as `if (let <pat> = <expr>) { ... }`; in a let-else, it is part of the
1237 /// desugaring to if-let. Only let-else supports the type annotation at present.
1238 #[derive(Debug, HashStable_Generic)]
1239 pub struct Let<'hir> {
1242 pub pat: &'hir Pat<'hir>,
1243 pub ty: Option<&'hir Ty<'hir>>,
1244 pub init: &'hir Expr<'hir>,
1247 #[derive(Debug, HashStable_Generic)]
1248 pub enum Guard<'hir> {
1249 If(&'hir Expr<'hir>),
1250 // FIXME use hir::Let for this.
1251 IfLet(&'hir Pat<'hir>, &'hir Expr<'hir>),
1254 #[derive(Debug, HashStable_Generic)]
1255 pub struct ExprField<'hir> {
1256 #[stable_hasher(ignore)]
1259 pub expr: &'hir Expr<'hir>,
1261 pub is_shorthand: bool,
1264 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1265 pub enum BlockCheckMode {
1267 UnsafeBlock(UnsafeSource),
1270 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1271 pub enum UnsafeSource {
1276 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
1281 /// The body of a function, closure, or constant value. In the case of
1282 /// a function, the body contains not only the function body itself
1283 /// (which is an expression), but also the argument patterns, since
1284 /// those are something that the caller doesn't really care about.
1289 /// fn foo((x, y): (u32, u32)) -> u32 {
1294 /// Here, the `Body` associated with `foo()` would contain:
1296 /// - an `params` array containing the `(x, y)` pattern
1297 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1298 /// - `generator_kind` would be `None`
1300 /// All bodies have an **owner**, which can be accessed via the HIR
1301 /// map using `body_owner_def_id()`.
1302 #[derive(Debug, HashStable_Generic)]
1303 pub struct Body<'hir> {
1304 pub params: &'hir [Param<'hir>],
1305 pub value: Expr<'hir>,
1306 pub generator_kind: Option<GeneratorKind>,
1309 impl<'hir> Body<'hir> {
1310 pub fn id(&self) -> BodyId {
1311 BodyId { hir_id: self.value.hir_id }
1314 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1319 /// The type of source expression that caused this generator to be created.
1332 pub enum GeneratorKind {
1333 /// An explicit `async` block or the body of an async function.
1334 Async(AsyncGeneratorKind),
1336 /// A generator literal created via a `yield` inside a closure.
1340 impl fmt::Display for GeneratorKind {
1341 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1343 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1344 GeneratorKind::Gen => f.write_str("generator"),
1349 impl GeneratorKind {
1350 pub fn descr(&self) -> &'static str {
1352 GeneratorKind::Async(ask) => ask.descr(),
1353 GeneratorKind::Gen => "generator",
1358 /// In the case of a generator created as part of an async construct,
1359 /// which kind of async construct caused it to be created?
1361 /// This helps error messages but is also used to drive coercions in
1362 /// type-checking (see #60424).
1375 pub enum AsyncGeneratorKind {
1376 /// An explicit `async` block written by the user.
1379 /// An explicit `async` block written by the user.
1382 /// The `async` block generated as the body of an async function.
1386 impl fmt::Display for AsyncGeneratorKind {
1387 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1388 f.write_str(match self {
1389 AsyncGeneratorKind::Block => "`async` block",
1390 AsyncGeneratorKind::Closure => "`async` closure body",
1391 AsyncGeneratorKind::Fn => "`async fn` body",
1396 impl AsyncGeneratorKind {
1397 pub fn descr(&self) -> &'static str {
1399 AsyncGeneratorKind::Block => "`async` block",
1400 AsyncGeneratorKind::Closure => "`async` closure body",
1401 AsyncGeneratorKind::Fn => "`async fn` body",
1406 #[derive(Copy, Clone, Debug)]
1407 pub enum BodyOwnerKind {
1408 /// Functions and methods.
1414 /// Constants and associated constants.
1417 /// Initializer of a `static` item.
1421 impl BodyOwnerKind {
1422 pub fn is_fn_or_closure(self) -> bool {
1424 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1425 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1430 /// The kind of an item that requires const-checking.
1431 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1432 pub enum ConstContext {
1436 /// A `static` or `static mut`.
1439 /// A `const`, associated `const`, or other const context.
1441 /// Other contexts include:
1442 /// - Array length expressions
1443 /// - Enum discriminants
1444 /// - Const generics
1446 /// For the most part, other contexts are treated just like a regular `const`, so they are
1447 /// lumped into the same category.
1452 /// A description of this const context that can appear between backticks in an error message.
1454 /// E.g. `const` or `static mut`.
1455 pub fn keyword_name(self) -> &'static str {
1457 Self::Const => "const",
1458 Self::Static(Mutability::Not) => "static",
1459 Self::Static(Mutability::Mut) => "static mut",
1460 Self::ConstFn => "const fn",
1465 /// A colloquial, trivially pluralizable description of this const context for use in error
1467 impl fmt::Display for ConstContext {
1468 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1470 Self::Const => write!(f, "constant"),
1471 Self::Static(_) => write!(f, "static"),
1472 Self::ConstFn => write!(f, "constant function"),
1478 pub type Lit = Spanned<LitKind>;
1480 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1487 pub fn hir_id(&self) -> HirId {
1489 &ArrayLen::Infer(hir_id, _) | &ArrayLen::Body(AnonConst { hir_id, body: _ }) => hir_id,
1494 /// A constant (expression) that's not an item or associated item,
1495 /// but needs its own `DefId` for type-checking, const-eval, etc.
1496 /// These are usually found nested inside types (e.g., array lengths)
1497 /// or expressions (e.g., repeat counts), and also used to define
1498 /// explicit discriminant values for enum variants.
1500 /// You can check if this anon const is a default in a const param
1501 /// `const N: usize = { ... }` with `tcx.hir().opt_const_param_default_param_hir_id(..)`
1502 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1503 pub struct AnonConst {
1510 pub struct Expr<'hir> {
1512 pub kind: ExprKind<'hir>,
1517 pub fn precedence(&self) -> ExprPrecedence {
1519 ExprKind::Box(_) => ExprPrecedence::Box,
1520 ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1521 ExprKind::Array(_) => ExprPrecedence::Array,
1522 ExprKind::Call(..) => ExprPrecedence::Call,
1523 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1524 ExprKind::Tup(_) => ExprPrecedence::Tup,
1525 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1526 ExprKind::Unary(..) => ExprPrecedence::Unary,
1527 ExprKind::Lit(_) => ExprPrecedence::Lit,
1528 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1529 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1530 ExprKind::If(..) => ExprPrecedence::If,
1531 ExprKind::Let(..) => ExprPrecedence::Let,
1532 ExprKind::Loop(..) => ExprPrecedence::Loop,
1533 ExprKind::Match(..) => ExprPrecedence::Match,
1534 ExprKind::Closure(..) => ExprPrecedence::Closure,
1535 ExprKind::Block(..) => ExprPrecedence::Block,
1536 ExprKind::Assign(..) => ExprPrecedence::Assign,
1537 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1538 ExprKind::Field(..) => ExprPrecedence::Field,
1539 ExprKind::Index(..) => ExprPrecedence::Index,
1540 ExprKind::Path(..) => ExprPrecedence::Path,
1541 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1542 ExprKind::Break(..) => ExprPrecedence::Break,
1543 ExprKind::Continue(..) => ExprPrecedence::Continue,
1544 ExprKind::Ret(..) => ExprPrecedence::Ret,
1545 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1546 ExprKind::Struct(..) => ExprPrecedence::Struct,
1547 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1548 ExprKind::Yield(..) => ExprPrecedence::Yield,
1549 ExprKind::Err => ExprPrecedence::Err,
1553 // Whether this looks like a place expr, without checking for deref
1555 // This will return `true` in some potentially surprising cases such as
1556 // `CONSTANT.field`.
1557 pub fn is_syntactic_place_expr(&self) -> bool {
1558 self.is_place_expr(|_| true)
1561 /// Whether this is a place expression.
1563 /// `allow_projections_from` should return `true` if indexing a field or index expression based
1564 /// on the given expression should be considered a place expression.
1565 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1567 ExprKind::Path(QPath::Resolved(_, ref path)) => {
1568 matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static(_), _) | Res::Err)
1571 // Type ascription inherits its place expression kind from its
1573 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1574 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1576 ExprKind::Unary(UnOp::Deref, _) => true,
1578 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1579 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1582 // Lang item paths cannot currently be local variables or statics.
1583 ExprKind::Path(QPath::LangItem(..)) => false,
1585 // Partially qualified paths in expressions can only legally
1586 // refer to associated items which are always rvalues.
1587 ExprKind::Path(QPath::TypeRelative(..))
1588 | ExprKind::Call(..)
1589 | ExprKind::MethodCall(..)
1590 | ExprKind::Struct(..)
1593 | ExprKind::Match(..)
1594 | ExprKind::Closure(..)
1595 | ExprKind::Block(..)
1596 | ExprKind::Repeat(..)
1597 | ExprKind::Array(..)
1598 | ExprKind::Break(..)
1599 | ExprKind::Continue(..)
1602 | ExprKind::Loop(..)
1603 | ExprKind::Assign(..)
1604 | ExprKind::InlineAsm(..)
1605 | ExprKind::AssignOp(..)
1607 | ExprKind::ConstBlock(..)
1608 | ExprKind::Unary(..)
1610 | ExprKind::AddrOf(..)
1611 | ExprKind::Binary(..)
1612 | ExprKind::Yield(..)
1613 | ExprKind::Cast(..)
1614 | ExprKind::DropTemps(..)
1615 | ExprKind::Err => false,
1619 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1620 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1621 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1622 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1623 /// beyond remembering to call this function before doing analysis on it.
1624 pub fn peel_drop_temps(&self) -> &Self {
1625 let mut expr = self;
1626 while let ExprKind::DropTemps(inner) = &expr.kind {
1632 pub fn peel_blocks(&self) -> &Self {
1633 let mut expr = self;
1634 while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind {
1640 pub fn can_have_side_effects(&self) -> bool {
1641 match self.peel_drop_temps().kind {
1642 ExprKind::Path(_) | ExprKind::Lit(_) => false,
1643 ExprKind::Type(base, _)
1644 | ExprKind::Unary(_, base)
1645 | ExprKind::Field(base, _)
1646 | ExprKind::Index(base, _)
1647 | ExprKind::AddrOf(.., base)
1648 | ExprKind::Cast(base, _) => {
1649 // This isn't exactly true for `Index` and all `Unary`, but we are using this
1650 // method exclusively for diagnostics and there's a *cultural* pressure against
1651 // them being used only for its side-effects.
1652 base.can_have_side_effects()
1654 ExprKind::Struct(_, fields, init) => fields
1656 .map(|field| field.expr)
1657 .chain(init.into_iter())
1658 .all(|e| e.can_have_side_effects()),
1660 ExprKind::Array(args)
1661 | ExprKind::Tup(args)
1665 ExprKind::Path(QPath::Resolved(
1667 Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. },
1672 ) => args.iter().all(|arg| arg.can_have_side_effects()),
1674 | ExprKind::Match(..)
1675 | ExprKind::MethodCall(..)
1676 | ExprKind::Call(..)
1677 | ExprKind::Closure(..)
1678 | ExprKind::Block(..)
1679 | ExprKind::Repeat(..)
1680 | ExprKind::Break(..)
1681 | ExprKind::Continue(..)
1684 | ExprKind::Loop(..)
1685 | ExprKind::Assign(..)
1686 | ExprKind::InlineAsm(..)
1687 | ExprKind::AssignOp(..)
1688 | ExprKind::ConstBlock(..)
1690 | ExprKind::Binary(..)
1691 | ExprKind::Yield(..)
1692 | ExprKind::DropTemps(..)
1693 | ExprKind::Err => true,
1698 /// Checks if the specified expression is a built-in range literal.
1699 /// (See: `LoweringContext::lower_expr()`).
1700 pub fn is_range_literal(expr: &Expr<'_>) -> bool {
1702 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1703 ExprKind::Struct(ref qpath, _, _) => matches!(
1708 | LangItem::RangeFrom
1709 | LangItem::RangeFull
1710 | LangItem::RangeToInclusive,
1715 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1716 ExprKind::Call(ref func, _) => {
1717 matches!(func.kind, ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, ..)))
1724 #[derive(Debug, HashStable_Generic)]
1725 pub enum ExprKind<'hir> {
1726 /// A `box x` expression.
1727 Box(&'hir Expr<'hir>),
1728 /// Allow anonymous constants from an inline `const` block
1729 ConstBlock(AnonConst),
1730 /// An array (e.g., `[a, b, c, d]`).
1731 Array(&'hir [Expr<'hir>]),
1732 /// A function call.
1734 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1735 /// and the second field is the list of arguments.
1736 /// This also represents calling the constructor of
1737 /// tuple-like ADTs such as tuple structs and enum variants.
1738 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1739 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1741 /// The `PathSegment` represents the method name and its generic arguments
1742 /// (within the angle brackets).
1743 /// The first element of the `&[Expr]` is the expression that evaluates
1744 /// to the object on which the method is being called on (the receiver),
1745 /// and the remaining elements are the rest of the arguments.
1746 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1747 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d], span)`.
1748 /// The final `Span` represents the span of the function and arguments
1749 /// (e.g. `foo::<Bar, Baz>(a, b, c, d)` in `x.foo::<Bar, Baz>(a, b, c, d)`
1751 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1752 /// the `hir_id` of the `MethodCall` node itself.
1754 /// [`type_dependent_def_id`]: ../ty/struct.TypeckResults.html#method.type_dependent_def_id
1755 MethodCall(&'hir PathSegment<'hir>, &'hir [Expr<'hir>], Span),
1756 /// A tuple (e.g., `(a, b, c, d)`).
1757 Tup(&'hir [Expr<'hir>]),
1758 /// A binary operation (e.g., `a + b`, `a * b`).
1759 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1760 /// A unary operation (e.g., `!x`, `*x`).
1761 Unary(UnOp, &'hir Expr<'hir>),
1762 /// A literal (e.g., `1`, `"foo"`).
1764 /// A cast (e.g., `foo as f64`).
1765 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1766 /// A type reference (e.g., `Foo`).
1767 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1768 /// Wraps the expression in a terminating scope.
1769 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1771 /// This construct only exists to tweak the drop order in HIR lowering.
1772 /// An example of that is the desugaring of `for` loops.
1773 DropTemps(&'hir Expr<'hir>),
1774 /// A `let $pat = $expr` expression.
1776 /// These are not `Local` and only occur as expressions.
1777 /// The `let Some(x) = foo()` in `if let Some(x) = foo()` is an example of `Let(..)`.
1778 Let(&'hir Let<'hir>),
1779 /// An `if` block, with an optional else block.
1781 /// I.e., `if <expr> { <expr> } else { <expr> }`.
1782 If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
1783 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1785 /// I.e., `'label: loop { <block> }`.
1787 /// The `Span` is the loop header (`for x in y`/`while let pat = expr`).
1788 Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span),
1789 /// A `match` block, with a source that indicates whether or not it is
1790 /// the result of a desugaring, and if so, which kind.
1791 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1792 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1794 /// The `Span` is the argument block `|...|`.
1796 /// This may also be a generator literal or an `async block` as indicated by the
1797 /// `Option<Movability>`.
1798 Closure(CaptureBy, &'hir FnDecl<'hir>, BodyId, Span, Option<Movability>),
1799 /// A block (e.g., `'label: { ... }`).
1800 Block(&'hir Block<'hir>, Option<Label>),
1802 /// An assignment (e.g., `a = foo()`).
1803 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1804 /// An assignment with an operator.
1807 AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1808 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1809 Field(&'hir Expr<'hir>, Ident),
1810 /// An indexing operation (`foo[2]`).
1811 Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1813 /// Path to a definition, possibly containing lifetime or type parameters.
1816 /// A referencing operation (i.e., `&a` or `&mut a`).
1817 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1818 /// A `break`, with an optional label to break.
1819 Break(Destination, Option<&'hir Expr<'hir>>),
1820 /// A `continue`, with an optional label.
1821 Continue(Destination),
1822 /// A `return`, with an optional value to be returned.
1823 Ret(Option<&'hir Expr<'hir>>),
1825 /// Inline assembly (from `asm!`), with its outputs and inputs.
1826 InlineAsm(&'hir InlineAsm<'hir>),
1828 /// A struct or struct-like variant literal expression.
1830 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1831 /// where `base` is the `Option<Expr>`.
1832 Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], Option<&'hir Expr<'hir>>),
1834 /// An array literal constructed from one repeated element.
1836 /// E.g., `[1; 5]`. The first expression is the element
1837 /// to be repeated; the second is the number of times to repeat it.
1838 Repeat(&'hir Expr<'hir>, ArrayLen),
1840 /// A suspension point for generators (i.e., `yield <expr>`).
1841 Yield(&'hir Expr<'hir>, YieldSource),
1843 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1847 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1849 /// To resolve the path to a `DefId`, call [`qpath_res`].
1851 /// [`qpath_res`]: ../rustc_middle/ty/struct.TypeckResults.html#method.qpath_res
1852 #[derive(Debug, HashStable_Generic)]
1853 pub enum QPath<'hir> {
1854 /// Path to a definition, optionally "fully-qualified" with a `Self`
1855 /// type, if the path points to an associated item in a trait.
1857 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1858 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1859 /// even though they both have the same two-segment `Clone::clone` `Path`.
1860 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
1862 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1863 /// Will be resolved by type-checking to an associated item.
1865 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1866 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1867 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1868 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
1870 /// Reference to a `#[lang = "foo"]` item. `HirId` of the inner expr.
1871 LangItem(LangItem, Span, Option<HirId>),
1874 impl<'hir> QPath<'hir> {
1875 /// Returns the span of this `QPath`.
1876 pub fn span(&self) -> Span {
1878 QPath::Resolved(_, path) => path.span,
1879 QPath::TypeRelative(qself, ps) => qself.span.to(ps.ident.span),
1880 QPath::LangItem(_, span, _) => span,
1884 /// Returns the span of the qself of this `QPath`. For example, `()` in
1885 /// `<() as Trait>::method`.
1886 pub fn qself_span(&self) -> Span {
1888 QPath::Resolved(_, path) => path.span,
1889 QPath::TypeRelative(qself, _) => qself.span,
1890 QPath::LangItem(_, span, _) => span,
1894 /// Returns the span of the last segment of this `QPath`. For example, `method` in
1895 /// `<() as Trait>::method`.
1896 pub fn last_segment_span(&self) -> Span {
1898 QPath::Resolved(_, path) => path.segments.last().unwrap().ident.span,
1899 QPath::TypeRelative(_, segment) => segment.ident.span,
1900 QPath::LangItem(_, span, _) => span,
1905 /// Hints at the original code for a let statement.
1906 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1907 pub enum LocalSource {
1908 /// A `match _ { .. }`.
1910 /// When lowering async functions, we create locals within the `async move` so that
1911 /// all parameters are dropped after the future is polled.
1913 /// ```ignore (pseudo-Rust)
1914 /// async fn foo(<pattern> @ x: Type) {
1916 /// let <pattern> = x;
1921 /// A desugared `<expr>.await`.
1923 /// A desugared `expr = expr`, where the LHS is a tuple, struct or array.
1924 /// The span is that of the `=` sign.
1925 AssignDesugar(Span),
1928 /// Hints at the original code for a `match _ { .. }`.
1929 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
1930 #[derive(HashStable_Generic)]
1931 pub enum MatchSource {
1932 /// A `match _ { .. }`.
1934 /// A desugared `for _ in _ { .. }` loop.
1936 /// A desugared `?` operator.
1938 /// A desugared `<expr>.await`.
1944 pub const fn name(self) -> &'static str {
1948 ForLoopDesugar => "for",
1950 AwaitDesugar => ".await",
1955 /// The loop type that yielded an `ExprKind::Loop`.
1956 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1957 pub enum LoopSource {
1958 /// A `loop { .. }` loop.
1960 /// A `while _ { .. }` loop.
1962 /// A `for _ in _ { .. }` loop.
1967 pub fn name(self) -> &'static str {
1969 LoopSource::Loop => "loop",
1970 LoopSource::While => "while",
1971 LoopSource::ForLoop => "for",
1976 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1977 pub enum LoopIdError {
1979 UnlabeledCfInWhileCondition,
1983 impl fmt::Display for LoopIdError {
1984 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1985 f.write_str(match self {
1986 LoopIdError::OutsideLoopScope => "not inside loop scope",
1987 LoopIdError::UnlabeledCfInWhileCondition => {
1988 "unlabeled control flow (break or continue) in while condition"
1990 LoopIdError::UnresolvedLabel => "label not found",
1995 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1996 pub struct Destination {
1997 // This is `Some(_)` iff there is an explicit user-specified `label
1998 pub label: Option<Label>,
2000 // These errors are caught and then reported during the diagnostics pass in
2001 // librustc_passes/loops.rs
2002 pub target_id: Result<HirId, LoopIdError>,
2005 /// The yield kind that caused an `ExprKind::Yield`.
2006 #[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
2007 pub enum YieldSource {
2008 /// An `<expr>.await`.
2009 Await { expr: Option<HirId> },
2010 /// A plain `yield`.
2015 pub fn is_await(&self) -> bool {
2017 YieldSource::Await { .. } => true,
2018 YieldSource::Yield => false,
2023 impl fmt::Display for YieldSource {
2024 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2025 f.write_str(match self {
2026 YieldSource::Await { .. } => "`await`",
2027 YieldSource::Yield => "`yield`",
2032 impl From<GeneratorKind> for YieldSource {
2033 fn from(kind: GeneratorKind) -> Self {
2035 // Guess based on the kind of the current generator.
2036 GeneratorKind::Gen => Self::Yield,
2037 GeneratorKind::Async(_) => Self::Await { expr: None },
2042 // N.B., if you change this, you'll probably want to change the corresponding
2043 // type structure in middle/ty.rs as well.
2044 #[derive(Debug, HashStable_Generic)]
2045 pub struct MutTy<'hir> {
2046 pub ty: &'hir Ty<'hir>,
2047 pub mutbl: Mutability,
2050 /// Represents a function's signature in a trait declaration,
2051 /// trait implementation, or a free function.
2052 #[derive(Debug, HashStable_Generic)]
2053 pub struct FnSig<'hir> {
2054 pub header: FnHeader,
2055 pub decl: &'hir FnDecl<'hir>,
2059 // The bodies for items are stored "out of line", in a separate
2060 // hashmap in the `Crate`. Here we just record the hir-id of the item
2061 // so it can fetched later.
2062 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
2063 pub struct TraitItemId {
2064 pub def_id: LocalDefId,
2069 pub fn hir_id(&self) -> HirId {
2070 // Items are always HIR owners.
2071 HirId::make_owner(self.def_id)
2075 /// Represents an item declaration within a trait declaration,
2076 /// possibly including a default implementation. A trait item is
2077 /// either required (meaning it doesn't have an implementation, just a
2078 /// signature) or provided (meaning it has a default implementation).
2079 #[derive(Debug, HashStable_Generic)]
2080 pub struct TraitItem<'hir> {
2082 pub def_id: LocalDefId,
2083 pub generics: Generics<'hir>,
2084 pub kind: TraitItemKind<'hir>,
2088 impl TraitItem<'_> {
2090 pub fn hir_id(&self) -> HirId {
2091 // Items are always HIR owners.
2092 HirId::make_owner(self.def_id)
2095 pub fn trait_item_id(&self) -> TraitItemId {
2096 TraitItemId { def_id: self.def_id }
2100 /// Represents a trait method's body (or just argument names).
2101 #[derive(Encodable, Debug, HashStable_Generic)]
2102 pub enum TraitFn<'hir> {
2103 /// No default body in the trait, just a signature.
2104 Required(&'hir [Ident]),
2106 /// Both signature and body are provided in the trait.
2110 /// Represents a trait method or associated constant or type
2111 #[derive(Debug, HashStable_Generic)]
2112 pub enum TraitItemKind<'hir> {
2113 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
2114 Const(&'hir Ty<'hir>, Option<BodyId>),
2115 /// An associated function with an optional body.
2116 Fn(FnSig<'hir>, TraitFn<'hir>),
2117 /// An associated type with (possibly empty) bounds and optional concrete
2119 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
2122 // The bodies for items are stored "out of line", in a separate
2123 // hashmap in the `Crate`. Here we just record the hir-id of the item
2124 // so it can fetched later.
2125 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
2126 pub struct ImplItemId {
2127 pub def_id: LocalDefId,
2132 pub fn hir_id(&self) -> HirId {
2133 // Items are always HIR owners.
2134 HirId::make_owner(self.def_id)
2138 /// Represents anything within an `impl` block.
2139 #[derive(Debug, HashStable_Generic)]
2140 pub struct ImplItem<'hir> {
2142 pub def_id: LocalDefId,
2143 pub generics: Generics<'hir>,
2144 pub kind: ImplItemKind<'hir>,
2151 pub fn hir_id(&self) -> HirId {
2152 // Items are always HIR owners.
2153 HirId::make_owner(self.def_id)
2156 pub fn impl_item_id(&self) -> ImplItemId {
2157 ImplItemId { def_id: self.def_id }
2161 /// Represents various kinds of content within an `impl`.
2162 #[derive(Debug, HashStable_Generic)]
2163 pub enum ImplItemKind<'hir> {
2164 /// An associated constant of the given type, set to the constant result
2165 /// of the expression.
2166 Const(&'hir Ty<'hir>, BodyId),
2167 /// An associated function implementation with the given signature and body.
2168 Fn(FnSig<'hir>, BodyId),
2169 /// An associated type.
2170 TyAlias(&'hir Ty<'hir>),
2173 // The name of the associated type for `Fn` return types.
2174 pub const FN_OUTPUT_NAME: Symbol = sym::Output;
2176 /// Bind a type to an associated type (i.e., `A = Foo`).
2178 /// Bindings like `A: Debug` are represented as a special type `A =
2179 /// $::Debug` that is understood by the astconv code.
2181 /// FIXME(alexreg): why have a separate type for the binding case,
2182 /// wouldn't it be better to make the `ty` field an enum like the
2186 /// enum TypeBindingKind {
2191 #[derive(Debug, HashStable_Generic)]
2192 pub struct TypeBinding<'hir> {
2195 pub gen_args: &'hir GenericArgs<'hir>,
2196 pub kind: TypeBindingKind<'hir>,
2200 #[derive(Debug, HashStable_Generic)]
2201 pub enum Term<'hir> {
2206 impl<'hir> From<&'hir Ty<'hir>> for Term<'hir> {
2207 fn from(ty: &'hir Ty<'hir>) -> Self {
2212 impl<'hir> From<AnonConst> for Term<'hir> {
2213 fn from(c: AnonConst) -> Self {
2218 // Represents the two kinds of type bindings.
2219 #[derive(Debug, HashStable_Generic)]
2220 pub enum TypeBindingKind<'hir> {
2221 /// E.g., `Foo<Bar: Send>`.
2222 Constraint { bounds: &'hir [GenericBound<'hir>] },
2223 /// E.g., `Foo<Bar = ()>`, `Foo<Bar = ()>`
2224 Equality { term: Term<'hir> },
2227 impl TypeBinding<'_> {
2228 pub fn ty(&self) -> &Ty<'_> {
2230 TypeBindingKind::Equality { term: Term::Ty(ref ty) } => ty,
2231 _ => panic!("expected equality type binding for parenthesized generic args"),
2234 pub fn opt_const(&self) -> Option<&'_ AnonConst> {
2236 TypeBindingKind::Equality { term: Term::Const(ref c) } => Some(c),
2243 pub struct Ty<'hir> {
2245 pub kind: TyKind<'hir>,
2249 /// Not represented directly in the AST; referred to by name through a `ty_path`.
2250 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
2251 #[derive(HashStable_Generic)]
2262 /// All of the primitive types
2263 pub const ALL: [Self; 17] = [
2264 // any changes here should also be reflected in `PrimTy::from_name`
2265 Self::Int(IntTy::I8),
2266 Self::Int(IntTy::I16),
2267 Self::Int(IntTy::I32),
2268 Self::Int(IntTy::I64),
2269 Self::Int(IntTy::I128),
2270 Self::Int(IntTy::Isize),
2271 Self::Uint(UintTy::U8),
2272 Self::Uint(UintTy::U16),
2273 Self::Uint(UintTy::U32),
2274 Self::Uint(UintTy::U64),
2275 Self::Uint(UintTy::U128),
2276 Self::Uint(UintTy::Usize),
2277 Self::Float(FloatTy::F32),
2278 Self::Float(FloatTy::F64),
2284 /// Like [`PrimTy::name`], but returns a &str instead of a symbol.
2287 pub fn name_str(self) -> &'static str {
2289 PrimTy::Int(i) => i.name_str(),
2290 PrimTy::Uint(u) => u.name_str(),
2291 PrimTy::Float(f) => f.name_str(),
2292 PrimTy::Str => "str",
2293 PrimTy::Bool => "bool",
2294 PrimTy::Char => "char",
2298 pub fn name(self) -> Symbol {
2300 PrimTy::Int(i) => i.name(),
2301 PrimTy::Uint(u) => u.name(),
2302 PrimTy::Float(f) => f.name(),
2303 PrimTy::Str => sym::str,
2304 PrimTy::Bool => sym::bool,
2305 PrimTy::Char => sym::char,
2309 /// Returns the matching `PrimTy` for a `Symbol` such as "str" or "i32".
2310 /// Returns `None` if no matching type is found.
2311 pub fn from_name(name: Symbol) -> Option<Self> {
2312 let ty = match name {
2313 // any changes here should also be reflected in `PrimTy::ALL`
2314 sym::i8 => Self::Int(IntTy::I8),
2315 sym::i16 => Self::Int(IntTy::I16),
2316 sym::i32 => Self::Int(IntTy::I32),
2317 sym::i64 => Self::Int(IntTy::I64),
2318 sym::i128 => Self::Int(IntTy::I128),
2319 sym::isize => Self::Int(IntTy::Isize),
2320 sym::u8 => Self::Uint(UintTy::U8),
2321 sym::u16 => Self::Uint(UintTy::U16),
2322 sym::u32 => Self::Uint(UintTy::U32),
2323 sym::u64 => Self::Uint(UintTy::U64),
2324 sym::u128 => Self::Uint(UintTy::U128),
2325 sym::usize => Self::Uint(UintTy::Usize),
2326 sym::f32 => Self::Float(FloatTy::F32),
2327 sym::f64 => Self::Float(FloatTy::F64),
2328 sym::bool => Self::Bool,
2329 sym::char => Self::Char,
2330 sym::str => Self::Str,
2337 #[derive(Debug, HashStable_Generic)]
2338 pub struct BareFnTy<'hir> {
2339 pub unsafety: Unsafety,
2341 pub generic_params: &'hir [GenericParam<'hir>],
2342 pub decl: &'hir FnDecl<'hir>,
2343 pub param_names: &'hir [Ident],
2346 #[derive(Debug, HashStable_Generic)]
2347 pub struct OpaqueTy<'hir> {
2348 pub generics: Generics<'hir>,
2349 pub bounds: GenericBounds<'hir>,
2350 pub origin: OpaqueTyOrigin,
2353 /// From whence the opaque type came.
2354 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2355 pub enum OpaqueTyOrigin {
2357 FnReturn(LocalDefId),
2359 AsyncFn(LocalDefId),
2360 /// type aliases: `type Foo = impl Trait;`
2364 /// The various kinds of types recognized by the compiler.
2365 #[derive(Debug, HashStable_Generic)]
2366 pub enum TyKind<'hir> {
2367 /// A variable length slice (i.e., `[T]`).
2368 Slice(&'hir Ty<'hir>),
2369 /// A fixed length array (i.e., `[T; n]`).
2370 Array(&'hir Ty<'hir>, ArrayLen),
2371 /// A raw pointer (i.e., `*const T` or `*mut T`).
2373 /// A reference (i.e., `&'a T` or `&'a mut T`).
2374 Rptr(Lifetime, MutTy<'hir>),
2375 /// A bare function (e.g., `fn(usize) -> bool`).
2376 BareFn(&'hir BareFnTy<'hir>),
2377 /// The never type (`!`).
2379 /// A tuple (`(A, B, C, D, ...)`).
2380 Tup(&'hir [Ty<'hir>]),
2381 /// A path to a type definition (`module::module::...::Type`), or an
2382 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2384 /// Type parameters may be stored in each `PathSegment`.
2386 /// An opaque type definition itself. This is only used for `impl Trait`.
2388 /// The generic argument list contains the lifetimes (and in the future
2389 /// possibly parameters) that are actually bound on the `impl Trait`.
2390 OpaqueDef(ItemId, &'hir [GenericArg<'hir>]),
2391 /// A trait object type `Bound1 + Bound2 + Bound3`
2392 /// where `Bound` is a trait or a lifetime.
2393 TraitObject(&'hir [PolyTraitRef<'hir>], Lifetime, TraitObjectSyntax),
2396 /// `TyKind::Infer` means the type should be inferred instead of it having been
2397 /// specified. This can appear anywhere in a type.
2399 /// Placeholder for a type that has failed to be defined.
2403 #[derive(Debug, HashStable_Generic)]
2404 pub enum InlineAsmOperand<'hir> {
2406 reg: InlineAsmRegOrRegClass,
2410 reg: InlineAsmRegOrRegClass,
2412 expr: Option<Expr<'hir>>,
2415 reg: InlineAsmRegOrRegClass,
2420 reg: InlineAsmRegOrRegClass,
2422 in_expr: Expr<'hir>,
2423 out_expr: Option<Expr<'hir>>,
2426 anon_const: AnonConst,
2429 anon_const: AnonConst,
2437 impl<'hir> InlineAsmOperand<'hir> {
2438 pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
2440 Self::In { reg, .. }
2441 | Self::Out { reg, .. }
2442 | Self::InOut { reg, .. }
2443 | Self::SplitInOut { reg, .. } => Some(reg),
2444 Self::Const { .. } | Self::SymFn { .. } | Self::SymStatic { .. } => None,
2448 pub fn is_clobber(&self) -> bool {
2451 InlineAsmOperand::Out { reg: InlineAsmRegOrRegClass::Reg(_), late: _, expr: None }
2456 #[derive(Debug, HashStable_Generic)]
2457 pub struct InlineAsm<'hir> {
2458 pub template: &'hir [InlineAsmTemplatePiece],
2459 pub template_strs: &'hir [(Symbol, Option<Symbol>, Span)],
2460 pub operands: &'hir [(InlineAsmOperand<'hir>, Span)],
2461 pub options: InlineAsmOptions,
2462 pub line_spans: &'hir [Span],
2465 /// Represents a parameter in a function header.
2466 #[derive(Debug, HashStable_Generic)]
2467 pub struct Param<'hir> {
2469 pub pat: &'hir Pat<'hir>,
2474 /// Represents the header (not the body) of a function declaration.
2475 #[derive(Debug, HashStable_Generic)]
2476 pub struct FnDecl<'hir> {
2477 /// The types of the function's parameters.
2479 /// Additional argument data is stored in the function's [body](Body::params).
2480 pub inputs: &'hir [Ty<'hir>],
2481 pub output: FnRetTy<'hir>,
2482 pub c_variadic: bool,
2483 /// Does the function have an implicit self?
2484 pub implicit_self: ImplicitSelfKind,
2487 /// Represents what type of implicit self a function has, if any.
2488 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2489 pub enum ImplicitSelfKind {
2490 /// Represents a `fn x(self);`.
2492 /// Represents a `fn x(mut self);`.
2494 /// Represents a `fn x(&self);`.
2496 /// Represents a `fn x(&mut self);`.
2498 /// Represents when a function does not have a self argument or
2499 /// when a function has a `self: X` argument.
2503 impl ImplicitSelfKind {
2504 /// Does this represent an implicit self?
2505 pub fn has_implicit_self(&self) -> bool {
2506 !matches!(*self, ImplicitSelfKind::None)
2510 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable, Debug)]
2511 #[derive(HashStable_Generic)]
2517 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable, HashStable_Generic)]
2518 pub enum Defaultness {
2519 Default { has_value: bool },
2524 pub fn has_value(&self) -> bool {
2526 Defaultness::Default { has_value } => has_value,
2527 Defaultness::Final => true,
2531 pub fn is_final(&self) -> bool {
2532 *self == Defaultness::Final
2535 pub fn is_default(&self) -> bool {
2536 matches!(*self, Defaultness::Default { .. })
2540 #[derive(Debug, HashStable_Generic)]
2541 pub enum FnRetTy<'hir> {
2542 /// Return type is not specified.
2544 /// Functions default to `()` and
2545 /// closures default to inference. Span points to where return
2546 /// type would be inserted.
2547 DefaultReturn(Span),
2548 /// Everything else.
2549 Return(&'hir Ty<'hir>),
2554 pub fn span(&self) -> Span {
2556 Self::DefaultReturn(span) => span,
2557 Self::Return(ref ty) => ty.span,
2562 #[derive(Encodable, Debug, HashStable_Generic)]
2563 pub struct Mod<'hir> {
2564 pub spans: ModSpans,
2565 pub item_ids: &'hir [ItemId],
2568 #[derive(Copy, Clone, Debug, HashStable_Generic, Encodable)]
2569 pub struct ModSpans {
2570 /// A span from the first token past `{` to the last token until `}`.
2571 /// For `mod foo;`, the inner span ranges from the first token
2572 /// to the last token in the external file.
2573 pub inner_span: Span,
2574 pub inject_use_span: Span,
2577 #[derive(Debug, HashStable_Generic)]
2578 pub struct EnumDef<'hir> {
2579 pub variants: &'hir [Variant<'hir>],
2582 #[derive(Debug, HashStable_Generic)]
2583 pub struct Variant<'hir> {
2584 /// Name of the variant.
2586 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2588 /// Fields and constructor id of the variant.
2589 pub data: VariantData<'hir>,
2590 /// Explicit discriminant (e.g., `Foo = 1`).
2591 pub disr_expr: Option<AnonConst>,
2596 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2598 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2599 /// Also produced for each element of a list `use`, e.g.
2600 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2603 /// Glob import, e.g., `use foo::*`.
2606 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2607 /// an additional `use foo::{}` for performing checks such as
2608 /// unstable feature gating. May be removed in the future.
2612 /// References to traits in impls.
2614 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2615 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2616 /// trait being referred to but just a unique `HirId` that serves as a key
2617 /// within the resolution map.
2618 #[derive(Clone, Debug, HashStable_Generic)]
2619 pub struct TraitRef<'hir> {
2620 pub path: &'hir Path<'hir>,
2621 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2622 #[stable_hasher(ignore)]
2623 pub hir_ref_id: HirId,
2627 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2628 pub fn trait_def_id(&self) -> Option<DefId> {
2629 match self.path.res {
2630 Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
2632 _ => unreachable!(),
2637 #[derive(Clone, Debug, HashStable_Generic)]
2638 pub struct PolyTraitRef<'hir> {
2639 /// The `'a` in `for<'a> Foo<&'a T>`.
2640 pub bound_generic_params: &'hir [GenericParam<'hir>],
2642 /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
2643 pub trait_ref: TraitRef<'hir>,
2648 #[derive(Debug, HashStable_Generic)]
2649 pub struct FieldDef<'hir> {
2654 pub ty: &'hir Ty<'hir>,
2658 // Still necessary in couple of places
2659 pub fn is_positional(&self) -> bool {
2660 let first = self.ident.as_str().as_bytes()[0];
2661 (b'0'..=b'9').contains(&first)
2665 /// Fields and constructor IDs of enum variants and structs.
2666 #[derive(Debug, HashStable_Generic)]
2667 pub enum VariantData<'hir> {
2668 /// A struct variant.
2670 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2671 Struct(&'hir [FieldDef<'hir>], /* recovered */ bool),
2672 /// A tuple variant.
2674 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2675 Tuple(&'hir [FieldDef<'hir>], HirId),
2678 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2682 impl<'hir> VariantData<'hir> {
2683 /// Return the fields of this variant.
2684 pub fn fields(&self) -> &'hir [FieldDef<'hir>] {
2686 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2691 /// Return the `HirId` of this variant's constructor, if it has one.
2692 pub fn ctor_hir_id(&self) -> Option<HirId> {
2694 VariantData::Struct(_, _) => None,
2695 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2700 // The bodies for items are stored "out of line", in a separate
2701 // hashmap in the `Crate`. Here we just record the hir-id of the item
2702 // so it can fetched later.
2703 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, Hash, HashStable_Generic)]
2705 pub def_id: LocalDefId,
2710 pub fn hir_id(&self) -> HirId {
2711 // Items are always HIR owners.
2712 HirId::make_owner(self.def_id)
2718 /// The name might be a dummy name in case of anonymous items
2719 #[derive(Debug, HashStable_Generic)]
2720 pub struct Item<'hir> {
2722 pub def_id: LocalDefId,
2723 pub kind: ItemKind<'hir>,
2730 pub fn hir_id(&self) -> HirId {
2731 // Items are always HIR owners.
2732 HirId::make_owner(self.def_id)
2735 pub fn item_id(&self) -> ItemId {
2736 ItemId { def_id: self.def_id }
2740 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2741 #[derive(Encodable, Decodable, HashStable_Generic)]
2748 pub fn prefix_str(&self) -> &'static str {
2750 Self::Unsafe => "unsafe ",
2756 impl fmt::Display for Unsafety {
2757 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2758 f.write_str(match *self {
2759 Self::Unsafe => "unsafe",
2760 Self::Normal => "normal",
2765 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2766 #[derive(Encodable, Decodable, HashStable_Generic)]
2767 pub enum Constness {
2772 impl fmt::Display for Constness {
2773 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2774 f.write_str(match *self {
2775 Self::Const => "const",
2776 Self::NotConst => "non-const",
2781 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2782 pub struct FnHeader {
2783 pub unsafety: Unsafety,
2784 pub constness: Constness,
2785 pub asyncness: IsAsync,
2790 pub fn is_async(&self) -> bool {
2791 matches!(&self.asyncness, IsAsync::Async)
2794 pub fn is_const(&self) -> bool {
2795 matches!(&self.constness, Constness::Const)
2798 pub fn is_unsafe(&self) -> bool {
2799 matches!(&self.unsafety, Unsafety::Unsafe)
2803 #[derive(Debug, HashStable_Generic)]
2804 pub enum ItemKind<'hir> {
2805 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2807 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2808 ExternCrate(Option<Symbol>),
2810 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2814 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2815 Use(&'hir Path<'hir>, UseKind),
2817 /// A `static` item.
2818 Static(&'hir Ty<'hir>, Mutability, BodyId),
2820 Const(&'hir Ty<'hir>, BodyId),
2821 /// A function declaration.
2822 Fn(FnSig<'hir>, Generics<'hir>, BodyId),
2823 /// A MBE macro definition (`macro_rules!` or `macro`).
2824 Macro(ast::MacroDef, MacroKind),
2827 /// An external module, e.g. `extern { .. }`.
2828 ForeignMod { abi: Abi, items: &'hir [ForeignItemRef] },
2829 /// Module-level inline assembly (from `global_asm!`).
2830 GlobalAsm(&'hir InlineAsm<'hir>),
2831 /// A type alias, e.g., `type Foo = Bar<u8>`.
2832 TyAlias(&'hir Ty<'hir>, Generics<'hir>),
2833 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2834 OpaqueTy(OpaqueTy<'hir>),
2835 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2836 Enum(EnumDef<'hir>, Generics<'hir>),
2837 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2838 Struct(VariantData<'hir>, Generics<'hir>),
2839 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2840 Union(VariantData<'hir>, Generics<'hir>),
2841 /// A trait definition.
2842 Trait(IsAuto, Unsafety, Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
2844 TraitAlias(Generics<'hir>, GenericBounds<'hir>),
2846 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2850 #[derive(Debug, HashStable_Generic)]
2851 pub struct Impl<'hir> {
2852 pub unsafety: Unsafety,
2853 pub polarity: ImplPolarity,
2854 pub defaultness: Defaultness,
2855 // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata
2856 // decoding as `Span`s cannot be decoded when a `Session` is not available.
2857 pub defaultness_span: Option<Span>,
2858 pub constness: Constness,
2859 pub generics: Generics<'hir>,
2861 /// The trait being implemented, if any.
2862 pub of_trait: Option<TraitRef<'hir>>,
2864 pub self_ty: &'hir Ty<'hir>,
2865 pub items: &'hir [ImplItemRef],
2869 pub fn generics(&self) -> Option<&Generics<'_>> {
2871 ItemKind::Fn(_, ref generics, _)
2872 | ItemKind::TyAlias(_, ref generics)
2873 | ItemKind::OpaqueTy(OpaqueTy {
2874 ref generics, origin: OpaqueTyOrigin::TyAlias, ..
2876 | ItemKind::Enum(_, ref generics)
2877 | ItemKind::Struct(_, ref generics)
2878 | ItemKind::Union(_, ref generics)
2879 | ItemKind::Trait(_, _, ref generics, _, _)
2880 | ItemKind::Impl(Impl { ref generics, .. }) => generics,
2885 pub fn descr(&self) -> &'static str {
2887 ItemKind::ExternCrate(..) => "extern crate",
2888 ItemKind::Use(..) => "`use` import",
2889 ItemKind::Static(..) => "static item",
2890 ItemKind::Const(..) => "constant item",
2891 ItemKind::Fn(..) => "function",
2892 ItemKind::Macro(..) => "macro",
2893 ItemKind::Mod(..) => "module",
2894 ItemKind::ForeignMod { .. } => "extern block",
2895 ItemKind::GlobalAsm(..) => "global asm item",
2896 ItemKind::TyAlias(..) => "type alias",
2897 ItemKind::OpaqueTy(..) => "opaque type",
2898 ItemKind::Enum(..) => "enum",
2899 ItemKind::Struct(..) => "struct",
2900 ItemKind::Union(..) => "union",
2901 ItemKind::Trait(..) => "trait",
2902 ItemKind::TraitAlias(..) => "trait alias",
2903 ItemKind::Impl(..) => "implementation",
2908 /// A reference from an trait to one of its associated items. This
2909 /// contains the item's id, naturally, but also the item's name and
2910 /// some other high-level details (like whether it is an associated
2911 /// type or method, and whether it is public). This allows other
2912 /// passes to find the impl they want without loading the ID (which
2913 /// means fewer edges in the incremental compilation graph).
2914 #[derive(Encodable, Debug, HashStable_Generic)]
2915 pub struct TraitItemRef {
2916 pub id: TraitItemId,
2918 pub kind: AssocItemKind,
2920 pub defaultness: Defaultness,
2923 /// A reference from an impl to one of its associated items. This
2924 /// contains the item's ID, naturally, but also the item's name and
2925 /// some other high-level details (like whether it is an associated
2926 /// type or method, and whether it is public). This allows other
2927 /// passes to find the impl they want without loading the ID (which
2928 /// means fewer edges in the incremental compilation graph).
2929 #[derive(Debug, HashStable_Generic)]
2930 pub struct ImplItemRef {
2933 pub kind: AssocItemKind,
2935 pub defaultness: Defaultness,
2936 /// When we are in a trait impl, link to the trait-item's id.
2937 pub trait_item_def_id: Option<DefId>,
2940 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2941 pub enum AssocItemKind {
2943 Fn { has_self: bool },
2947 // The bodies for items are stored "out of line", in a separate
2948 // hashmap in the `Crate`. Here we just record the hir-id of the item
2949 // so it can fetched later.
2950 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
2951 pub struct ForeignItemId {
2952 pub def_id: LocalDefId,
2955 impl ForeignItemId {
2957 pub fn hir_id(&self) -> HirId {
2958 // Items are always HIR owners.
2959 HirId::make_owner(self.def_id)
2963 /// A reference from a foreign block to one of its items. This
2964 /// contains the item's ID, naturally, but also the item's name and
2965 /// some other high-level details (like whether it is an associated
2966 /// type or method, and whether it is public). This allows other
2967 /// passes to find the impl they want without loading the ID (which
2968 /// means fewer edges in the incremental compilation graph).
2969 #[derive(Debug, HashStable_Generic)]
2970 pub struct ForeignItemRef {
2971 pub id: ForeignItemId,
2976 #[derive(Debug, HashStable_Generic)]
2977 pub struct ForeignItem<'hir> {
2979 pub kind: ForeignItemKind<'hir>,
2980 pub def_id: LocalDefId,
2985 impl ForeignItem<'_> {
2987 pub fn hir_id(&self) -> HirId {
2988 // Items are always HIR owners.
2989 HirId::make_owner(self.def_id)
2992 pub fn foreign_item_id(&self) -> ForeignItemId {
2993 ForeignItemId { def_id: self.def_id }
2997 /// An item within an `extern` block.
2998 #[derive(Debug, HashStable_Generic)]
2999 pub enum ForeignItemKind<'hir> {
3000 /// A foreign function.
3001 Fn(&'hir FnDecl<'hir>, &'hir [Ident], Generics<'hir>),
3002 /// A foreign static item (`static ext: u8`).
3003 Static(&'hir Ty<'hir>, Mutability),
3008 /// A variable captured by a closure.
3009 #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)]
3011 // First span where it is accessed (there can be multiple).
3015 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
3016 // has length > 0 if the trait is found through an chain of imports, starting with the
3017 // import/use statement in the scope where the trait is used.
3018 #[derive(Encodable, Decodable, Clone, Debug, HashStable_Generic)]
3019 pub struct TraitCandidate {
3021 pub import_ids: SmallVec<[LocalDefId; 1]>,
3024 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3025 pub enum OwnerNode<'hir> {
3026 Item(&'hir Item<'hir>),
3027 ForeignItem(&'hir ForeignItem<'hir>),
3028 TraitItem(&'hir TraitItem<'hir>),
3029 ImplItem(&'hir ImplItem<'hir>),
3030 Crate(&'hir Mod<'hir>),
3033 impl<'hir> OwnerNode<'hir> {
3034 pub fn ident(&self) -> Option<Ident> {
3036 OwnerNode::Item(Item { ident, .. })
3037 | OwnerNode::ForeignItem(ForeignItem { ident, .. })
3038 | OwnerNode::ImplItem(ImplItem { ident, .. })
3039 | OwnerNode::TraitItem(TraitItem { ident, .. }) => Some(*ident),
3040 OwnerNode::Crate(..) => None,
3044 pub fn span(&self) -> Span {
3046 OwnerNode::Item(Item { span, .. })
3047 | OwnerNode::ForeignItem(ForeignItem { span, .. })
3048 | OwnerNode::ImplItem(ImplItem { span, .. })
3049 | OwnerNode::TraitItem(TraitItem { span, .. }) => *span,
3050 OwnerNode::Crate(Mod { spans: ModSpans { inner_span, .. }, .. }) => *inner_span,
3054 pub fn fn_decl(&self) -> Option<&FnDecl<'hir>> {
3056 OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3057 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3058 | OwnerNode::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3059 OwnerNode::ForeignItem(ForeignItem {
3060 kind: ForeignItemKind::Fn(fn_decl, _, _),
3062 }) => Some(fn_decl),
3067 pub fn body_id(&self) -> Option<BodyId> {
3069 OwnerNode::TraitItem(TraitItem {
3070 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3073 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3074 | OwnerNode::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3079 pub fn generics(&self) -> Option<&'hir Generics<'hir>> {
3081 OwnerNode::TraitItem(TraitItem { generics, .. })
3082 | OwnerNode::ImplItem(ImplItem { generics, .. }) => Some(generics),
3083 OwnerNode::Item(item) => item.kind.generics(),
3088 pub fn def_id(self) -> LocalDefId {
3090 OwnerNode::Item(Item { def_id, .. })
3091 | OwnerNode::TraitItem(TraitItem { def_id, .. })
3092 | OwnerNode::ImplItem(ImplItem { def_id, .. })
3093 | OwnerNode::ForeignItem(ForeignItem { def_id, .. }) => *def_id,
3094 OwnerNode::Crate(..) => crate::CRATE_HIR_ID.owner,
3098 pub fn expect_item(self) -> &'hir Item<'hir> {
3100 OwnerNode::Item(n) => n,
3105 pub fn expect_foreign_item(self) -> &'hir ForeignItem<'hir> {
3107 OwnerNode::ForeignItem(n) => n,
3112 pub fn expect_impl_item(self) -> &'hir ImplItem<'hir> {
3114 OwnerNode::ImplItem(n) => n,
3119 pub fn expect_trait_item(self) -> &'hir TraitItem<'hir> {
3121 OwnerNode::TraitItem(n) => n,
3127 impl<'hir> Into<OwnerNode<'hir>> for &'hir Item<'hir> {
3128 fn into(self) -> OwnerNode<'hir> {
3129 OwnerNode::Item(self)
3133 impl<'hir> Into<OwnerNode<'hir>> for &'hir ForeignItem<'hir> {
3134 fn into(self) -> OwnerNode<'hir> {
3135 OwnerNode::ForeignItem(self)
3139 impl<'hir> Into<OwnerNode<'hir>> for &'hir ImplItem<'hir> {
3140 fn into(self) -> OwnerNode<'hir> {
3141 OwnerNode::ImplItem(self)
3145 impl<'hir> Into<OwnerNode<'hir>> for &'hir TraitItem<'hir> {
3146 fn into(self) -> OwnerNode<'hir> {
3147 OwnerNode::TraitItem(self)
3151 impl<'hir> Into<Node<'hir>> for OwnerNode<'hir> {
3152 fn into(self) -> Node<'hir> {
3154 OwnerNode::Item(n) => Node::Item(n),
3155 OwnerNode::ForeignItem(n) => Node::ForeignItem(n),
3156 OwnerNode::ImplItem(n) => Node::ImplItem(n),
3157 OwnerNode::TraitItem(n) => Node::TraitItem(n),
3158 OwnerNode::Crate(n) => Node::Crate(n),
3163 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3164 pub enum Node<'hir> {
3165 Param(&'hir Param<'hir>),
3166 Item(&'hir Item<'hir>),
3167 ForeignItem(&'hir ForeignItem<'hir>),
3168 TraitItem(&'hir TraitItem<'hir>),
3169 ImplItem(&'hir ImplItem<'hir>),
3170 Variant(&'hir Variant<'hir>),
3171 Field(&'hir FieldDef<'hir>),
3172 AnonConst(&'hir AnonConst),
3173 Expr(&'hir Expr<'hir>),
3174 Stmt(&'hir Stmt<'hir>),
3175 PathSegment(&'hir PathSegment<'hir>),
3177 TraitRef(&'hir TraitRef<'hir>),
3178 Binding(&'hir Pat<'hir>),
3179 Pat(&'hir Pat<'hir>),
3180 Arm(&'hir Arm<'hir>),
3181 Block(&'hir Block<'hir>),
3182 Local(&'hir Local<'hir>),
3184 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
3185 /// with synthesized constructors.
3186 Ctor(&'hir VariantData<'hir>),
3188 Lifetime(&'hir Lifetime),
3189 GenericParam(&'hir GenericParam<'hir>),
3191 Crate(&'hir Mod<'hir>),
3193 Infer(&'hir InferArg),
3196 impl<'hir> Node<'hir> {
3197 /// Get the identifier of this `Node`, if applicable.
3201 /// Calling `.ident()` on a [`Node::Ctor`] will return `None`
3202 /// because `Ctor`s do not have identifiers themselves.
3203 /// Instead, call `.ident()` on the parent struct/variant, like so:
3205 /// ```ignore (illustrative)
3208 /// .and_then(|ctor_id| tcx.hir().find(tcx.hir().get_parent_node(ctor_id)))
3209 /// .and_then(|parent| parent.ident())
3211 pub fn ident(&self) -> Option<Ident> {
3213 Node::TraitItem(TraitItem { ident, .. })
3214 | Node::ImplItem(ImplItem { ident, .. })
3215 | Node::ForeignItem(ForeignItem { ident, .. })
3216 | Node::Field(FieldDef { ident, .. })
3217 | Node::Variant(Variant { ident, .. })
3218 | Node::Item(Item { ident, .. })
3219 | Node::PathSegment(PathSegment { ident, .. }) => Some(*ident),
3220 Node::Lifetime(lt) => Some(lt.name.ident()),
3221 Node::GenericParam(p) => Some(p.name.ident()),
3223 | Node::AnonConst(..)
3234 | Node::TraitRef(..)
3235 | Node::Infer(..) => None,
3239 pub fn fn_decl(&self) -> Option<&'hir FnDecl<'hir>> {
3241 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3242 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3243 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3244 Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
3251 pub fn fn_sig(&self) -> Option<&'hir FnSig<'hir>> {
3253 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3254 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3255 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig),
3260 pub fn body_id(&self) -> Option<BodyId> {
3262 Node::TraitItem(TraitItem {
3263 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3266 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3267 | Node::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3272 pub fn generics(&self) -> Option<&'hir Generics<'hir>> {
3274 Node::TraitItem(TraitItem { generics, .. })
3275 | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
3276 Node::Item(item) => item.kind.generics(),
3281 pub fn as_owner(self) -> Option<OwnerNode<'hir>> {
3283 Node::Item(i) => Some(OwnerNode::Item(i)),
3284 Node::ForeignItem(i) => Some(OwnerNode::ForeignItem(i)),
3285 Node::TraitItem(i) => Some(OwnerNode::TraitItem(i)),
3286 Node::ImplItem(i) => Some(OwnerNode::ImplItem(i)),
3287 Node::Crate(i) => Some(OwnerNode::Crate(i)),
3292 pub fn fn_kind(self) -> Option<FnKind<'hir>> {
3294 Node::Item(i) => match i.kind {
3295 ItemKind::Fn(ref sig, ref generics, _) => {
3296 Some(FnKind::ItemFn(i.ident, generics, sig.header))
3300 Node::TraitItem(ti) => match ti.kind {
3301 TraitItemKind::Fn(ref sig, TraitFn::Provided(_)) => {
3302 Some(FnKind::Method(ti.ident, sig))
3306 Node::ImplItem(ii) => match ii.kind {
3307 ImplItemKind::Fn(ref sig, _) => Some(FnKind::Method(ii.ident, sig)),
3310 Node::Expr(e) => match e.kind {
3311 ExprKind::Closure(..) => Some(FnKind::Closure),
3318 /// Get the fields for the tuple-constructor,
3319 /// if this node is a tuple constructor, otherwise None
3320 pub fn tuple_fields(&self) -> Option<&'hir [FieldDef<'hir>]> {
3321 if let Node::Ctor(&VariantData::Tuple(fields, _)) = self { Some(fields) } else { None }
3325 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3326 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
3328 rustc_data_structures::static_assert_size!(super::Block<'static>, 48);
3329 rustc_data_structures::static_assert_size!(super::Expr<'static>, 56);
3330 rustc_data_structures::static_assert_size!(super::Pat<'static>, 88);
3331 rustc_data_structures::static_assert_size!(super::QPath<'static>, 24);
3332 rustc_data_structures::static_assert_size!(super::Ty<'static>, 72);
3334 rustc_data_structures::static_assert_size!(super::Item<'static>, 160);
3335 rustc_data_structures::static_assert_size!(super::TraitItem<'static>, 128);
3336 rustc_data_structures::static_assert_size!(super::ImplItem<'static>, 120);
3337 rustc_data_structures::static_assert_size!(super::ForeignItem<'static>, 112);