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, LlvmAsmDialect};
9 use rustc_ast::{Attribute, FloatTy, IntTy, Label, LitKind, StrStyle, 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::source_map::Spanned;
19 use rustc_span::symbol::{kw, sym, Ident, Symbol};
20 use rustc_span::{def_id::LocalDefId, BytePos, MultiSpan, Span, DUMMY_SP};
21 use rustc_target::asm::InlineAsmRegOrRegClass;
22 use rustc_target::spec::abi::Abi;
24 use smallvec::SmallVec;
27 #[derive(Copy, Clone, Encodable, HashStable_Generic)]
32 /// Either "`'a`", referring to a named lifetime definition,
33 /// or "``" (i.e., `kw::Empty`), for elision placeholders.
35 /// HIR lowering inserts these placeholders in type paths that
36 /// refer to type definitions needing lifetime parameters,
37 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
38 pub name: LifetimeName,
41 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
42 #[derive(HashStable_Generic)]
44 /// Some user-given name like `T` or `'x`.
47 /// Synthetic name generated when user elided a lifetime in an impl header.
49 /// E.g., the lifetimes in cases like these:
52 /// impl Foo<'_> for u32
54 /// in that case, we rewrite to
56 /// impl<'f> Foo for &'f u32
57 /// impl<'f> Foo<'f> for u32
59 /// where `'f` is something like `Fresh(0)`. The indices are
60 /// unique per impl, but not necessarily continuous.
63 /// Indicates an illegal name was given and an error has been
64 /// reported (so we should squelch other derived errors). Occurs
65 /// when, e.g., `'_` is used in the wrong place.
70 pub fn ident(&self) -> Ident {
72 ParamName::Plain(ident) => ident,
73 ParamName::Fresh(_) | ParamName::Error => {
74 Ident::with_dummy_span(kw::UnderscoreLifetime)
79 pub fn normalize_to_macros_2_0(&self) -> ParamName {
81 ParamName::Plain(ident) => ParamName::Plain(ident.normalize_to_macros_2_0()),
82 param_name => param_name,
87 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
88 #[derive(HashStable_Generic)]
89 pub enum LifetimeName {
90 /// User-given names or fresh (synthetic) names.
93 /// User wrote nothing (e.g., the lifetime in `&u32`).
95 /// The bool indicates whether the user should have written something.
98 /// Implicit lifetime in a context like `dyn Foo`. This is
99 /// distinguished from implicit lifetimes elsewhere because the
100 /// lifetime that they default to must appear elsewhere within the
101 /// enclosing type. This means that, in an `impl Trait` context, we
102 /// don't have to create a parameter for them. That is, `impl
103 /// Trait<Item = &u32>` expands to an opaque type like `type
104 /// Foo<'a> = impl Trait<Item = &'a u32>`, but `impl Trait<item =
105 /// dyn Bar>` expands to `type Foo = impl Trait<Item = dyn Bar +
106 /// 'static>`. The latter uses `ImplicitObjectLifetimeDefault` so
107 /// that surrounding code knows not to create a lifetime
109 ImplicitObjectLifetimeDefault,
111 /// Indicates an error during lowering (usually `'_` in wrong place)
112 /// that was already reported.
115 /// User wrote specifies `'_`.
118 /// User wrote `'static`.
123 pub fn ident(&self) -> Ident {
125 LifetimeName::ImplicitObjectLifetimeDefault
126 | LifetimeName::Implicit(_)
127 | LifetimeName::Error => Ident::empty(),
128 LifetimeName::Underscore => Ident::with_dummy_span(kw::UnderscoreLifetime),
129 LifetimeName::Static => Ident::with_dummy_span(kw::StaticLifetime),
130 LifetimeName::Param(param_name) => param_name.ident(),
134 pub fn is_elided(&self) -> bool {
136 LifetimeName::ImplicitObjectLifetimeDefault
137 | LifetimeName::Implicit(_)
138 | LifetimeName::Underscore => true,
140 // It might seem surprising that `Fresh(_)` counts as
141 // *not* elided -- but this is because, as far as the code
142 // in the compiler is concerned -- `Fresh(_)` variants act
143 // equivalently to "some fresh name". They correspond to
144 // early-bound regions on an impl, in other words.
145 LifetimeName::Error | LifetimeName::Param(_) | LifetimeName::Static => false,
149 fn is_static(&self) -> bool {
150 self == &LifetimeName::Static
153 pub fn normalize_to_macros_2_0(&self) -> LifetimeName {
155 LifetimeName::Param(param_name) => {
156 LifetimeName::Param(param_name.normalize_to_macros_2_0())
158 lifetime_name => lifetime_name,
163 impl fmt::Display for Lifetime {
164 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
165 self.name.ident().fmt(f)
169 impl fmt::Debug for Lifetime {
170 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171 write!(f, "lifetime({}: {})", self.hir_id, self.name.ident())
176 pub fn is_elided(&self) -> bool {
177 self.name.is_elided()
180 pub fn is_static(&self) -> bool {
181 self.name.is_static()
185 /// A `Path` is essentially Rust's notion of a name; for instance,
186 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
187 /// along with a bunch of supporting information.
188 #[derive(Debug, HashStable_Generic)]
189 pub struct Path<'hir> {
191 /// The resolution for the path.
193 /// The segments in the path: the things separated by `::`.
194 pub segments: &'hir [PathSegment<'hir>],
198 pub fn is_global(&self) -> bool {
199 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
203 /// A segment of a path: an identifier, an optional lifetime, and a set of
205 #[derive(Debug, HashStable_Generic)]
206 pub struct PathSegment<'hir> {
207 /// The identifier portion of this path segment.
208 #[stable_hasher(project(name))]
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_const(&self) -> bool {
298 matches!(self, GenericArg::Const(_))
301 pub fn is_synthetic(&self) -> bool {
302 matches!(self, GenericArg::Lifetime(lifetime) if lifetime.name.ident() == Ident::empty())
305 pub fn descr(&self) -> &'static str {
307 GenericArg::Lifetime(_) => "lifetime",
308 GenericArg::Type(_) => "type",
309 GenericArg::Const(_) => "constant",
310 GenericArg::Infer(_) => "inferred",
314 pub fn to_ord(&self) -> ast::ParamKindOrd {
316 GenericArg::Lifetime(_) => ast::ParamKindOrd::Lifetime,
317 GenericArg::Type(_) => ast::ParamKindOrd::Type,
318 GenericArg::Const(_) => ast::ParamKindOrd::Const,
319 GenericArg::Infer(_) => ast::ParamKindOrd::Infer,
324 #[derive(Debug, HashStable_Generic)]
325 pub struct GenericArgs<'hir> {
326 /// The generic arguments for this path segment.
327 pub args: &'hir [GenericArg<'hir>],
328 /// Bindings (equality constraints) on associated types, if present.
329 /// E.g., `Foo<A = Bar>`.
330 pub bindings: &'hir [TypeBinding<'hir>],
331 /// Were arguments written in parenthesized form `Fn(T) -> U`?
332 /// This is required mostly for pretty-printing and diagnostics,
333 /// but also for changing lifetime elision rules to be "function-like".
334 pub parenthesized: bool,
335 /// The span encompassing arguments and the surrounding brackets `<>` or `()`
336 /// Foo<A, B, AssocTy = D> Fn(T, U, V) -> W
337 /// ^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^
338 /// Note that this may be:
339 /// - empty, if there are no generic brackets (but there may be hidden lifetimes)
340 /// - dummy, if this was generated while desugaring
344 impl GenericArgs<'_> {
345 pub const fn none() -> Self {
346 Self { args: &[], bindings: &[], parenthesized: false, span_ext: DUMMY_SP }
349 pub fn inputs(&self) -> &[Ty<'_>] {
350 if self.parenthesized {
351 for arg in self.args {
353 GenericArg::Lifetime(_) => {}
354 GenericArg::Type(ref ty) => {
355 if let TyKind::Tup(ref tys) = ty.kind {
360 GenericArg::Const(_) => {}
361 GenericArg::Infer(_) => {}
365 panic!("GenericArgs::inputs: not a `Fn(T) -> U`");
369 pub fn has_type_params(&self) -> bool {
370 self.args.iter().any(|arg| matches!(arg, GenericArg::Type(_)))
373 pub fn has_err(&self) -> bool {
374 self.args.iter().any(|arg| match arg {
375 GenericArg::Type(ty) => matches!(ty.kind, TyKind::Err),
377 }) || self.bindings.iter().any(|arg| match arg.kind {
378 TypeBindingKind::Equality { ty } => matches!(ty.kind, TyKind::Err),
384 pub fn num_type_params(&self) -> usize {
385 self.args.iter().filter(|arg| matches!(arg, GenericArg::Type(_))).count()
389 pub fn num_lifetime_params(&self) -> usize {
390 self.args.iter().filter(|arg| matches!(arg, GenericArg::Lifetime(_))).count()
394 pub fn has_lifetime_params(&self) -> bool {
395 self.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)))
399 pub fn num_generic_params(&self) -> usize {
400 self.args.iter().filter(|arg| !matches!(arg, GenericArg::Lifetime(_))).count()
403 /// The span encompassing the text inside the surrounding brackets.
404 /// It will also include bindings if they aren't in the form `-> Ret`
405 /// Returns `None` if the span is empty (e.g. no brackets) or dummy
406 pub fn span(&self) -> Option<Span> {
407 let span_ext = self.span_ext()?;
408 Some(span_ext.with_lo(span_ext.lo() + BytePos(1)).with_hi(span_ext.hi() - BytePos(1)))
411 /// Returns span encompassing arguments and their surrounding `<>` or `()`
412 pub fn span_ext(&self) -> Option<Span> {
413 Some(self.span_ext).filter(|span| !span.is_empty())
416 pub fn is_empty(&self) -> bool {
421 /// A modifier on a bound, currently this is only used for `?Sized`, where the
422 /// modifier is `Maybe`. Negative bounds should also be handled here.
423 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
424 #[derive(HashStable_Generic)]
425 pub enum TraitBoundModifier {
431 /// The AST represents all type param bounds as types.
432 /// `typeck::collect::compute_bounds` matches these against
433 /// the "special" built-in traits (see `middle::lang_items`) and
434 /// detects `Copy`, `Send` and `Sync`.
435 #[derive(Clone, Debug, HashStable_Generic)]
436 pub enum GenericBound<'hir> {
437 Trait(PolyTraitRef<'hir>, TraitBoundModifier),
438 // FIXME(davidtwco): Introduce `PolyTraitRef::LangItem`
439 LangItemTrait(LangItem, Span, HirId, &'hir GenericArgs<'hir>),
443 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
444 rustc_data_structures::static_assert_size!(GenericBound<'_>, 48);
446 impl GenericBound<'_> {
447 pub fn trait_ref(&self) -> Option<&TraitRef<'_>> {
449 GenericBound::Trait(data, _) => Some(&data.trait_ref),
454 pub fn span(&self) -> Span {
456 GenericBound::Trait(t, ..) => t.span,
457 GenericBound::LangItemTrait(_, span, ..) => *span,
458 GenericBound::Outlives(l) => l.span,
463 pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
465 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
466 pub enum LifetimeParamKind {
467 // Indicates that the lifetime definition was explicitly declared (e.g., in
468 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
471 // Indicates that the lifetime definition was synthetically added
472 // as a result of an in-band lifetime usage (e.g., in
473 // `fn foo(x: &'a u8) -> &'a u8 { x }`).
476 // Indication that the lifetime was elided (e.g., in both cases in
477 // `fn foo(x: &u8) -> &'_ u8 { x }`).
480 // Indication that the lifetime name was somehow in error.
484 #[derive(Debug, HashStable_Generic)]
485 pub enum GenericParamKind<'hir> {
486 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
488 kind: LifetimeParamKind,
491 default: Option<&'hir Ty<'hir>>,
496 /// Optional default value for the const generic param
497 default: Option<AnonConst>,
501 #[derive(Debug, HashStable_Generic)]
502 pub struct GenericParam<'hir> {
505 pub bounds: GenericBounds<'hir>,
507 pub pure_wrt_drop: bool,
508 pub kind: GenericParamKind<'hir>,
511 impl<'hir> GenericParam<'hir> {
512 pub fn bounds_span_for_suggestions(&self) -> Option<Span> {
515 .fold(None, |span: Option<Span>, bound| {
516 // We include bounds that come from a `#[derive(_)]` but point at the user's code,
517 // as we use this method to get a span appropriate for suggestions.
518 if !bound.span().can_be_used_for_suggestions() {
521 let span = span.map(|s| s.to(bound.span())).unwrap_or_else(|| bound.span());
525 .map(|sp| sp.shrink_to_hi())
530 pub struct GenericParamCount {
531 pub lifetimes: usize,
537 /// Represents lifetimes and type parameters attached to a declaration
538 /// of a function, enum, trait, etc.
539 #[derive(Debug, HashStable_Generic)]
540 pub struct Generics<'hir> {
541 pub params: &'hir [GenericParam<'hir>],
542 pub where_clause: WhereClause<'hir>,
546 impl<'hir> Generics<'hir> {
547 pub const fn empty() -> Generics<'hir> {
550 where_clause: WhereClause { predicates: &[], span: DUMMY_SP },
555 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'_>> {
556 for param in self.params {
557 if name == param.name.ident().name {
564 pub fn spans(&self) -> MultiSpan {
565 if self.params.is_empty() {
568 self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
573 /// A where-clause in a definition.
574 #[derive(Debug, HashStable_Generic)]
575 pub struct WhereClause<'hir> {
576 pub predicates: &'hir [WherePredicate<'hir>],
577 // Only valid if predicates aren't empty.
581 impl WhereClause<'_> {
582 pub fn span(&self) -> Option<Span> {
583 if self.predicates.is_empty() { None } else { Some(self.span) }
586 /// The `WhereClause` under normal circumstances points at either the predicates or the empty
587 /// space where the `where` clause should be. Only of use for diagnostic suggestions.
588 pub fn span_for_predicates_or_empty_place(&self) -> Span {
592 /// `Span` where further predicates would be suggested, accounting for trailing commas, like
593 /// in `fn foo<T>(t: T) where T: Foo,` so we don't suggest two trailing commas.
594 pub fn tail_span_for_suggestion(&self) -> Span {
595 let end = self.span_for_predicates_or_empty_place().shrink_to_hi();
596 self.predicates.last().map_or(end, |p| p.span()).shrink_to_hi().to(end)
600 /// A single predicate in a where-clause.
601 #[derive(Debug, HashStable_Generic)]
602 pub enum WherePredicate<'hir> {
603 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
604 BoundPredicate(WhereBoundPredicate<'hir>),
605 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
606 RegionPredicate(WhereRegionPredicate<'hir>),
607 /// An equality predicate (unsupported).
608 EqPredicate(WhereEqPredicate<'hir>),
611 impl<'hir> WherePredicate<'hir> {
612 pub fn span(&self) -> Span {
614 WherePredicate::BoundPredicate(p) => p.span,
615 WherePredicate::RegionPredicate(p) => p.span,
616 WherePredicate::EqPredicate(p) => p.span,
621 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
622 #[derive(Debug, HashStable_Generic)]
623 pub struct WhereBoundPredicate<'hir> {
625 /// Any generics from a `for` binding.
626 pub bound_generic_params: &'hir [GenericParam<'hir>],
627 /// The type being bounded.
628 pub bounded_ty: &'hir Ty<'hir>,
629 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
630 pub bounds: GenericBounds<'hir>,
633 impl<'hir> WhereBoundPredicate<'hir> {
634 /// Returns `true` if `param_def_id` matches the `bounded_ty` of this predicate.
635 pub fn is_param_bound(&self, param_def_id: DefId) -> bool {
636 let path = match self.bounded_ty.kind {
637 TyKind::Path(QPath::Resolved(None, path)) => path,
641 Res::Def(DefKind::TyParam, def_id) | Res::SelfTy(Some(def_id), None) => {
642 def_id == param_def_id
649 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
650 #[derive(Debug, HashStable_Generic)]
651 pub struct WhereRegionPredicate<'hir> {
653 pub lifetime: Lifetime,
654 pub bounds: GenericBounds<'hir>,
657 /// An equality predicate (e.g., `T = int`); currently unsupported.
658 #[derive(Debug, HashStable_Generic)]
659 pub struct WhereEqPredicate<'hir> {
662 pub lhs_ty: &'hir Ty<'hir>,
663 pub rhs_ty: &'hir Ty<'hir>,
666 /// HIR node coupled with its parent's id in the same HIR owner.
668 /// The parent is trash when the node is a HIR owner.
669 #[derive(Clone, Debug)]
670 pub struct ParentedNode<'tcx> {
671 pub parent: ItemLocalId,
672 pub node: Node<'tcx>,
675 /// Attributes owned by a HIR owner.
677 pub struct AttributeMap<'tcx> {
678 pub map: SortedMap<ItemLocalId, &'tcx [Attribute]>,
679 pub hash: Fingerprint,
682 impl<'tcx> AttributeMap<'tcx> {
683 pub const EMPTY: &'static AttributeMap<'static> =
684 &AttributeMap { map: SortedMap::new(), hash: Fingerprint::ZERO };
687 pub fn get(&self, id: ItemLocalId) -> &'tcx [Attribute] {
688 self.map.get(&id).copied().unwrap_or(&[])
692 /// Map of all HIR nodes inside the current owner.
693 /// These nodes are mapped by `ItemLocalId` alongside the index of their parent node.
694 /// The HIR tree, including bodies, is pre-hashed.
696 pub struct OwnerNodes<'tcx> {
697 /// Pre-computed hash of the full HIR.
698 pub hash_including_bodies: Fingerprint,
699 /// Pre-computed hash of the item signature, sithout recursing into the body.
700 pub hash_without_bodies: Fingerprint,
701 /// Full HIR for the current owner.
702 // The zeroth node's parent should never be accessed: the owner's parent is computed by the
703 // hir_owner_parent query. It is set to `ItemLocalId::INVALID` to force an ICE if accidentally
705 pub nodes: IndexVec<ItemLocalId, Option<ParentedNode<'tcx>>>,
706 /// Content of local bodies.
707 pub bodies: SortedMap<ItemLocalId, &'tcx Body<'tcx>>,
710 /// Full information resulting from lowering an AST node.
711 #[derive(Debug, HashStable_Generic)]
712 pub struct OwnerInfo<'hir> {
713 /// Contents of the HIR.
714 pub nodes: OwnerNodes<'hir>,
715 /// Map from each nested owner to its parent's local id.
716 pub parenting: FxHashMap<LocalDefId, ItemLocalId>,
717 /// Collected attributes of the HIR nodes.
718 pub attrs: AttributeMap<'hir>,
719 /// Map indicating what traits are in scope for places where this
720 /// is relevant; generated by resolve.
721 pub trait_map: FxHashMap<ItemLocalId, Box<[TraitCandidate]>>,
724 impl<'tcx> OwnerInfo<'tcx> {
726 pub fn node(&self) -> OwnerNode<'tcx> {
727 use rustc_index::vec::Idx;
728 let node = self.nodes.nodes[ItemLocalId::new(0)].as_ref().unwrap().node;
729 let node = node.as_owner().unwrap(); // Indexing must ensure it is an OwnerNode.
734 /// The top-level data structure that stores the entire contents of
735 /// the crate currently being compiled.
737 /// For more details, see the [rustc dev guide].
739 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
741 pub struct Crate<'hir> {
742 pub owners: IndexVec<LocalDefId, Option<OwnerInfo<'hir>>>,
743 pub hir_hash: Fingerprint,
746 /// A block of statements `{ .. }`, which may have a label (in this case the
747 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
748 /// the `rules` being anything but `DefaultBlock`.
749 #[derive(Debug, HashStable_Generic)]
750 pub struct Block<'hir> {
751 /// Statements in a block.
752 pub stmts: &'hir [Stmt<'hir>],
753 /// An expression at the end of the block
754 /// without a semicolon, if any.
755 pub expr: Option<&'hir Expr<'hir>>,
756 #[stable_hasher(ignore)]
758 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
759 pub rules: BlockCheckMode,
761 /// If true, then there may exist `break 'a` values that aim to
762 /// break out of this block early.
763 /// Used by `'label: {}` blocks and by `try {}` blocks.
764 pub targeted_by_break: bool,
767 #[derive(Debug, HashStable_Generic)]
768 pub struct Pat<'hir> {
769 #[stable_hasher(ignore)]
771 pub kind: PatKind<'hir>,
773 // Whether to use default binding modes.
774 // At present, this is false only for destructuring assignment.
775 pub default_binding_modes: bool,
778 impl<'hir> Pat<'hir> {
779 // FIXME(#19596) this is a workaround, but there should be a better way
780 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) -> bool {
787 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
788 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
789 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
790 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
791 Slice(before, slice, after) => {
792 before.iter().chain(slice).chain(after.iter()).all(|p| p.walk_short_(it))
797 /// Walk the pattern in left-to-right order,
798 /// short circuiting (with `.all(..)`) if `false` is returned.
800 /// Note that when visiting e.g. `Tuple(ps)`,
801 /// if visiting `ps[0]` returns `false`,
802 /// then `ps[1]` will not be visited.
803 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) -> bool {
804 self.walk_short_(&mut it)
807 // FIXME(#19596) this is a workaround, but there should be a better way
808 fn walk_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) {
815 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
816 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
817 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
818 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
819 Slice(before, slice, after) => {
820 before.iter().chain(slice).chain(after.iter()).for_each(|p| p.walk_(it))
825 /// Walk the pattern in left-to-right order.
827 /// If `it(pat)` returns `false`, the children are not visited.
828 pub fn walk(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) {
832 /// Walk the pattern in left-to-right order.
834 /// If you always want to recurse, prefer this method over `walk`.
835 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
843 /// A single field in a struct pattern.
845 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
846 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
847 /// except `is_shorthand` is true.
848 #[derive(Debug, HashStable_Generic)]
849 pub struct PatField<'hir> {
850 #[stable_hasher(ignore)]
852 /// The identifier for the field.
853 #[stable_hasher(project(name))]
855 /// The pattern the field is destructured to.
856 pub pat: &'hir Pat<'hir>,
857 pub is_shorthand: bool,
861 /// Explicit binding annotations given in the HIR for a binding. Note
862 /// that this is not the final binding *mode* that we infer after type
864 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
865 pub enum BindingAnnotation {
866 /// No binding annotation given: this means that the final binding mode
867 /// will depend on whether we have skipped through a `&` reference
868 /// when matching. For example, the `x` in `Some(x)` will have binding
869 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
870 /// ultimately be inferred to be by-reference.
872 /// Note that implicit reference skipping is not implemented yet (#42640).
875 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
878 /// Annotated as `ref`, like `ref x`
881 /// Annotated as `ref mut x`.
885 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
891 impl fmt::Display for RangeEnd {
892 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
893 f.write_str(match self {
894 RangeEnd::Included => "..=",
895 RangeEnd::Excluded => "..",
900 #[derive(Debug, HashStable_Generic)]
901 pub enum PatKind<'hir> {
902 /// Represents a wildcard pattern (i.e., `_`).
905 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
906 /// The `HirId` is the canonical ID for the variable being bound,
907 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
908 /// which is the pattern ID of the first `x`.
909 Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
911 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
912 /// The `bool` is `true` in the presence of a `..`.
913 Struct(QPath<'hir>, &'hir [PatField<'hir>], bool),
915 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
916 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
917 /// `0 <= position <= subpats.len()`
918 TupleStruct(QPath<'hir>, &'hir [Pat<'hir>], Option<usize>),
920 /// An or-pattern `A | B | C`.
921 /// Invariant: `pats.len() >= 2`.
922 Or(&'hir [Pat<'hir>]),
924 /// A path pattern for a unit struct/variant or a (maybe-associated) constant.
927 /// A tuple pattern (e.g., `(a, b)`).
928 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
929 /// `0 <= position <= subpats.len()`
930 Tuple(&'hir [Pat<'hir>], Option<usize>),
933 Box(&'hir Pat<'hir>),
935 /// A reference pattern (e.g., `&mut (a, b)`).
936 Ref(&'hir Pat<'hir>, Mutability),
939 Lit(&'hir Expr<'hir>),
941 /// A range pattern (e.g., `1..=2` or `1..2`).
942 Range(Option<&'hir Expr<'hir>>, Option<&'hir Expr<'hir>>, RangeEnd),
944 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
946 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
947 /// If `slice` exists, then `after` can be non-empty.
949 /// The representation for e.g., `[a, b, .., c, d]` is:
951 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
953 Slice(&'hir [Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [Pat<'hir>]),
956 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
958 /// The `+` operator (addition).
960 /// The `-` operator (subtraction).
962 /// The `*` operator (multiplication).
964 /// The `/` operator (division).
966 /// The `%` operator (modulus).
968 /// The `&&` operator (logical and).
970 /// The `||` operator (logical or).
972 /// The `^` operator (bitwise xor).
974 /// The `&` operator (bitwise and).
976 /// The `|` operator (bitwise or).
978 /// The `<<` operator (shift left).
980 /// The `>>` operator (shift right).
982 /// The `==` operator (equality).
984 /// The `<` operator (less than).
986 /// The `<=` operator (less than or equal to).
988 /// The `!=` operator (not equal to).
990 /// The `>=` operator (greater than or equal to).
992 /// The `>` operator (greater than).
997 pub fn as_str(self) -> &'static str {
999 BinOpKind::Add => "+",
1000 BinOpKind::Sub => "-",
1001 BinOpKind::Mul => "*",
1002 BinOpKind::Div => "/",
1003 BinOpKind::Rem => "%",
1004 BinOpKind::And => "&&",
1005 BinOpKind::Or => "||",
1006 BinOpKind::BitXor => "^",
1007 BinOpKind::BitAnd => "&",
1008 BinOpKind::BitOr => "|",
1009 BinOpKind::Shl => "<<",
1010 BinOpKind::Shr => ">>",
1011 BinOpKind::Eq => "==",
1012 BinOpKind::Lt => "<",
1013 BinOpKind::Le => "<=",
1014 BinOpKind::Ne => "!=",
1015 BinOpKind::Ge => ">=",
1016 BinOpKind::Gt => ">",
1020 pub fn is_lazy(self) -> bool {
1021 matches!(self, BinOpKind::And | BinOpKind::Or)
1024 pub fn is_shift(self) -> bool {
1025 matches!(self, BinOpKind::Shl | BinOpKind::Shr)
1028 pub fn is_comparison(self) -> bool {
1035 | BinOpKind::Ge => true,
1047 | BinOpKind::Shr => false,
1051 /// Returns `true` if the binary operator takes its arguments by value.
1052 pub fn is_by_value(self) -> bool {
1053 !self.is_comparison()
1057 impl Into<ast::BinOpKind> for BinOpKind {
1058 fn into(self) -> ast::BinOpKind {
1060 BinOpKind::Add => ast::BinOpKind::Add,
1061 BinOpKind::Sub => ast::BinOpKind::Sub,
1062 BinOpKind::Mul => ast::BinOpKind::Mul,
1063 BinOpKind::Div => ast::BinOpKind::Div,
1064 BinOpKind::Rem => ast::BinOpKind::Rem,
1065 BinOpKind::And => ast::BinOpKind::And,
1066 BinOpKind::Or => ast::BinOpKind::Or,
1067 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1068 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1069 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1070 BinOpKind::Shl => ast::BinOpKind::Shl,
1071 BinOpKind::Shr => ast::BinOpKind::Shr,
1072 BinOpKind::Eq => ast::BinOpKind::Eq,
1073 BinOpKind::Lt => ast::BinOpKind::Lt,
1074 BinOpKind::Le => ast::BinOpKind::Le,
1075 BinOpKind::Ne => ast::BinOpKind::Ne,
1076 BinOpKind::Ge => ast::BinOpKind::Ge,
1077 BinOpKind::Gt => ast::BinOpKind::Gt,
1082 pub type BinOp = Spanned<BinOpKind>;
1084 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1086 /// The `*` operator (deferencing).
1088 /// The `!` operator (logical negation).
1090 /// The `-` operator (negation).
1095 pub fn as_str(self) -> &'static str {
1103 /// Returns `true` if the unary operator takes its argument by value.
1104 pub fn is_by_value(self) -> bool {
1105 matches!(self, Self::Neg | Self::Not)
1110 #[derive(Debug, HashStable_Generic)]
1111 pub struct Stmt<'hir> {
1113 pub kind: StmtKind<'hir>,
1117 /// The contents of a statement.
1118 #[derive(Debug, HashStable_Generic)]
1119 pub enum StmtKind<'hir> {
1120 /// A local (`let`) binding.
1121 Local(&'hir Local<'hir>),
1123 /// An item binding.
1126 /// An expression without a trailing semi-colon (must have unit type).
1127 Expr(&'hir Expr<'hir>),
1129 /// An expression with a trailing semi-colon (may have any type).
1130 Semi(&'hir Expr<'hir>),
1133 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1134 #[derive(Debug, HashStable_Generic)]
1135 pub struct Local<'hir> {
1136 pub pat: &'hir Pat<'hir>,
1137 /// Type annotation, if any (otherwise the type will be inferred).
1138 pub ty: Option<&'hir Ty<'hir>>,
1139 /// Initializer expression to set the value, if any.
1140 pub init: Option<&'hir Expr<'hir>>,
1143 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1144 /// desugaring. Otherwise will be `Normal`.
1145 pub source: LocalSource,
1148 /// Represents a single arm of a `match` expression, e.g.
1149 /// `<pat> (if <guard>) => <body>`.
1150 #[derive(Debug, HashStable_Generic)]
1151 pub struct Arm<'hir> {
1152 #[stable_hasher(ignore)]
1155 /// If this pattern and the optional guard matches, then `body` is evaluated.
1156 pub pat: &'hir Pat<'hir>,
1157 /// Optional guard clause.
1158 pub guard: Option<Guard<'hir>>,
1159 /// The expression the arm evaluates to if this arm matches.
1160 pub body: &'hir Expr<'hir>,
1163 /// Represents a `let <pat>[: <ty>] = <expr>` expression (not a Local), occurring in an `if-let` or
1164 /// `let-else`, evaluating to a boolean. Typically the pattern is refutable.
1166 /// In an if-let, imagine it as `if (let <pat> = <expr>) { ... }`; in a let-else, it is part of the
1167 /// desugaring to if-let. Only let-else supports the type annotation at present.
1168 #[derive(Debug, HashStable_Generic)]
1169 pub struct Let<'hir> {
1172 pub pat: &'hir Pat<'hir>,
1173 pub ty: Option<&'hir Ty<'hir>>,
1174 pub init: &'hir Expr<'hir>,
1177 #[derive(Debug, HashStable_Generic)]
1178 pub enum Guard<'hir> {
1179 If(&'hir Expr<'hir>),
1180 // FIXME use hir::Let for this.
1181 IfLet(&'hir Pat<'hir>, &'hir Expr<'hir>),
1184 #[derive(Debug, HashStable_Generic)]
1185 pub struct ExprField<'hir> {
1186 #[stable_hasher(ignore)]
1189 pub expr: &'hir Expr<'hir>,
1191 pub is_shorthand: bool,
1194 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1195 pub enum BlockCheckMode {
1197 UnsafeBlock(UnsafeSource),
1200 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1201 pub enum UnsafeSource {
1206 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
1211 /// The body of a function, closure, or constant value. In the case of
1212 /// a function, the body contains not only the function body itself
1213 /// (which is an expression), but also the argument patterns, since
1214 /// those are something that the caller doesn't really care about.
1219 /// fn foo((x, y): (u32, u32)) -> u32 {
1224 /// Here, the `Body` associated with `foo()` would contain:
1226 /// - an `params` array containing the `(x, y)` pattern
1227 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1228 /// - `generator_kind` would be `None`
1230 /// All bodies have an **owner**, which can be accessed via the HIR
1231 /// map using `body_owner_def_id()`.
1233 pub struct Body<'hir> {
1234 pub params: &'hir [Param<'hir>],
1235 pub value: Expr<'hir>,
1236 pub generator_kind: Option<GeneratorKind>,
1239 impl<'hir> Body<'hir> {
1240 pub fn id(&self) -> BodyId {
1241 BodyId { hir_id: self.value.hir_id }
1244 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1249 /// The type of source expression that caused this generator to be created.
1262 pub enum GeneratorKind {
1263 /// An explicit `async` block or the body of an async function.
1264 Async(AsyncGeneratorKind),
1266 /// A generator literal created via a `yield` inside a closure.
1270 impl fmt::Display for GeneratorKind {
1271 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1273 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1274 GeneratorKind::Gen => f.write_str("generator"),
1279 impl GeneratorKind {
1280 pub fn descr(&self) -> &'static str {
1282 GeneratorKind::Async(ask) => ask.descr(),
1283 GeneratorKind::Gen => "generator",
1288 /// In the case of a generator created as part of an async construct,
1289 /// which kind of async construct caused it to be created?
1291 /// This helps error messages but is also used to drive coercions in
1292 /// type-checking (see #60424).
1305 pub enum AsyncGeneratorKind {
1306 /// An explicit `async` block written by the user.
1309 /// An explicit `async` block written by the user.
1312 /// The `async` block generated as the body of an async function.
1316 impl fmt::Display for AsyncGeneratorKind {
1317 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1318 f.write_str(match self {
1319 AsyncGeneratorKind::Block => "`async` block",
1320 AsyncGeneratorKind::Closure => "`async` closure body",
1321 AsyncGeneratorKind::Fn => "`async fn` body",
1326 impl AsyncGeneratorKind {
1327 pub fn descr(&self) -> &'static str {
1329 AsyncGeneratorKind::Block => "`async` block",
1330 AsyncGeneratorKind::Closure => "`async` closure body",
1331 AsyncGeneratorKind::Fn => "`async fn` body",
1336 #[derive(Copy, Clone, Debug)]
1337 pub enum BodyOwnerKind {
1338 /// Functions and methods.
1344 /// Constants and associated constants.
1347 /// Initializer of a `static` item.
1351 impl BodyOwnerKind {
1352 pub fn is_fn_or_closure(self) -> bool {
1354 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1355 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1360 /// The kind of an item that requires const-checking.
1361 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1362 pub enum ConstContext {
1366 /// A `static` or `static mut`.
1369 /// A `const`, associated `const`, or other const context.
1371 /// Other contexts include:
1372 /// - Array length expressions
1373 /// - Enum discriminants
1374 /// - Const generics
1376 /// For the most part, other contexts are treated just like a regular `const`, so they are
1377 /// lumped into the same category.
1382 /// A description of this const context that can appear between backticks in an error message.
1384 /// E.g. `const` or `static mut`.
1385 pub fn keyword_name(self) -> &'static str {
1387 Self::Const => "const",
1388 Self::Static(Mutability::Not) => "static",
1389 Self::Static(Mutability::Mut) => "static mut",
1390 Self::ConstFn => "const fn",
1395 /// A colloquial, trivially pluralizable description of this const context for use in error
1397 impl fmt::Display for ConstContext {
1398 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1400 Self::Const => write!(f, "constant"),
1401 Self::Static(_) => write!(f, "static"),
1402 Self::ConstFn => write!(f, "constant function"),
1408 pub type Lit = Spanned<LitKind>;
1410 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1417 pub fn hir_id(&self) -> HirId {
1419 &ArrayLen::Infer(hir_id, _) | &ArrayLen::Body(AnonConst { hir_id, body: _ }) => hir_id,
1424 /// A constant (expression) that's not an item or associated item,
1425 /// but needs its own `DefId` for type-checking, const-eval, etc.
1426 /// These are usually found nested inside types (e.g., array lengths)
1427 /// or expressions (e.g., repeat counts), and also used to define
1428 /// explicit discriminant values for enum variants.
1430 /// You can check if this anon const is a default in a const param
1431 /// `const N: usize = { ... }` with `tcx.hir().opt_const_param_default_param_hir_id(..)`
1432 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1433 pub struct AnonConst {
1440 pub struct Expr<'hir> {
1442 pub kind: ExprKind<'hir>,
1447 pub fn precedence(&self) -> ExprPrecedence {
1449 ExprKind::Box(_) => ExprPrecedence::Box,
1450 ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1451 ExprKind::Array(_) => ExprPrecedence::Array,
1452 ExprKind::Call(..) => ExprPrecedence::Call,
1453 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1454 ExprKind::Tup(_) => ExprPrecedence::Tup,
1455 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1456 ExprKind::Unary(..) => ExprPrecedence::Unary,
1457 ExprKind::Lit(_) => ExprPrecedence::Lit,
1458 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1459 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1460 ExprKind::If(..) => ExprPrecedence::If,
1461 ExprKind::Let(..) => ExprPrecedence::Let,
1462 ExprKind::Loop(..) => ExprPrecedence::Loop,
1463 ExprKind::Match(..) => ExprPrecedence::Match,
1464 ExprKind::Closure(..) => ExprPrecedence::Closure,
1465 ExprKind::Block(..) => ExprPrecedence::Block,
1466 ExprKind::Assign(..) => ExprPrecedence::Assign,
1467 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1468 ExprKind::Field(..) => ExprPrecedence::Field,
1469 ExprKind::Index(..) => ExprPrecedence::Index,
1470 ExprKind::Path(..) => ExprPrecedence::Path,
1471 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1472 ExprKind::Break(..) => ExprPrecedence::Break,
1473 ExprKind::Continue(..) => ExprPrecedence::Continue,
1474 ExprKind::Ret(..) => ExprPrecedence::Ret,
1475 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1476 ExprKind::LlvmInlineAsm(..) => ExprPrecedence::InlineAsm,
1477 ExprKind::Struct(..) => ExprPrecedence::Struct,
1478 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1479 ExprKind::Yield(..) => ExprPrecedence::Yield,
1480 ExprKind::Err => ExprPrecedence::Err,
1484 // Whether this looks like a place expr, without checking for deref
1486 // This will return `true` in some potentially surprising cases such as
1487 // `CONSTANT.field`.
1488 pub fn is_syntactic_place_expr(&self) -> bool {
1489 self.is_place_expr(|_| true)
1492 /// Whether this is a place expression.
1494 /// `allow_projections_from` should return `true` if indexing a field or index expression based
1495 /// on the given expression should be considered a place expression.
1496 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1498 ExprKind::Path(QPath::Resolved(_, ref path)) => {
1499 matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static, _) | Res::Err)
1502 // Type ascription inherits its place expression kind from its
1504 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1505 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1507 ExprKind::Unary(UnOp::Deref, _) => true,
1509 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1510 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1513 // Lang item paths cannot currently be local variables or statics.
1514 ExprKind::Path(QPath::LangItem(..)) => false,
1516 // Partially qualified paths in expressions can only legally
1517 // refer to associated items which are always rvalues.
1518 ExprKind::Path(QPath::TypeRelative(..))
1519 | ExprKind::Call(..)
1520 | ExprKind::MethodCall(..)
1521 | ExprKind::Struct(..)
1524 | ExprKind::Match(..)
1525 | ExprKind::Closure(..)
1526 | ExprKind::Block(..)
1527 | ExprKind::Repeat(..)
1528 | ExprKind::Array(..)
1529 | ExprKind::Break(..)
1530 | ExprKind::Continue(..)
1533 | ExprKind::Loop(..)
1534 | ExprKind::Assign(..)
1535 | ExprKind::InlineAsm(..)
1536 | ExprKind::LlvmInlineAsm(..)
1537 | ExprKind::AssignOp(..)
1539 | ExprKind::ConstBlock(..)
1540 | ExprKind::Unary(..)
1542 | ExprKind::AddrOf(..)
1543 | ExprKind::Binary(..)
1544 | ExprKind::Yield(..)
1545 | ExprKind::Cast(..)
1546 | ExprKind::DropTemps(..)
1547 | ExprKind::Err => false,
1551 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1552 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1553 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1554 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1555 /// beyond remembering to call this function before doing analysis on it.
1556 pub fn peel_drop_temps(&self) -> &Self {
1557 let mut expr = self;
1558 while let ExprKind::DropTemps(inner) = &expr.kind {
1564 pub fn peel_blocks(&self) -> &Self {
1565 let mut expr = self;
1566 while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind {
1572 pub fn can_have_side_effects(&self) -> bool {
1573 match self.peel_drop_temps().kind {
1574 ExprKind::Path(_) | ExprKind::Lit(_) => false,
1575 ExprKind::Type(base, _)
1576 | ExprKind::Unary(_, base)
1577 | ExprKind::Field(base, _)
1578 | ExprKind::Index(base, _)
1579 | ExprKind::AddrOf(.., base)
1580 | ExprKind::Cast(base, _) => {
1581 // This isn't exactly true for `Index` and all `Unnary`, but we are using this
1582 // method exclusively for diagnostics and there's a *cultural* pressure against
1583 // them being used only for its side-effects.
1584 base.can_have_side_effects()
1586 ExprKind::Struct(_, fields, init) => fields
1588 .map(|field| field.expr)
1589 .chain(init.into_iter())
1590 .all(|e| e.can_have_side_effects()),
1592 ExprKind::Array(args)
1593 | ExprKind::Tup(args)
1597 ExprKind::Path(QPath::Resolved(
1599 Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. },
1604 ) => args.iter().all(|arg| arg.can_have_side_effects()),
1606 | ExprKind::Match(..)
1607 | ExprKind::MethodCall(..)
1608 | ExprKind::Call(..)
1609 | ExprKind::Closure(..)
1610 | ExprKind::Block(..)
1611 | ExprKind::Repeat(..)
1612 | ExprKind::Break(..)
1613 | ExprKind::Continue(..)
1616 | ExprKind::Loop(..)
1617 | ExprKind::Assign(..)
1618 | ExprKind::InlineAsm(..)
1619 | ExprKind::LlvmInlineAsm(..)
1620 | ExprKind::AssignOp(..)
1621 | ExprKind::ConstBlock(..)
1623 | ExprKind::Binary(..)
1624 | ExprKind::Yield(..)
1625 | ExprKind::DropTemps(..)
1626 | ExprKind::Err => true,
1631 /// Checks if the specified expression is a built-in range literal.
1632 /// (See: `LoweringContext::lower_expr()`).
1633 pub fn is_range_literal(expr: &Expr<'_>) -> bool {
1635 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1636 ExprKind::Struct(ref qpath, _, _) => matches!(
1641 | LangItem::RangeFrom
1642 | LangItem::RangeFull
1643 | LangItem::RangeToInclusive,
1648 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1649 ExprKind::Call(ref func, _) => {
1650 matches!(func.kind, ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, ..)))
1657 #[derive(Debug, HashStable_Generic)]
1658 pub enum ExprKind<'hir> {
1659 /// A `box x` expression.
1660 Box(&'hir Expr<'hir>),
1661 /// Allow anonymous constants from an inline `const` block
1662 ConstBlock(AnonConst),
1663 /// An array (e.g., `[a, b, c, d]`).
1664 Array(&'hir [Expr<'hir>]),
1665 /// A function call.
1667 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1668 /// and the second field is the list of arguments.
1669 /// This also represents calling the constructor of
1670 /// tuple-like ADTs such as tuple structs and enum variants.
1671 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1672 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1674 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1675 /// (within the angle brackets).
1676 /// The first element of the vector of `Expr`s is the expression that evaluates
1677 /// to the object on which the method is being called on (the receiver),
1678 /// and the remaining elements are the rest of the arguments.
1679 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1680 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1681 /// The final `Span` represents the span of the function and arguments
1682 /// (e.g. `foo::<Bar, Baz>(a, b, c, d)` in `x.foo::<Bar, Baz>(a, b, c, d)`
1684 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1685 /// the `hir_id` of the `MethodCall` node itself.
1687 /// [`type_dependent_def_id`]: ../ty/struct.TypeckResults.html#method.type_dependent_def_id
1688 MethodCall(&'hir PathSegment<'hir>, Span, &'hir [Expr<'hir>], Span),
1689 /// A tuple (e.g., `(a, b, c, d)`).
1690 Tup(&'hir [Expr<'hir>]),
1691 /// A binary operation (e.g., `a + b`, `a * b`).
1692 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1693 /// A unary operation (e.g., `!x`, `*x`).
1694 Unary(UnOp, &'hir Expr<'hir>),
1695 /// A literal (e.g., `1`, `"foo"`).
1697 /// A cast (e.g., `foo as f64`).
1698 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1699 /// A type reference (e.g., `Foo`).
1700 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1701 /// Wraps the expression in a terminating scope.
1702 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1704 /// This construct only exists to tweak the drop order in HIR lowering.
1705 /// An example of that is the desugaring of `for` loops.
1706 DropTemps(&'hir Expr<'hir>),
1707 /// A `let $pat = $expr` expression.
1709 /// These are not `Local` and only occur as expressions.
1710 /// The `let Some(x) = foo()` in `if let Some(x) = foo()` is an example of `Let(..)`.
1711 Let(&'hir Let<'hir>),
1712 /// An `if` block, with an optional else block.
1714 /// I.e., `if <expr> { <expr> } else { <expr> }`.
1715 If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
1716 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1718 /// I.e., `'label: loop { <block> }`.
1720 /// The `Span` is the loop header (`for x in y`/`while let pat = expr`).
1721 Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span),
1722 /// A `match` block, with a source that indicates whether or not it is
1723 /// the result of a desugaring, and if so, which kind.
1724 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1725 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1727 /// The `Span` is the argument block `|...|`.
1729 /// This may also be a generator literal or an `async block` as indicated by the
1730 /// `Option<Movability>`.
1731 Closure(CaptureBy, &'hir FnDecl<'hir>, BodyId, Span, Option<Movability>),
1732 /// A block (e.g., `'label: { ... }`).
1733 Block(&'hir Block<'hir>, Option<Label>),
1735 /// An assignment (e.g., `a = foo()`).
1736 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1737 /// An assignment with an operator.
1740 AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1741 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1742 Field(&'hir Expr<'hir>, Ident),
1743 /// An indexing operation (`foo[2]`).
1744 Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1746 /// Path to a definition, possibly containing lifetime or type parameters.
1749 /// A referencing operation (i.e., `&a` or `&mut a`).
1750 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1751 /// A `break`, with an optional label to break.
1752 Break(Destination, Option<&'hir Expr<'hir>>),
1753 /// A `continue`, with an optional label.
1754 Continue(Destination),
1755 /// A `return`, with an optional value to be returned.
1756 Ret(Option<&'hir Expr<'hir>>),
1758 /// Inline assembly (from `asm!`), with its outputs and inputs.
1759 InlineAsm(&'hir InlineAsm<'hir>),
1760 /// Inline assembly (from `llvm_asm!`), with its outputs and inputs.
1761 LlvmInlineAsm(&'hir LlvmInlineAsm<'hir>),
1763 /// A struct or struct-like variant literal expression.
1765 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1766 /// where `base` is the `Option<Expr>`.
1767 Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], Option<&'hir Expr<'hir>>),
1769 /// An array literal constructed from one repeated element.
1771 /// E.g., `[1; 5]`. The first expression is the element
1772 /// to be repeated; the second is the number of times to repeat it.
1773 Repeat(&'hir Expr<'hir>, ArrayLen),
1775 /// A suspension point for generators (i.e., `yield <expr>`).
1776 Yield(&'hir Expr<'hir>, YieldSource),
1778 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1782 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1784 /// To resolve the path to a `DefId`, call [`qpath_res`].
1786 /// [`qpath_res`]: ../rustc_middle/ty/struct.TypeckResults.html#method.qpath_res
1787 #[derive(Debug, HashStable_Generic)]
1788 pub enum QPath<'hir> {
1789 /// Path to a definition, optionally "fully-qualified" with a `Self`
1790 /// type, if the path points to an associated item in a trait.
1792 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1793 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1794 /// even though they both have the same two-segment `Clone::clone` `Path`.
1795 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
1797 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1798 /// Will be resolved by type-checking to an associated item.
1800 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1801 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1802 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1803 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
1805 /// Reference to a `#[lang = "foo"]` item. `HirId` of the inner expr.
1806 LangItem(LangItem, Span, Option<HirId>),
1809 impl<'hir> QPath<'hir> {
1810 /// Returns the span of this `QPath`.
1811 pub fn span(&self) -> Span {
1813 QPath::Resolved(_, path) => path.span,
1814 QPath::TypeRelative(qself, ps) => qself.span.to(ps.ident.span),
1815 QPath::LangItem(_, span, _) => span,
1819 /// Returns the span of the qself of this `QPath`. For example, `()` in
1820 /// `<() as Trait>::method`.
1821 pub fn qself_span(&self) -> Span {
1823 QPath::Resolved(_, path) => path.span,
1824 QPath::TypeRelative(qself, _) => qself.span,
1825 QPath::LangItem(_, span, _) => span,
1829 /// Returns the span of the last segment of this `QPath`. For example, `method` in
1830 /// `<() as Trait>::method`.
1831 pub fn last_segment_span(&self) -> Span {
1833 QPath::Resolved(_, path) => path.segments.last().unwrap().ident.span,
1834 QPath::TypeRelative(_, segment) => segment.ident.span,
1835 QPath::LangItem(_, span, _) => span,
1840 /// Hints at the original code for a let statement.
1841 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1842 pub enum LocalSource {
1843 /// A `match _ { .. }`.
1845 /// When lowering async functions, we create locals within the `async move` so that
1846 /// all parameters are dropped after the future is polled.
1848 /// ```ignore (pseudo-Rust)
1849 /// async fn foo(<pattern> @ x: Type) {
1851 /// let <pattern> = x;
1856 /// A desugared `<expr>.await`.
1858 /// A desugared `expr = expr`, where the LHS is a tuple, struct or array.
1859 /// The span is that of the `=` sign.
1860 AssignDesugar(Span),
1863 /// Hints at the original code for a `match _ { .. }`.
1864 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
1865 #[derive(HashStable_Generic)]
1866 pub enum MatchSource {
1867 /// A `match _ { .. }`.
1869 /// A desugared `for _ in _ { .. }` loop.
1871 /// A desugared `?` operator.
1873 /// A desugared `<expr>.await`.
1879 pub const fn name(self) -> &'static str {
1883 ForLoopDesugar => "for",
1885 AwaitDesugar => ".await",
1890 /// The loop type that yielded an `ExprKind::Loop`.
1891 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1892 pub enum LoopSource {
1893 /// A `loop { .. }` loop.
1895 /// A `while _ { .. }` loop.
1897 /// A `for _ in _ { .. }` loop.
1902 pub fn name(self) -> &'static str {
1904 LoopSource::Loop => "loop",
1905 LoopSource::While => "while",
1906 LoopSource::ForLoop => "for",
1911 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1912 pub enum LoopIdError {
1914 UnlabeledCfInWhileCondition,
1918 impl fmt::Display for LoopIdError {
1919 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1920 f.write_str(match self {
1921 LoopIdError::OutsideLoopScope => "not inside loop scope",
1922 LoopIdError::UnlabeledCfInWhileCondition => {
1923 "unlabeled control flow (break or continue) in while condition"
1925 LoopIdError::UnresolvedLabel => "label not found",
1930 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1931 pub struct Destination {
1932 // This is `Some(_)` iff there is an explicit user-specified `label
1933 pub label: Option<Label>,
1935 // These errors are caught and then reported during the diagnostics pass in
1936 // librustc_passes/loops.rs
1937 pub target_id: Result<HirId, LoopIdError>,
1940 /// The yield kind that caused an `ExprKind::Yield`.
1941 #[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
1942 pub enum YieldSource {
1943 /// An `<expr>.await`.
1944 Await { expr: Option<HirId> },
1945 /// A plain `yield`.
1950 pub fn is_await(&self) -> bool {
1952 YieldSource::Await { .. } => true,
1953 YieldSource::Yield => false,
1958 impl fmt::Display for YieldSource {
1959 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1960 f.write_str(match self {
1961 YieldSource::Await { .. } => "`await`",
1962 YieldSource::Yield => "`yield`",
1967 impl From<GeneratorKind> for YieldSource {
1968 fn from(kind: GeneratorKind) -> Self {
1970 // Guess based on the kind of the current generator.
1971 GeneratorKind::Gen => Self::Yield,
1972 GeneratorKind::Async(_) => Self::Await { expr: None },
1977 // N.B., if you change this, you'll probably want to change the corresponding
1978 // type structure in middle/ty.rs as well.
1979 #[derive(Debug, HashStable_Generic)]
1980 pub struct MutTy<'hir> {
1981 pub ty: &'hir Ty<'hir>,
1982 pub mutbl: Mutability,
1985 /// Represents a function's signature in a trait declaration,
1986 /// trait implementation, or a free function.
1987 #[derive(Debug, HashStable_Generic)]
1988 pub struct FnSig<'hir> {
1989 pub header: FnHeader,
1990 pub decl: &'hir FnDecl<'hir>,
1994 // The bodies for items are stored "out of line", in a separate
1995 // hashmap in the `Crate`. Here we just record the hir-id of the item
1996 // so it can fetched later.
1997 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug)]
1998 pub struct TraitItemId {
1999 pub def_id: LocalDefId,
2004 pub fn hir_id(&self) -> HirId {
2005 // Items are always HIR owners.
2006 HirId::make_owner(self.def_id)
2010 /// Represents an item declaration within a trait declaration,
2011 /// possibly including a default implementation. A trait item is
2012 /// either required (meaning it doesn't have an implementation, just a
2013 /// signature) or provided (meaning it has a default implementation).
2015 pub struct TraitItem<'hir> {
2017 pub def_id: LocalDefId,
2018 pub generics: Generics<'hir>,
2019 pub kind: TraitItemKind<'hir>,
2023 impl TraitItem<'_> {
2025 pub fn hir_id(&self) -> HirId {
2026 // Items are always HIR owners.
2027 HirId::make_owner(self.def_id)
2030 pub fn trait_item_id(&self) -> TraitItemId {
2031 TraitItemId { def_id: self.def_id }
2035 /// Represents a trait method's body (or just argument names).
2036 #[derive(Encodable, Debug, HashStable_Generic)]
2037 pub enum TraitFn<'hir> {
2038 /// No default body in the trait, just a signature.
2039 Required(&'hir [Ident]),
2041 /// Both signature and body are provided in the trait.
2045 /// Represents a trait method or associated constant or type
2046 #[derive(Debug, HashStable_Generic)]
2047 pub enum TraitItemKind<'hir> {
2048 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
2049 Const(&'hir Ty<'hir>, Option<BodyId>),
2050 /// An associated function with an optional body.
2051 Fn(FnSig<'hir>, TraitFn<'hir>),
2052 /// An associated type with (possibly empty) bounds and optional concrete
2054 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
2057 // The bodies for items are stored "out of line", in a separate
2058 // hashmap in the `Crate`. Here we just record the hir-id of the item
2059 // so it can fetched later.
2060 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug)]
2061 pub struct ImplItemId {
2062 pub def_id: LocalDefId,
2067 pub fn hir_id(&self) -> HirId {
2068 // Items are always HIR owners.
2069 HirId::make_owner(self.def_id)
2073 /// Represents anything within an `impl` block.
2075 pub struct ImplItem<'hir> {
2077 pub def_id: LocalDefId,
2078 pub vis: Visibility<'hir>,
2079 pub defaultness: Defaultness,
2080 pub generics: Generics<'hir>,
2081 pub kind: ImplItemKind<'hir>,
2087 pub fn hir_id(&self) -> HirId {
2088 // Items are always HIR owners.
2089 HirId::make_owner(self.def_id)
2092 pub fn impl_item_id(&self) -> ImplItemId {
2093 ImplItemId { def_id: self.def_id }
2097 /// Represents various kinds of content within an `impl`.
2098 #[derive(Debug, HashStable_Generic)]
2099 pub enum ImplItemKind<'hir> {
2100 /// An associated constant of the given type, set to the constant result
2101 /// of the expression.
2102 Const(&'hir Ty<'hir>, BodyId),
2103 /// An associated function implementation with the given signature and body.
2104 Fn(FnSig<'hir>, BodyId),
2105 /// An associated type.
2106 TyAlias(&'hir Ty<'hir>),
2109 // The name of the associated type for `Fn` return types.
2110 pub const FN_OUTPUT_NAME: Symbol = sym::Output;
2112 /// Bind a type to an associated type (i.e., `A = Foo`).
2114 /// Bindings like `A: Debug` are represented as a special type `A =
2115 /// $::Debug` that is understood by the astconv code.
2117 /// FIXME(alexreg): why have a separate type for the binding case,
2118 /// wouldn't it be better to make the `ty` field an enum like the
2122 /// enum TypeBindingKind {
2127 #[derive(Debug, HashStable_Generic)]
2128 pub struct TypeBinding<'hir> {
2130 #[stable_hasher(project(name))]
2132 pub gen_args: &'hir GenericArgs<'hir>,
2133 pub kind: TypeBindingKind<'hir>,
2137 // Represents the two kinds of type bindings.
2138 #[derive(Debug, HashStable_Generic)]
2139 pub enum TypeBindingKind<'hir> {
2140 /// E.g., `Foo<Bar: Send>`.
2141 Constraint { bounds: &'hir [GenericBound<'hir>] },
2142 /// E.g., `Foo<Bar = ()>`.
2143 Equality { ty: &'hir Ty<'hir> },
2146 impl TypeBinding<'_> {
2147 pub fn ty(&self) -> &Ty<'_> {
2149 TypeBindingKind::Equality { ref ty } => ty,
2150 _ => panic!("expected equality type binding for parenthesized generic args"),
2156 pub struct Ty<'hir> {
2158 pub kind: TyKind<'hir>,
2162 /// Not represented directly in the AST; referred to by name through a `ty_path`.
2163 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
2164 #[derive(HashStable_Generic)]
2175 /// All of the primitive types
2176 pub const ALL: [Self; 17] = [
2177 // any changes here should also be reflected in `PrimTy::from_name`
2178 Self::Int(IntTy::I8),
2179 Self::Int(IntTy::I16),
2180 Self::Int(IntTy::I32),
2181 Self::Int(IntTy::I64),
2182 Self::Int(IntTy::I128),
2183 Self::Int(IntTy::Isize),
2184 Self::Uint(UintTy::U8),
2185 Self::Uint(UintTy::U16),
2186 Self::Uint(UintTy::U32),
2187 Self::Uint(UintTy::U64),
2188 Self::Uint(UintTy::U128),
2189 Self::Uint(UintTy::Usize),
2190 Self::Float(FloatTy::F32),
2191 Self::Float(FloatTy::F64),
2197 /// Like [`PrimTy::name`], but returns a &str instead of a symbol.
2200 pub fn name_str(self) -> &'static str {
2202 PrimTy::Int(i) => i.name_str(),
2203 PrimTy::Uint(u) => u.name_str(),
2204 PrimTy::Float(f) => f.name_str(),
2205 PrimTy::Str => "str",
2206 PrimTy::Bool => "bool",
2207 PrimTy::Char => "char",
2211 pub fn name(self) -> Symbol {
2213 PrimTy::Int(i) => i.name(),
2214 PrimTy::Uint(u) => u.name(),
2215 PrimTy::Float(f) => f.name(),
2216 PrimTy::Str => sym::str,
2217 PrimTy::Bool => sym::bool,
2218 PrimTy::Char => sym::char,
2222 /// Returns the matching `PrimTy` for a `Symbol` such as "str" or "i32".
2223 /// Returns `None` if no matching type is found.
2224 pub fn from_name(name: Symbol) -> Option<Self> {
2225 let ty = match name {
2226 // any changes here should also be reflected in `PrimTy::ALL`
2227 sym::i8 => Self::Int(IntTy::I8),
2228 sym::i16 => Self::Int(IntTy::I16),
2229 sym::i32 => Self::Int(IntTy::I32),
2230 sym::i64 => Self::Int(IntTy::I64),
2231 sym::i128 => Self::Int(IntTy::I128),
2232 sym::isize => Self::Int(IntTy::Isize),
2233 sym::u8 => Self::Uint(UintTy::U8),
2234 sym::u16 => Self::Uint(UintTy::U16),
2235 sym::u32 => Self::Uint(UintTy::U32),
2236 sym::u64 => Self::Uint(UintTy::U64),
2237 sym::u128 => Self::Uint(UintTy::U128),
2238 sym::usize => Self::Uint(UintTy::Usize),
2239 sym::f32 => Self::Float(FloatTy::F32),
2240 sym::f64 => Self::Float(FloatTy::F64),
2241 sym::bool => Self::Bool,
2242 sym::char => Self::Char,
2243 sym::str => Self::Str,
2250 #[derive(Debug, HashStable_Generic)]
2251 pub struct BareFnTy<'hir> {
2252 pub unsafety: Unsafety,
2254 pub generic_params: &'hir [GenericParam<'hir>],
2255 pub decl: &'hir FnDecl<'hir>,
2256 pub param_names: &'hir [Ident],
2259 #[derive(Debug, HashStable_Generic)]
2260 pub struct OpaqueTy<'hir> {
2261 pub generics: Generics<'hir>,
2262 pub bounds: GenericBounds<'hir>,
2263 pub origin: OpaqueTyOrigin,
2266 /// From whence the opaque type came.
2267 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2268 pub enum OpaqueTyOrigin {
2270 FnReturn(LocalDefId),
2272 AsyncFn(LocalDefId),
2273 /// type aliases: `type Foo = impl Trait;`
2277 /// The various kinds of types recognized by the compiler.
2278 #[derive(Debug, HashStable_Generic)]
2279 pub enum TyKind<'hir> {
2280 /// A variable length slice (i.e., `[T]`).
2281 Slice(&'hir Ty<'hir>),
2282 /// A fixed length array (i.e., `[T; n]`).
2283 Array(&'hir Ty<'hir>, ArrayLen),
2284 /// A raw pointer (i.e., `*const T` or `*mut T`).
2286 /// A reference (i.e., `&'a T` or `&'a mut T`).
2287 Rptr(Lifetime, MutTy<'hir>),
2288 /// A bare function (e.g., `fn(usize) -> bool`).
2289 BareFn(&'hir BareFnTy<'hir>),
2290 /// The never type (`!`).
2292 /// A tuple (`(A, B, C, D, ...)`).
2293 Tup(&'hir [Ty<'hir>]),
2294 /// A path to a type definition (`module::module::...::Type`), or an
2295 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2297 /// Type parameters may be stored in each `PathSegment`.
2299 /// An opaque type definition itself. This is only used for `impl Trait`.
2301 /// The generic argument list contains the lifetimes (and in the future
2302 /// possibly parameters) that are actually bound on the `impl Trait`.
2303 OpaqueDef(ItemId, &'hir [GenericArg<'hir>]),
2304 /// A trait object type `Bound1 + Bound2 + Bound3`
2305 /// where `Bound` is a trait or a lifetime.
2306 TraitObject(&'hir [PolyTraitRef<'hir>], Lifetime, TraitObjectSyntax),
2309 /// `TyKind::Infer` means the type should be inferred instead of it having been
2310 /// specified. This can appear anywhere in a type.
2312 /// Placeholder for a type that has failed to be defined.
2316 #[derive(Debug, HashStable_Generic)]
2317 pub enum InlineAsmOperand<'hir> {
2319 reg: InlineAsmRegOrRegClass,
2323 reg: InlineAsmRegOrRegClass,
2325 expr: Option<Expr<'hir>>,
2328 reg: InlineAsmRegOrRegClass,
2333 reg: InlineAsmRegOrRegClass,
2335 in_expr: Expr<'hir>,
2336 out_expr: Option<Expr<'hir>>,
2339 anon_const: AnonConst,
2346 impl<'hir> InlineAsmOperand<'hir> {
2347 pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
2349 Self::In { reg, .. }
2350 | Self::Out { reg, .. }
2351 | Self::InOut { reg, .. }
2352 | Self::SplitInOut { reg, .. } => Some(reg),
2353 Self::Const { .. } | Self::Sym { .. } => None,
2357 pub fn is_clobber(&self) -> bool {
2360 InlineAsmOperand::Out { reg: InlineAsmRegOrRegClass::Reg(_), late: _, expr: None }
2365 #[derive(Debug, HashStable_Generic)]
2366 pub struct InlineAsm<'hir> {
2367 pub template: &'hir [InlineAsmTemplatePiece],
2368 pub template_strs: &'hir [(Symbol, Option<Symbol>, Span)],
2369 pub operands: &'hir [(InlineAsmOperand<'hir>, Span)],
2370 pub options: InlineAsmOptions,
2371 pub line_spans: &'hir [Span],
2374 #[derive(Copy, Clone, Encodable, Decodable, Debug, Hash, HashStable_Generic, PartialEq)]
2375 pub struct LlvmInlineAsmOutput {
2376 pub constraint: Symbol,
2378 pub is_indirect: bool,
2382 // NOTE(eddyb) This is used within MIR as well, so unlike the rest of the HIR,
2383 // it needs to be `Clone` and `Decodable` and use plain `Vec<T>` instead of
2384 // arena-allocated slice.
2385 #[derive(Clone, Encodable, Decodable, Debug, Hash, HashStable_Generic, PartialEq)]
2386 pub struct LlvmInlineAsmInner {
2388 pub asm_str_style: StrStyle,
2389 pub outputs: Vec<LlvmInlineAsmOutput>,
2390 pub inputs: Vec<Symbol>,
2391 pub clobbers: Vec<Symbol>,
2393 pub alignstack: bool,
2394 pub dialect: LlvmAsmDialect,
2397 #[derive(Debug, HashStable_Generic)]
2398 pub struct LlvmInlineAsm<'hir> {
2399 pub inner: LlvmInlineAsmInner,
2400 pub outputs_exprs: &'hir [Expr<'hir>],
2401 pub inputs_exprs: &'hir [Expr<'hir>],
2404 /// Represents a parameter in a function header.
2405 #[derive(Debug, HashStable_Generic)]
2406 pub struct Param<'hir> {
2408 pub pat: &'hir Pat<'hir>,
2413 /// Represents the header (not the body) of a function declaration.
2414 #[derive(Debug, HashStable_Generic)]
2415 pub struct FnDecl<'hir> {
2416 /// The types of the function's parameters.
2418 /// Additional argument data is stored in the function's [body](Body::params).
2419 pub inputs: &'hir [Ty<'hir>],
2420 pub output: FnRetTy<'hir>,
2421 pub c_variadic: bool,
2422 /// Does the function have an implicit self?
2423 pub implicit_self: ImplicitSelfKind,
2426 /// Represents what type of implicit self a function has, if any.
2427 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2428 pub enum ImplicitSelfKind {
2429 /// Represents a `fn x(self);`.
2431 /// Represents a `fn x(mut self);`.
2433 /// Represents a `fn x(&self);`.
2435 /// Represents a `fn x(&mut self);`.
2437 /// Represents when a function does not have a self argument or
2438 /// when a function has a `self: X` argument.
2442 impl ImplicitSelfKind {
2443 /// Does this represent an implicit self?
2444 pub fn has_implicit_self(&self) -> bool {
2445 !matches!(*self, ImplicitSelfKind::None)
2449 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable, Debug)]
2450 #[derive(HashStable_Generic)]
2456 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable, HashStable_Generic)]
2457 pub enum Defaultness {
2458 Default { has_value: bool },
2463 pub fn has_value(&self) -> bool {
2465 Defaultness::Default { has_value } => has_value,
2466 Defaultness::Final => true,
2470 pub fn is_final(&self) -> bool {
2471 *self == Defaultness::Final
2474 pub fn is_default(&self) -> bool {
2475 matches!(*self, Defaultness::Default { .. })
2479 #[derive(Debug, HashStable_Generic)]
2480 pub enum FnRetTy<'hir> {
2481 /// Return type is not specified.
2483 /// Functions default to `()` and
2484 /// closures default to inference. Span points to where return
2485 /// type would be inserted.
2486 DefaultReturn(Span),
2487 /// Everything else.
2488 Return(&'hir Ty<'hir>),
2493 pub fn span(&self) -> Span {
2495 Self::DefaultReturn(span) => span,
2496 Self::Return(ref ty) => ty.span,
2501 #[derive(Encodable, Debug, HashStable_Generic)]
2502 pub struct Mod<'hir> {
2503 /// A span from the first token past `{` to the last token until `}`.
2504 /// For `mod foo;`, the inner span ranges from the first token
2505 /// to the last token in the external file.
2507 pub item_ids: &'hir [ItemId],
2510 #[derive(Debug, HashStable_Generic)]
2511 pub struct EnumDef<'hir> {
2512 pub variants: &'hir [Variant<'hir>],
2515 #[derive(Debug, HashStable_Generic)]
2516 pub struct Variant<'hir> {
2517 /// Name of the variant.
2518 #[stable_hasher(project(name))]
2520 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2522 /// Fields and constructor id of the variant.
2523 pub data: VariantData<'hir>,
2524 /// Explicit discriminant (e.g., `Foo = 1`).
2525 pub disr_expr: Option<AnonConst>,
2530 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2532 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2533 /// Also produced for each element of a list `use`, e.g.
2534 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2537 /// Glob import, e.g., `use foo::*`.
2540 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2541 /// an additional `use foo::{}` for performing checks such as
2542 /// unstable feature gating. May be removed in the future.
2546 /// References to traits in impls.
2548 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2549 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2550 /// trait being referred to but just a unique `HirId` that serves as a key
2551 /// within the resolution map.
2552 #[derive(Clone, Debug, HashStable_Generic)]
2553 pub struct TraitRef<'hir> {
2554 pub path: &'hir Path<'hir>,
2555 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2556 #[stable_hasher(ignore)]
2557 pub hir_ref_id: HirId,
2561 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2562 pub fn trait_def_id(&self) -> Option<DefId> {
2563 match self.path.res {
2564 Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
2566 _ => unreachable!(),
2571 #[derive(Clone, Debug, HashStable_Generic)]
2572 pub struct PolyTraitRef<'hir> {
2573 /// The `'a` in `for<'a> Foo<&'a T>`.
2574 pub bound_generic_params: &'hir [GenericParam<'hir>],
2576 /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
2577 pub trait_ref: TraitRef<'hir>,
2582 pub type Visibility<'hir> = Spanned<VisibilityKind<'hir>>;
2584 #[derive(Copy, Clone, Debug)]
2585 pub enum VisibilityKind<'hir> {
2588 Restricted { path: &'hir Path<'hir>, hir_id: HirId },
2592 impl VisibilityKind<'_> {
2593 pub fn is_pub(&self) -> bool {
2594 matches!(*self, VisibilityKind::Public)
2597 pub fn is_pub_restricted(&self) -> bool {
2599 VisibilityKind::Public | VisibilityKind::Inherited => false,
2600 VisibilityKind::Crate(..) | VisibilityKind::Restricted { .. } => true,
2605 #[derive(Debug, HashStable_Generic)]
2606 pub struct FieldDef<'hir> {
2608 #[stable_hasher(project(name))]
2610 pub vis: Visibility<'hir>,
2612 pub ty: &'hir Ty<'hir>,
2616 // Still necessary in couple of places
2617 pub fn is_positional(&self) -> bool {
2618 let first = self.ident.as_str().as_bytes()[0];
2619 (b'0'..=b'9').contains(&first)
2623 /// Fields and constructor IDs of enum variants and structs.
2624 #[derive(Debug, HashStable_Generic)]
2625 pub enum VariantData<'hir> {
2626 /// A struct variant.
2628 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2629 Struct(&'hir [FieldDef<'hir>], /* recovered */ bool),
2630 /// A tuple variant.
2632 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2633 Tuple(&'hir [FieldDef<'hir>], HirId),
2636 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2640 impl<'hir> VariantData<'hir> {
2641 /// Return the fields of this variant.
2642 pub fn fields(&self) -> &'hir [FieldDef<'hir>] {
2644 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2649 /// Return the `HirId` of this variant's constructor, if it has one.
2650 pub fn ctor_hir_id(&self) -> Option<HirId> {
2652 VariantData::Struct(_, _) => None,
2653 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2658 // The bodies for items are stored "out of line", in a separate
2659 // hashmap in the `Crate`. Here we just record the hir-id of the item
2660 // so it can fetched later.
2661 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, Hash)]
2663 pub def_id: LocalDefId,
2668 pub fn hir_id(&self) -> HirId {
2669 // Items are always HIR owners.
2670 HirId::make_owner(self.def_id)
2676 /// The name might be a dummy name in case of anonymous items
2678 pub struct Item<'hir> {
2680 pub def_id: LocalDefId,
2681 pub kind: ItemKind<'hir>,
2682 pub vis: Visibility<'hir>,
2688 pub fn hir_id(&self) -> HirId {
2689 // Items are always HIR owners.
2690 HirId::make_owner(self.def_id)
2693 pub fn item_id(&self) -> ItemId {
2694 ItemId { def_id: self.def_id }
2698 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2699 #[derive(Encodable, Decodable, HashStable_Generic)]
2706 pub fn prefix_str(&self) -> &'static str {
2708 Self::Unsafe => "unsafe ",
2714 impl fmt::Display for Unsafety {
2715 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2716 f.write_str(match *self {
2717 Self::Unsafe => "unsafe",
2718 Self::Normal => "normal",
2723 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2724 #[derive(Encodable, Decodable, HashStable_Generic)]
2725 pub enum Constness {
2730 impl fmt::Display for Constness {
2731 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2732 f.write_str(match *self {
2733 Self::Const => "const",
2734 Self::NotConst => "non-const",
2739 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2740 pub struct FnHeader {
2741 pub unsafety: Unsafety,
2742 pub constness: Constness,
2743 pub asyncness: IsAsync,
2748 pub fn is_const(&self) -> bool {
2749 matches!(&self.constness, Constness::Const)
2753 #[derive(Debug, HashStable_Generic)]
2754 pub enum ItemKind<'hir> {
2755 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2757 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2758 ExternCrate(Option<Symbol>),
2760 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2764 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2765 Use(&'hir Path<'hir>, UseKind),
2767 /// A `static` item.
2768 Static(&'hir Ty<'hir>, Mutability, BodyId),
2770 Const(&'hir Ty<'hir>, BodyId),
2771 /// A function declaration.
2772 Fn(FnSig<'hir>, Generics<'hir>, BodyId),
2773 /// A MBE macro definition (`macro_rules!` or `macro`).
2774 Macro(ast::MacroDef),
2777 /// An external module, e.g. `extern { .. }`.
2778 ForeignMod { abi: Abi, items: &'hir [ForeignItemRef] },
2779 /// Module-level inline assembly (from `global_asm!`).
2780 GlobalAsm(&'hir InlineAsm<'hir>),
2781 /// A type alias, e.g., `type Foo = Bar<u8>`.
2782 TyAlias(&'hir Ty<'hir>, Generics<'hir>),
2783 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2784 OpaqueTy(OpaqueTy<'hir>),
2785 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2786 Enum(EnumDef<'hir>, Generics<'hir>),
2787 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2788 Struct(VariantData<'hir>, Generics<'hir>),
2789 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2790 Union(VariantData<'hir>, Generics<'hir>),
2791 /// A trait definition.
2792 Trait(IsAuto, Unsafety, Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
2794 TraitAlias(Generics<'hir>, GenericBounds<'hir>),
2796 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2800 #[derive(Debug, HashStable_Generic)]
2801 pub struct Impl<'hir> {
2802 pub unsafety: Unsafety,
2803 pub polarity: ImplPolarity,
2804 pub defaultness: Defaultness,
2805 // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata
2806 // decoding as `Span`s cannot be decoded when a `Session` is not available.
2807 pub defaultness_span: Option<Span>,
2808 pub constness: Constness,
2809 pub generics: Generics<'hir>,
2811 /// The trait being implemented, if any.
2812 pub of_trait: Option<TraitRef<'hir>>,
2814 pub self_ty: &'hir Ty<'hir>,
2815 pub items: &'hir [ImplItemRef],
2819 pub fn generics(&self) -> Option<&Generics<'_>> {
2821 ItemKind::Fn(_, ref generics, _)
2822 | ItemKind::TyAlias(_, ref generics)
2823 | ItemKind::OpaqueTy(OpaqueTy {
2824 ref generics, origin: OpaqueTyOrigin::TyAlias, ..
2826 | ItemKind::Enum(_, ref generics)
2827 | ItemKind::Struct(_, ref generics)
2828 | ItemKind::Union(_, ref generics)
2829 | ItemKind::Trait(_, _, ref generics, _, _)
2830 | ItemKind::Impl(Impl { ref generics, .. }) => generics,
2835 pub fn descr(&self) -> &'static str {
2837 ItemKind::ExternCrate(..) => "extern crate",
2838 ItemKind::Use(..) => "`use` import",
2839 ItemKind::Static(..) => "static item",
2840 ItemKind::Const(..) => "constant item",
2841 ItemKind::Fn(..) => "function",
2842 ItemKind::Macro(..) => "macro",
2843 ItemKind::Mod(..) => "module",
2844 ItemKind::ForeignMod { .. } => "extern block",
2845 ItemKind::GlobalAsm(..) => "global asm item",
2846 ItemKind::TyAlias(..) => "type alias",
2847 ItemKind::OpaqueTy(..) => "opaque type",
2848 ItemKind::Enum(..) => "enum",
2849 ItemKind::Struct(..) => "struct",
2850 ItemKind::Union(..) => "union",
2851 ItemKind::Trait(..) => "trait",
2852 ItemKind::TraitAlias(..) => "trait alias",
2853 ItemKind::Impl(..) => "implementation",
2858 /// A reference from an trait to one of its associated items. This
2859 /// contains the item's id, naturally, but also the item's name and
2860 /// some other high-level details (like whether it is an associated
2861 /// type or method, and whether it is public). This allows other
2862 /// passes to find the impl they want without loading the ID (which
2863 /// means fewer edges in the incremental compilation graph).
2864 #[derive(Encodable, Debug, HashStable_Generic)]
2865 pub struct TraitItemRef {
2866 pub id: TraitItemId,
2867 #[stable_hasher(project(name))]
2869 pub kind: AssocItemKind,
2871 pub defaultness: Defaultness,
2874 /// A reference from an impl to one of its associated items. This
2875 /// contains the item's ID, naturally, but also the item's name and
2876 /// some other high-level details (like whether it is an associated
2877 /// type or method, and whether it is public). This allows other
2878 /// passes to find the impl they want without loading the ID (which
2879 /// means fewer edges in the incremental compilation graph).
2880 #[derive(Debug, HashStable_Generic)]
2881 pub struct ImplItemRef {
2883 #[stable_hasher(project(name))]
2885 pub kind: AssocItemKind,
2887 pub defaultness: Defaultness,
2890 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2891 pub enum AssocItemKind {
2893 Fn { has_self: bool },
2897 // The bodies for items are stored "out of line", in a separate
2898 // hashmap in the `Crate`. Here we just record the hir-id of the item
2899 // so it can fetched later.
2900 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug)]
2901 pub struct ForeignItemId {
2902 pub def_id: LocalDefId,
2905 impl ForeignItemId {
2907 pub fn hir_id(&self) -> HirId {
2908 // Items are always HIR owners.
2909 HirId::make_owner(self.def_id)
2913 /// A reference from a foreign block to one of its items. This
2914 /// contains the item's ID, naturally, but also the item's name and
2915 /// some other high-level details (like whether it is an associated
2916 /// type or method, and whether it is public). This allows other
2917 /// passes to find the impl they want without loading the ID (which
2918 /// means fewer edges in the incremental compilation graph).
2919 #[derive(Debug, HashStable_Generic)]
2920 pub struct ForeignItemRef {
2921 pub id: ForeignItemId,
2922 #[stable_hasher(project(name))]
2928 pub struct ForeignItem<'hir> {
2930 pub kind: ForeignItemKind<'hir>,
2931 pub def_id: LocalDefId,
2933 pub vis: Visibility<'hir>,
2936 impl ForeignItem<'_> {
2938 pub fn hir_id(&self) -> HirId {
2939 // Items are always HIR owners.
2940 HirId::make_owner(self.def_id)
2943 pub fn foreign_item_id(&self) -> ForeignItemId {
2944 ForeignItemId { def_id: self.def_id }
2948 /// An item within an `extern` block.
2949 #[derive(Debug, HashStable_Generic)]
2950 pub enum ForeignItemKind<'hir> {
2951 /// A foreign function.
2952 Fn(&'hir FnDecl<'hir>, &'hir [Ident], Generics<'hir>),
2953 /// A foreign static item (`static ext: u8`).
2954 Static(&'hir Ty<'hir>, Mutability),
2959 /// A variable captured by a closure.
2960 #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)]
2962 // First span where it is accessed (there can be multiple).
2966 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2967 // has length > 0 if the trait is found through an chain of imports, starting with the
2968 // import/use statement in the scope where the trait is used.
2969 #[derive(Encodable, Decodable, Clone, Debug)]
2970 pub struct TraitCandidate {
2972 pub import_ids: SmallVec<[LocalDefId; 1]>,
2975 #[derive(Copy, Clone, Debug, HashStable_Generic)]
2976 pub enum OwnerNode<'hir> {
2977 Item(&'hir Item<'hir>),
2978 ForeignItem(&'hir ForeignItem<'hir>),
2979 TraitItem(&'hir TraitItem<'hir>),
2980 ImplItem(&'hir ImplItem<'hir>),
2981 Crate(&'hir Mod<'hir>),
2984 impl<'hir> OwnerNode<'hir> {
2985 pub fn ident(&self) -> Option<Ident> {
2987 OwnerNode::Item(Item { ident, .. })
2988 | OwnerNode::ForeignItem(ForeignItem { ident, .. })
2989 | OwnerNode::ImplItem(ImplItem { ident, .. })
2990 | OwnerNode::TraitItem(TraitItem { ident, .. }) => Some(*ident),
2991 OwnerNode::Crate(..) => None,
2995 pub fn span(&self) -> Span {
2997 OwnerNode::Item(Item { span, .. })
2998 | OwnerNode::ForeignItem(ForeignItem { span, .. })
2999 | OwnerNode::ImplItem(ImplItem { span, .. })
3000 | OwnerNode::TraitItem(TraitItem { span, .. })
3001 | OwnerNode::Crate(Mod { inner: span, .. }) => *span,
3005 pub fn fn_decl(&self) -> Option<&FnDecl<'hir>> {
3007 OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3008 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3009 | OwnerNode::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3010 OwnerNode::ForeignItem(ForeignItem {
3011 kind: ForeignItemKind::Fn(fn_decl, _, _),
3013 }) => Some(fn_decl),
3018 pub fn body_id(&self) -> Option<BodyId> {
3020 OwnerNode::TraitItem(TraitItem {
3021 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3024 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3025 | OwnerNode::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3030 pub fn generics(&self) -> Option<&'hir Generics<'hir>> {
3032 OwnerNode::TraitItem(TraitItem { generics, .. })
3033 | OwnerNode::ImplItem(ImplItem { generics, .. }) => Some(generics),
3034 OwnerNode::Item(item) => item.kind.generics(),
3039 pub fn def_id(self) -> LocalDefId {
3041 OwnerNode::Item(Item { def_id, .. })
3042 | OwnerNode::TraitItem(TraitItem { def_id, .. })
3043 | OwnerNode::ImplItem(ImplItem { def_id, .. })
3044 | OwnerNode::ForeignItem(ForeignItem { def_id, .. }) => *def_id,
3045 OwnerNode::Crate(..) => crate::CRATE_HIR_ID.owner,
3049 pub fn expect_item(self) -> &'hir Item<'hir> {
3051 OwnerNode::Item(n) => n,
3056 pub fn expect_foreign_item(self) -> &'hir ForeignItem<'hir> {
3058 OwnerNode::ForeignItem(n) => n,
3063 pub fn expect_impl_item(self) -> &'hir ImplItem<'hir> {
3065 OwnerNode::ImplItem(n) => n,
3070 pub fn expect_trait_item(self) -> &'hir TraitItem<'hir> {
3072 OwnerNode::TraitItem(n) => n,
3078 impl<'hir> Into<OwnerNode<'hir>> for &'hir Item<'hir> {
3079 fn into(self) -> OwnerNode<'hir> {
3080 OwnerNode::Item(self)
3084 impl<'hir> Into<OwnerNode<'hir>> for &'hir ForeignItem<'hir> {
3085 fn into(self) -> OwnerNode<'hir> {
3086 OwnerNode::ForeignItem(self)
3090 impl<'hir> Into<OwnerNode<'hir>> for &'hir ImplItem<'hir> {
3091 fn into(self) -> OwnerNode<'hir> {
3092 OwnerNode::ImplItem(self)
3096 impl<'hir> Into<OwnerNode<'hir>> for &'hir TraitItem<'hir> {
3097 fn into(self) -> OwnerNode<'hir> {
3098 OwnerNode::TraitItem(self)
3102 impl<'hir> Into<Node<'hir>> for OwnerNode<'hir> {
3103 fn into(self) -> Node<'hir> {
3105 OwnerNode::Item(n) => Node::Item(n),
3106 OwnerNode::ForeignItem(n) => Node::ForeignItem(n),
3107 OwnerNode::ImplItem(n) => Node::ImplItem(n),
3108 OwnerNode::TraitItem(n) => Node::TraitItem(n),
3109 OwnerNode::Crate(n) => Node::Crate(n),
3114 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3115 pub enum Node<'hir> {
3116 Param(&'hir Param<'hir>),
3117 Item(&'hir Item<'hir>),
3118 ForeignItem(&'hir ForeignItem<'hir>),
3119 TraitItem(&'hir TraitItem<'hir>),
3120 ImplItem(&'hir ImplItem<'hir>),
3121 Variant(&'hir Variant<'hir>),
3122 Field(&'hir FieldDef<'hir>),
3123 AnonConst(&'hir AnonConst),
3124 Expr(&'hir Expr<'hir>),
3125 Stmt(&'hir Stmt<'hir>),
3126 PathSegment(&'hir PathSegment<'hir>),
3128 TraitRef(&'hir TraitRef<'hir>),
3129 Binding(&'hir Pat<'hir>),
3130 Pat(&'hir Pat<'hir>),
3131 Arm(&'hir Arm<'hir>),
3132 Block(&'hir Block<'hir>),
3133 Local(&'hir Local<'hir>),
3135 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
3136 /// with synthesized constructors.
3137 Ctor(&'hir VariantData<'hir>),
3139 Lifetime(&'hir Lifetime),
3140 GenericParam(&'hir GenericParam<'hir>),
3141 Visibility(&'hir Visibility<'hir>),
3143 Crate(&'hir Mod<'hir>),
3145 Infer(&'hir InferArg),
3148 impl<'hir> Node<'hir> {
3149 /// Get the identifier of this `Node`, if applicable.
3153 /// Calling `.ident()` on a [`Node::Ctor`] will return `None`
3154 /// because `Ctor`s do not have identifiers themselves.
3155 /// Instead, call `.ident()` on the parent struct/variant, like so:
3157 /// ```ignore (illustrative)
3160 /// .and_then(|ctor_id| tcx.hir().find(tcx.hir().get_parent_node(ctor_id)))
3161 /// .and_then(|parent| parent.ident())
3163 pub fn ident(&self) -> Option<Ident> {
3165 Node::TraitItem(TraitItem { ident, .. })
3166 | Node::ImplItem(ImplItem { ident, .. })
3167 | Node::ForeignItem(ForeignItem { ident, .. })
3168 | Node::Field(FieldDef { ident, .. })
3169 | Node::Variant(Variant { ident, .. })
3170 | Node::Item(Item { ident, .. })
3171 | Node::PathSegment(PathSegment { ident, .. }) => Some(*ident),
3172 Node::Lifetime(lt) => Some(lt.name.ident()),
3173 Node::GenericParam(p) => Some(p.name.ident()),
3175 | Node::AnonConst(..)
3184 | Node::Visibility(..)
3187 | Node::TraitRef(..)
3188 | Node::Infer(..) => None,
3192 pub fn fn_decl(&self) -> Option<&FnDecl<'hir>> {
3194 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3195 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3196 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3197 Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
3204 pub fn body_id(&self) -> Option<BodyId> {
3206 Node::TraitItem(TraitItem {
3207 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3210 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3211 | Node::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3216 pub fn generics(&self) -> Option<&'hir Generics<'hir>> {
3218 Node::TraitItem(TraitItem { generics, .. })
3219 | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
3220 Node::Item(item) => item.kind.generics(),
3225 pub fn as_owner(self) -> Option<OwnerNode<'hir>> {
3227 Node::Item(i) => Some(OwnerNode::Item(i)),
3228 Node::ForeignItem(i) => Some(OwnerNode::ForeignItem(i)),
3229 Node::TraitItem(i) => Some(OwnerNode::TraitItem(i)),
3230 Node::ImplItem(i) => Some(OwnerNode::ImplItem(i)),
3231 Node::Crate(i) => Some(OwnerNode::Crate(i)),
3236 pub fn fn_kind(self) -> Option<FnKind<'hir>> {
3238 Node::Item(i) => match i.kind {
3239 ItemKind::Fn(ref sig, ref generics, _) => {
3240 Some(FnKind::ItemFn(i.ident, generics, sig.header, &i.vis))
3244 Node::TraitItem(ti) => match ti.kind {
3245 TraitItemKind::Fn(ref sig, TraitFn::Provided(_)) => {
3246 Some(FnKind::Method(ti.ident, sig, None))
3250 Node::ImplItem(ii) => match ii.kind {
3251 ImplItemKind::Fn(ref sig, _) => Some(FnKind::Method(ii.ident, sig, Some(&ii.vis))),
3254 Node::Expr(e) => match e.kind {
3255 ExprKind::Closure(..) => Some(FnKind::Closure),
3263 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3264 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
3266 rustc_data_structures::static_assert_size!(super::Block<'static>, 48);
3267 rustc_data_structures::static_assert_size!(super::Expr<'static>, 64);
3268 rustc_data_structures::static_assert_size!(super::Pat<'static>, 88);
3269 rustc_data_structures::static_assert_size!(super::QPath<'static>, 24);
3270 rustc_data_structures::static_assert_size!(super::Ty<'static>, 80);
3272 rustc_data_structures::static_assert_size!(super::Item<'static>, 184);
3273 rustc_data_structures::static_assert_size!(super::TraitItem<'static>, 128);
3274 rustc_data_structures::static_assert_size!(super::ImplItem<'static>, 152);
3275 rustc_data_structures::static_assert_size!(super::ForeignItem<'static>, 136);