1 // ignore-tidy-filelength
2 use crate::def::{CtorKind, DefKind, Res};
3 use crate::def_id::{DefId, CRATE_DEF_ID};
4 crate use crate::hir_id::{HirId, ItemLocalId};
5 use crate::{itemlikevisit, LangItem};
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::fx::FxHashMap;
14 use rustc_data_structures::sync::{par_for_each_in, Send, Sync};
15 use rustc_index::vec::IndexVec;
16 use rustc_macros::HashStable_Generic;
17 use rustc_span::source_map::Spanned;
18 use rustc_span::symbol::{kw, sym, Ident, Symbol};
19 use rustc_span::{def_id::LocalDefId, BytePos};
20 use rustc_span::{MultiSpan, Span, DUMMY_SP};
21 use rustc_target::asm::InlineAsmRegOrRegClass;
22 use rustc_target::spec::abi::Abi;
24 use smallvec::SmallVec;
25 use std::collections::{BTreeMap, BTreeSet};
28 #[derive(Copy, Clone, Encodable, HashStable_Generic)]
33 /// Either "`'a`", referring to a named lifetime definition,
34 /// or "``" (i.e., `kw::Empty`), for elision placeholders.
36 /// HIR lowering inserts these placeholders in type paths that
37 /// refer to type definitions needing lifetime parameters,
38 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
39 pub name: LifetimeName,
42 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
43 #[derive(HashStable_Generic)]
45 /// Some user-given name like `T` or `'x`.
48 /// Synthetic name generated when user elided a lifetime in an impl header.
50 /// E.g., the lifetimes in cases like these:
53 /// impl Foo<'_> for u32
55 /// in that case, we rewrite to
57 /// impl<'f> Foo for &'f u32
58 /// impl<'f> Foo<'f> for u32
60 /// where `'f` is something like `Fresh(0)`. The indices are
61 /// unique per impl, but not necessarily continuous.
64 /// Indicates an illegal name was given and an error has been
65 /// reported (so we should squelch other derived errors). Occurs
66 /// when, e.g., `'_` is used in the wrong place.
71 pub fn ident(&self) -> Ident {
73 ParamName::Plain(ident) => ident,
74 ParamName::Fresh(_) | ParamName::Error => {
75 Ident::with_dummy_span(kw::UnderscoreLifetime)
80 pub fn normalize_to_macros_2_0(&self) -> ParamName {
82 ParamName::Plain(ident) => ParamName::Plain(ident.normalize_to_macros_2_0()),
83 param_name => param_name,
88 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
89 #[derive(HashStable_Generic)]
90 pub enum LifetimeName {
91 /// User-given names or fresh (synthetic) names.
94 /// User wrote nothing (e.g., the lifetime in `&u32`).
97 /// Implicit lifetime in a context like `dyn Foo`. This is
98 /// distinguished from implicit lifetimes elsewhere because the
99 /// lifetime that they default to must appear elsewhere within the
100 /// enclosing type. This means that, in an `impl Trait` context, we
101 /// don't have to create a parameter for them. That is, `impl
102 /// Trait<Item = &u32>` expands to an opaque type like `type
103 /// Foo<'a> = impl Trait<Item = &'a u32>`, but `impl Trait<item =
104 /// dyn Bar>` expands to `type Foo = impl Trait<Item = dyn Bar +
105 /// 'static>`. The latter uses `ImplicitObjectLifetimeDefault` so
106 /// that surrounding code knows not to create a lifetime
108 ImplicitObjectLifetimeDefault,
110 /// Indicates an error during lowering (usually `'_` in wrong place)
111 /// that was already reported.
114 /// User wrote specifies `'_`.
117 /// User wrote `'static`.
122 pub fn ident(&self) -> Ident {
124 LifetimeName::ImplicitObjectLifetimeDefault
125 | LifetimeName::Implicit
126 | LifetimeName::Error => Ident::invalid(),
127 LifetimeName::Underscore => Ident::with_dummy_span(kw::UnderscoreLifetime),
128 LifetimeName::Static => Ident::with_dummy_span(kw::StaticLifetime),
129 LifetimeName::Param(param_name) => param_name.ident(),
133 pub fn is_elided(&self) -> bool {
135 LifetimeName::ImplicitObjectLifetimeDefault
136 | LifetimeName::Implicit
137 | LifetimeName::Underscore => true,
139 // It might seem surprising that `Fresh(_)` counts as
140 // *not* elided -- but this is because, as far as the code
141 // in the compiler is concerned -- `Fresh(_)` variants act
142 // equivalently to "some fresh name". They correspond to
143 // early-bound regions on an impl, in other words.
144 LifetimeName::Error | LifetimeName::Param(_) | LifetimeName::Static => false,
148 fn is_static(&self) -> bool {
149 self == &LifetimeName::Static
152 pub fn normalize_to_macros_2_0(&self) -> LifetimeName {
154 LifetimeName::Param(param_name) => {
155 LifetimeName::Param(param_name.normalize_to_macros_2_0())
157 lifetime_name => lifetime_name,
162 impl fmt::Display for Lifetime {
163 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
164 self.name.ident().fmt(f)
168 impl fmt::Debug for Lifetime {
169 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
170 write!(f, "lifetime({}: {})", self.hir_id, self.name.ident())
175 pub fn is_elided(&self) -> bool {
176 self.name.is_elided()
179 pub fn is_static(&self) -> bool {
180 self.name.is_static()
184 /// A `Path` is essentially Rust's notion of a name; for instance,
185 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
186 /// along with a bunch of supporting information.
187 #[derive(Debug, HashStable_Generic)]
188 pub struct Path<'hir> {
190 /// The resolution for the path.
192 /// The segments in the path: the things separated by `::`.
193 pub segments: &'hir [PathSegment<'hir>],
197 pub fn is_global(&self) -> bool {
198 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
202 /// A segment of a path: an identifier, an optional lifetime, and a set of
204 #[derive(Debug, HashStable_Generic)]
205 pub struct PathSegment<'hir> {
206 /// The identifier portion of this path segment.
207 #[stable_hasher(project(name))]
209 // `id` and `res` are optional. We currently only use these in save-analysis,
210 // any path segments without these will not have save-analysis info and
211 // therefore will not have 'jump to def' in IDEs, but otherwise will not be
212 // affected. (In general, we don't bother to get the defs for synthesized
213 // segments, only for segments which have come from the AST).
214 pub hir_id: Option<HirId>,
215 pub res: Option<Res>,
217 /// Type/lifetime parameters attached to this path. They come in
218 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
219 /// this is more than just simple syntactic sugar; the use of
220 /// parens affects the region binding rules, so we preserve the
222 pub args: Option<&'hir GenericArgs<'hir>>,
224 /// Whether to infer remaining type parameters, if any.
225 /// This only applies to expression and pattern paths, and
226 /// out of those only the segments with no type parameters
227 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
228 pub infer_args: bool,
231 impl<'hir> PathSegment<'hir> {
232 /// Converts an identifier to the corresponding segment.
233 pub fn from_ident(ident: Ident) -> PathSegment<'hir> {
234 PathSegment { ident, hir_id: None, res: None, infer_args: true, args: None }
237 pub fn invalid() -> Self {
238 Self::from_ident(Ident::invalid())
241 pub fn args(&self) -> &GenericArgs<'hir> {
242 if let Some(ref args) = self.args {
245 const DUMMY: &GenericArgs<'_> = &GenericArgs::none();
251 #[derive(Encodable, Debug, HashStable_Generic)]
252 pub struct ConstArg {
253 pub value: AnonConst,
257 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
265 pub fn is_type(self) -> bool {
266 matches!(self, InferKind::Type)
270 #[derive(Encodable, Debug, HashStable_Generic)]
271 pub struct InferArg {
278 pub fn to_ty(&self) -> Ty<'_> {
279 Ty { kind: TyKind::Infer, span: self.span, hir_id: self.hir_id }
283 #[derive(Debug, HashStable_Generic)]
284 pub enum GenericArg<'hir> {
291 impl GenericArg<'_> {
292 pub fn span(&self) -> Span {
294 GenericArg::Lifetime(l) => l.span,
295 GenericArg::Type(t) => t.span,
296 GenericArg::Const(c) => c.span,
297 GenericArg::Infer(i) => i.span,
301 pub fn id(&self) -> HirId {
303 GenericArg::Lifetime(l) => l.hir_id,
304 GenericArg::Type(t) => t.hir_id,
305 GenericArg::Const(c) => c.value.hir_id,
306 GenericArg::Infer(i) => i.hir_id,
310 pub fn is_const(&self) -> bool {
311 matches!(self, GenericArg::Const(_))
314 pub fn is_synthetic(&self) -> bool {
315 matches!(self, GenericArg::Lifetime(lifetime) if lifetime.name.ident() == Ident::invalid())
318 pub fn descr(&self) -> &'static str {
320 GenericArg::Lifetime(_) => "lifetime",
321 GenericArg::Type(_) => "type",
322 GenericArg::Const(_) => "constant",
323 GenericArg::Infer(_) => "inferred",
327 pub fn to_ord(&self, feats: &rustc_feature::Features) -> ast::ParamKindOrd {
329 GenericArg::Lifetime(_) => ast::ParamKindOrd::Lifetime,
330 GenericArg::Type(_) => ast::ParamKindOrd::Type,
331 GenericArg::Const(_) => {
332 ast::ParamKindOrd::Const { unordered: feats.unordered_const_ty_params() }
334 GenericArg::Infer(_) => ast::ParamKindOrd::Infer,
339 #[derive(Debug, HashStable_Generic)]
340 pub struct GenericArgs<'hir> {
341 /// The generic arguments for this path segment.
342 pub args: &'hir [GenericArg<'hir>],
343 /// Bindings (equality constraints) on associated types, if present.
344 /// E.g., `Foo<A = Bar>`.
345 pub bindings: &'hir [TypeBinding<'hir>],
346 /// Were arguments written in parenthesized form `Fn(T) -> U`?
347 /// This is required mostly for pretty-printing and diagnostics,
348 /// but also for changing lifetime elision rules to be "function-like".
349 pub parenthesized: bool,
350 /// The span encompassing arguments and the surrounding brackets `<>` or `()`
351 /// Foo<A, B, AssocTy = D> Fn(T, U, V) -> W
352 /// ^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^
353 /// Note that this may be:
354 /// - empty, if there are no generic brackets (but there may be hidden lifetimes)
355 /// - dummy, if this was generated while desugaring
359 impl GenericArgs<'_> {
360 pub const fn none() -> Self {
361 Self { args: &[], bindings: &[], parenthesized: false, span_ext: DUMMY_SP }
364 pub fn inputs(&self) -> &[Ty<'_>] {
365 if self.parenthesized {
366 for arg in self.args {
368 GenericArg::Lifetime(_) => {}
369 GenericArg::Type(ref ty) => {
370 if let TyKind::Tup(ref tys) = ty.kind {
375 GenericArg::Const(_) => {}
376 GenericArg::Infer(_) => {}
380 panic!("GenericArgs::inputs: not a `Fn(T) -> U`");
384 pub fn has_type_params(&self) -> bool {
385 self.args.iter().any(|arg| matches!(arg, GenericArg::Type(_)))
389 pub fn num_type_params(&self) -> usize {
390 self.args.iter().filter(|arg| matches!(arg, GenericArg::Type(_))).count()
394 pub fn num_lifetime_params(&self) -> usize {
395 self.args.iter().filter(|arg| matches!(arg, GenericArg::Lifetime(_))).count()
399 pub fn has_lifetime_params(&self) -> bool {
400 self.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)))
404 pub fn num_generic_params(&self) -> usize {
405 self.args.iter().filter(|arg| !matches!(arg, GenericArg::Lifetime(_))).count()
408 /// The span encompassing the text inside the surrounding brackets.
409 /// It will also include bindings if they aren't in the form `-> Ret`
410 /// Returns `None` if the span is empty (e.g. no brackets) or dummy
411 pub fn span(&self) -> Option<Span> {
412 let span_ext = self.span_ext()?;
413 Some(span_ext.with_lo(span_ext.lo() + BytePos(1)).with_hi(span_ext.hi() - BytePos(1)))
416 /// Returns span encompassing arguments and their surrounding `<>` or `()`
417 pub fn span_ext(&self) -> Option<Span> {
418 Some(self.span_ext).filter(|span| !span.is_empty())
421 pub fn is_empty(&self) -> bool {
426 /// A modifier on a bound, currently this is only used for `?Sized`, where the
427 /// modifier is `Maybe`. Negative bounds should also be handled here.
428 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
429 #[derive(HashStable_Generic)]
430 pub enum TraitBoundModifier {
436 /// The AST represents all type param bounds as types.
437 /// `typeck::collect::compute_bounds` matches these against
438 /// the "special" built-in traits (see `middle::lang_items`) and
439 /// detects `Copy`, `Send` and `Sync`.
440 #[derive(Clone, Debug, HashStable_Generic)]
441 pub enum GenericBound<'hir> {
442 Trait(PolyTraitRef<'hir>, TraitBoundModifier),
443 // FIXME(davidtwco): Introduce `PolyTraitRef::LangItem`
444 LangItemTrait(LangItem, Span, HirId, &'hir GenericArgs<'hir>),
449 impl GenericBound<'_> {
450 pub fn trait_ref(&self) -> Option<&TraitRef<'_>> {
452 GenericBound::Trait(data, _) => Some(&data.trait_ref),
457 pub fn span(&self) -> Span {
459 GenericBound::Trait(t, ..) => t.span,
460 GenericBound::LangItemTrait(_, span, ..) => *span,
461 GenericBound::Outlives(l) => l.span,
462 GenericBound::Unsized(span) => *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 // Indicates that the lifetime definition was synthetically added
476 // as a result of an in-band lifetime usage (e.g., in
477 // `fn foo(x: &'a u8) -> &'a u8 { x }`).
480 // Indication that the lifetime was elided (e.g., in both cases in
481 // `fn foo(x: &u8) -> &'_ u8 { x }`).
484 // Indication that the lifetime name was somehow in error.
488 #[derive(Debug, HashStable_Generic)]
489 pub enum GenericParamKind<'hir> {
490 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
492 kind: LifetimeParamKind,
495 default: Option<&'hir Ty<'hir>>,
496 synthetic: Option<SyntheticTyParamKind>,
500 /// Optional default value for the const generic param
501 default: Option<AnonConst>,
505 #[derive(Debug, HashStable_Generic)]
506 pub struct GenericParam<'hir> {
509 pub bounds: GenericBounds<'hir>,
511 pub pure_wrt_drop: bool,
512 pub kind: GenericParamKind<'hir>,
515 impl GenericParam<'hir> {
516 pub fn bounds_span(&self) -> Option<Span> {
517 self.bounds.iter().fold(None, |span, bound| {
518 let span = span.map(|s| s.to(bound.span())).unwrap_or_else(|| bound.span());
526 pub struct GenericParamCount {
527 pub lifetimes: usize,
533 /// Represents lifetimes and type parameters attached to a declaration
534 /// of a function, enum, trait, etc.
535 #[derive(Debug, HashStable_Generic)]
536 pub struct Generics<'hir> {
537 pub params: &'hir [GenericParam<'hir>],
538 pub where_clause: WhereClause<'hir>,
542 impl Generics<'hir> {
543 pub const fn empty() -> Generics<'hir> {
546 where_clause: WhereClause { predicates: &[], span: DUMMY_SP },
551 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'_>> {
552 for param in self.params {
553 if name == param.name.ident().name {
560 pub fn spans(&self) -> MultiSpan {
561 if self.params.is_empty() {
564 self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
569 /// Synthetic type parameters are converted to another form during lowering; this allows
570 /// us to track the original form they had, and is useful for error messages.
571 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
572 #[derive(HashStable_Generic)]
573 pub enum SyntheticTyParamKind {
575 // Created by the `#[rustc_synthetic]` attribute.
579 /// A where-clause in a definition.
580 #[derive(Debug, HashStable_Generic)]
581 pub struct WhereClause<'hir> {
582 pub predicates: &'hir [WherePredicate<'hir>],
583 // Only valid if predicates aren't empty.
587 impl WhereClause<'_> {
588 pub fn span(&self) -> Option<Span> {
589 if self.predicates.is_empty() { None } else { Some(self.span) }
592 /// The `WhereClause` under normal circumstances points at either the predicates or the empty
593 /// space where the `where` clause should be. Only of use for diagnostic suggestions.
594 pub fn span_for_predicates_or_empty_place(&self) -> Span {
598 /// `Span` where further predicates would be suggested, accounting for trailing commas, like
599 /// in `fn foo<T>(t: T) where T: Foo,` so we don't suggest two trailing commas.
600 pub fn tail_span_for_suggestion(&self) -> Span {
601 let end = self.span_for_predicates_or_empty_place().shrink_to_hi();
602 self.predicates.last().map_or(end, |p| p.span()).shrink_to_hi().to(end)
606 /// A single predicate in a where-clause.
607 #[derive(Debug, HashStable_Generic)]
608 pub enum WherePredicate<'hir> {
609 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
610 BoundPredicate(WhereBoundPredicate<'hir>),
611 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
612 RegionPredicate(WhereRegionPredicate<'hir>),
613 /// An equality predicate (unsupported).
614 EqPredicate(WhereEqPredicate<'hir>),
617 impl WherePredicate<'_> {
618 pub fn span(&self) -> Span {
620 WherePredicate::BoundPredicate(p) => p.span,
621 WherePredicate::RegionPredicate(p) => p.span,
622 WherePredicate::EqPredicate(p) => p.span,
627 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
628 #[derive(Debug, HashStable_Generic)]
629 pub struct WhereBoundPredicate<'hir> {
631 /// Any generics from a `for` binding.
632 pub bound_generic_params: &'hir [GenericParam<'hir>],
633 /// The type being bounded.
634 pub bounded_ty: &'hir Ty<'hir>,
635 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
636 pub bounds: GenericBounds<'hir>,
639 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
640 #[derive(Debug, HashStable_Generic)]
641 pub struct WhereRegionPredicate<'hir> {
643 pub lifetime: Lifetime,
644 pub bounds: GenericBounds<'hir>,
647 /// An equality predicate (e.g., `T = int`); currently unsupported.
648 #[derive(Debug, HashStable_Generic)]
649 pub struct WhereEqPredicate<'hir> {
652 pub lhs_ty: &'hir Ty<'hir>,
653 pub rhs_ty: &'hir Ty<'hir>,
656 #[derive(Default, Encodable, Debug, HashStable_Generic)]
657 pub struct ModuleItems {
658 // Use BTreeSets here so items are in the same order as in the
659 // list of all items in Crate
660 pub items: BTreeSet<ItemId>,
661 pub trait_items: BTreeSet<TraitItemId>,
662 pub impl_items: BTreeSet<ImplItemId>,
663 pub foreign_items: BTreeSet<ForeignItemId>,
666 /// The top-level data structure that stores the entire contents of
667 /// the crate currently being compiled.
669 /// For more details, see the [rustc dev guide].
671 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
673 pub struct Crate<'hir> {
674 // Attributes from non-exported macros, kept only for collecting the library feature list.
675 pub non_exported_macro_attrs: &'hir [Attribute],
677 pub owners: IndexVec<LocalDefId, Option<OwnerNode<'hir>>>,
678 pub bodies: BTreeMap<BodyId, Body<'hir>>,
679 pub trait_impls: BTreeMap<DefId, Vec<LocalDefId>>,
681 /// A list of the body ids written out in the order in which they
682 /// appear in the crate. If you're going to process all the bodies
683 /// in the crate, you should iterate over this list rather than the keys
685 pub body_ids: Vec<BodyId>,
687 /// A list of modules written out in the order in which they
688 /// appear in the crate. This includes the main crate module.
689 pub modules: BTreeMap<LocalDefId, ModuleItems>,
690 /// A list of proc macro HirIds, written out in the order in which
691 /// they are declared in the static array generated by proc_macro_harness.
692 pub proc_macros: Vec<HirId>,
694 /// Map indicating what traits are in scope for places where this
695 /// is relevant; generated by resolve.
696 pub trait_map: FxHashMap<LocalDefId, FxHashMap<ItemLocalId, Box<[TraitCandidate]>>>,
698 /// Collected attributes from HIR nodes.
699 pub attrs: BTreeMap<HirId, &'hir [Attribute]>,
703 pub fn module(&self) -> &'hir Mod<'hir> {
704 if let Some(OwnerNode::Crate(m)) = self.owners[CRATE_DEF_ID] { m } else { panic!() }
707 pub fn item(&self, id: ItemId) -> &'hir Item<'hir> {
708 self.owners[id.def_id].as_ref().unwrap().expect_item()
711 pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> {
712 self.owners[id.def_id].as_ref().unwrap().expect_trait_item()
715 pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> {
716 self.owners[id.def_id].as_ref().unwrap().expect_impl_item()
719 pub fn foreign_item(&self, id: ForeignItemId) -> &'hir ForeignItem<'hir> {
720 self.owners[id.def_id].as_ref().unwrap().expect_foreign_item()
723 pub fn body(&self, id: BodyId) -> &Body<'hir> {
729 /// Visits all items in the crate in some deterministic (but
730 /// unspecified) order. If you just need to process every item,
731 /// but don't care about nesting, this method is the best choice.
733 /// If you do care about nesting -- usually because your algorithm
734 /// follows lexical scoping rules -- then you want a different
735 /// approach. You should override `visit_nested_item` in your
736 /// visitor and then call `intravisit::walk_crate` instead.
737 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
739 V: itemlikevisit::ItemLikeVisitor<'hir>,
741 for owner in self.owners.iter().filter_map(Option::as_ref) {
743 OwnerNode::Item(item) => visitor.visit_item(item),
744 OwnerNode::ForeignItem(item) => visitor.visit_foreign_item(item),
745 OwnerNode::ImplItem(item) => visitor.visit_impl_item(item),
746 OwnerNode::TraitItem(item) => visitor.visit_trait_item(item),
747 OwnerNode::MacroDef(_) | OwnerNode::Crate(_) => {}
752 /// A parallel version of `visit_all_item_likes`.
753 pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
755 V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send,
757 par_for_each_in(&self.owners.raw, |owner| match owner {
758 Some(OwnerNode::Item(item)) => visitor.visit_item(item),
759 Some(OwnerNode::ForeignItem(item)) => visitor.visit_foreign_item(item),
760 Some(OwnerNode::ImplItem(item)) => visitor.visit_impl_item(item),
761 Some(OwnerNode::TraitItem(item)) => visitor.visit_trait_item(item),
762 Some(OwnerNode::MacroDef(_)) | Some(OwnerNode::Crate(_)) | None => {}
766 pub fn items<'hir>(&'hir self) -> impl Iterator<Item = &'hir Item<'hir>> + 'hir {
767 self.owners.iter().filter_map(|owner| match owner {
768 Some(OwnerNode::Item(item)) => Some(*item),
773 pub fn exported_macros<'hir>(&'hir self) -> impl Iterator<Item = &'hir MacroDef<'hir>> + 'hir {
774 self.owners.iter().filter_map(|owner| match owner {
775 Some(OwnerNode::MacroDef(macro_def)) => Some(*macro_def),
781 /// A macro definition, in this crate or imported from another.
783 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
785 pub struct MacroDef<'hir> {
787 pub vis: Visibility<'hir>,
788 pub def_id: LocalDefId,
790 pub ast: ast::MacroDef,
795 pub fn hir_id(&self) -> HirId {
796 HirId::make_owner(self.def_id)
800 /// A block of statements `{ .. }`, which may have a label (in this case the
801 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
802 /// the `rules` being anything but `DefaultBlock`.
803 #[derive(Debug, HashStable_Generic)]
804 pub struct Block<'hir> {
805 /// Statements in a block.
806 pub stmts: &'hir [Stmt<'hir>],
807 /// An expression at the end of the block
808 /// without a semicolon, if any.
809 pub expr: Option<&'hir Expr<'hir>>,
810 #[stable_hasher(ignore)]
812 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
813 pub rules: BlockCheckMode,
815 /// If true, then there may exist `break 'a` values that aim to
816 /// break out of this block early.
817 /// Used by `'label: {}` blocks and by `try {}` blocks.
818 pub targeted_by_break: bool,
821 #[derive(Debug, HashStable_Generic)]
822 pub struct Pat<'hir> {
823 #[stable_hasher(ignore)]
825 pub kind: PatKind<'hir>,
827 // Whether to use default binding modes.
828 // At present, this is false only for destructuring assignment.
829 pub default_binding_modes: bool,
832 impl<'hir> Pat<'hir> {
833 // FIXME(#19596) this is a workaround, but there should be a better way
834 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) -> bool {
841 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
842 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
843 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
844 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
845 Slice(before, slice, after) => {
846 before.iter().chain(slice).chain(after.iter()).all(|p| p.walk_short_(it))
851 /// Walk the pattern in left-to-right order,
852 /// short circuiting (with `.all(..)`) if `false` is returned.
854 /// Note that when visiting e.g. `Tuple(ps)`,
855 /// if visiting `ps[0]` returns `false`,
856 /// then `ps[1]` will not be visited.
857 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) -> bool {
858 self.walk_short_(&mut it)
861 // FIXME(#19596) this is a workaround, but there should be a better way
862 fn walk_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) {
869 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
870 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
871 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
872 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
873 Slice(before, slice, after) => {
874 before.iter().chain(slice).chain(after.iter()).for_each(|p| p.walk_(it))
879 /// Walk the pattern in left-to-right order.
881 /// If `it(pat)` returns `false`, the children are not visited.
882 pub fn walk(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) {
886 /// Walk the pattern in left-to-right order.
888 /// If you always want to recurse, prefer this method over `walk`.
889 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
897 /// A single field in a struct pattern.
899 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
900 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
901 /// except `is_shorthand` is true.
902 #[derive(Debug, HashStable_Generic)]
903 pub struct PatField<'hir> {
904 #[stable_hasher(ignore)]
906 /// The identifier for the field.
907 #[stable_hasher(project(name))]
909 /// The pattern the field is destructured to.
910 pub pat: &'hir Pat<'hir>,
911 pub is_shorthand: bool,
915 /// Explicit binding annotations given in the HIR for a binding. Note
916 /// that this is not the final binding *mode* that we infer after type
918 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
919 pub enum BindingAnnotation {
920 /// No binding annotation given: this means that the final binding mode
921 /// will depend on whether we have skipped through a `&` reference
922 /// when matching. For example, the `x` in `Some(x)` will have binding
923 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
924 /// ultimately be inferred to be by-reference.
926 /// Note that implicit reference skipping is not implemented yet (#42640).
929 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
932 /// Annotated as `ref`, like `ref x`
935 /// Annotated as `ref mut x`.
939 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
945 impl fmt::Display for RangeEnd {
946 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
947 f.write_str(match self {
948 RangeEnd::Included => "..=",
949 RangeEnd::Excluded => "..",
954 #[derive(Debug, HashStable_Generic)]
955 pub enum PatKind<'hir> {
956 /// Represents a wildcard pattern (i.e., `_`).
959 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
960 /// The `HirId` is the canonical ID for the variable being bound,
961 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
962 /// which is the pattern ID of the first `x`.
963 Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
965 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
966 /// The `bool` is `true` in the presence of a `..`.
967 Struct(QPath<'hir>, &'hir [PatField<'hir>], bool),
969 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
970 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
971 /// `0 <= position <= subpats.len()`
972 TupleStruct(QPath<'hir>, &'hir [Pat<'hir>], Option<usize>),
974 /// An or-pattern `A | B | C`.
975 /// Invariant: `pats.len() >= 2`.
976 Or(&'hir [Pat<'hir>]),
978 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
981 /// A tuple pattern (e.g., `(a, b)`).
982 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
983 /// `0 <= position <= subpats.len()`
984 Tuple(&'hir [Pat<'hir>], Option<usize>),
987 Box(&'hir Pat<'hir>),
989 /// A reference pattern (e.g., `&mut (a, b)`).
990 Ref(&'hir Pat<'hir>, Mutability),
993 Lit(&'hir Expr<'hir>),
995 /// A range pattern (e.g., `1..=2` or `1..2`).
996 Range(Option<&'hir Expr<'hir>>, Option<&'hir Expr<'hir>>, RangeEnd),
998 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
1000 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
1001 /// If `slice` exists, then `after` can be non-empty.
1003 /// The representation for e.g., `[a, b, .., c, d]` is:
1005 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
1007 Slice(&'hir [Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [Pat<'hir>]),
1010 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1011 pub enum BinOpKind {
1012 /// The `+` operator (addition).
1014 /// The `-` operator (subtraction).
1016 /// The `*` operator (multiplication).
1018 /// The `/` operator (division).
1020 /// The `%` operator (modulus).
1022 /// The `&&` operator (logical and).
1024 /// The `||` operator (logical or).
1026 /// The `^` operator (bitwise xor).
1028 /// The `&` operator (bitwise and).
1030 /// The `|` operator (bitwise or).
1032 /// The `<<` operator (shift left).
1034 /// The `>>` operator (shift right).
1036 /// The `==` operator (equality).
1038 /// The `<` operator (less than).
1040 /// The `<=` operator (less than or equal to).
1042 /// The `!=` operator (not equal to).
1044 /// The `>=` operator (greater than or equal to).
1046 /// The `>` operator (greater than).
1051 pub fn as_str(self) -> &'static str {
1053 BinOpKind::Add => "+",
1054 BinOpKind::Sub => "-",
1055 BinOpKind::Mul => "*",
1056 BinOpKind::Div => "/",
1057 BinOpKind::Rem => "%",
1058 BinOpKind::And => "&&",
1059 BinOpKind::Or => "||",
1060 BinOpKind::BitXor => "^",
1061 BinOpKind::BitAnd => "&",
1062 BinOpKind::BitOr => "|",
1063 BinOpKind::Shl => "<<",
1064 BinOpKind::Shr => ">>",
1065 BinOpKind::Eq => "==",
1066 BinOpKind::Lt => "<",
1067 BinOpKind::Le => "<=",
1068 BinOpKind::Ne => "!=",
1069 BinOpKind::Ge => ">=",
1070 BinOpKind::Gt => ">",
1074 pub fn is_lazy(self) -> bool {
1075 matches!(self, BinOpKind::And | BinOpKind::Or)
1078 pub fn is_shift(self) -> bool {
1079 matches!(self, BinOpKind::Shl | BinOpKind::Shr)
1082 pub fn is_comparison(self) -> bool {
1089 | BinOpKind::Ge => true,
1101 | BinOpKind::Shr => false,
1105 /// Returns `true` if the binary operator takes its arguments by value.
1106 pub fn is_by_value(self) -> bool {
1107 !self.is_comparison()
1111 impl Into<ast::BinOpKind> for BinOpKind {
1112 fn into(self) -> ast::BinOpKind {
1114 BinOpKind::Add => ast::BinOpKind::Add,
1115 BinOpKind::Sub => ast::BinOpKind::Sub,
1116 BinOpKind::Mul => ast::BinOpKind::Mul,
1117 BinOpKind::Div => ast::BinOpKind::Div,
1118 BinOpKind::Rem => ast::BinOpKind::Rem,
1119 BinOpKind::And => ast::BinOpKind::And,
1120 BinOpKind::Or => ast::BinOpKind::Or,
1121 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1122 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1123 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1124 BinOpKind::Shl => ast::BinOpKind::Shl,
1125 BinOpKind::Shr => ast::BinOpKind::Shr,
1126 BinOpKind::Eq => ast::BinOpKind::Eq,
1127 BinOpKind::Lt => ast::BinOpKind::Lt,
1128 BinOpKind::Le => ast::BinOpKind::Le,
1129 BinOpKind::Ne => ast::BinOpKind::Ne,
1130 BinOpKind::Ge => ast::BinOpKind::Ge,
1131 BinOpKind::Gt => ast::BinOpKind::Gt,
1136 pub type BinOp = Spanned<BinOpKind>;
1138 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1140 /// The `*` operator (deferencing).
1142 /// The `!` operator (logical negation).
1144 /// The `-` operator (negation).
1149 pub fn as_str(self) -> &'static str {
1157 /// Returns `true` if the unary operator takes its argument by value.
1158 pub fn is_by_value(self) -> bool {
1159 matches!(self, Self::Neg | Self::Not)
1164 #[derive(Debug, HashStable_Generic)]
1165 pub struct Stmt<'hir> {
1167 pub kind: StmtKind<'hir>,
1171 /// The contents of a statement.
1172 #[derive(Debug, HashStable_Generic)]
1173 pub enum StmtKind<'hir> {
1174 /// A local (`let`) binding.
1175 Local(&'hir Local<'hir>),
1177 /// An item binding.
1180 /// An expression without a trailing semi-colon (must have unit type).
1181 Expr(&'hir Expr<'hir>),
1183 /// An expression with a trailing semi-colon (may have any type).
1184 Semi(&'hir Expr<'hir>),
1187 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1188 #[derive(Debug, HashStable_Generic)]
1189 pub struct Local<'hir> {
1190 pub pat: &'hir Pat<'hir>,
1191 /// Type annotation, if any (otherwise the type will be inferred).
1192 pub ty: Option<&'hir Ty<'hir>>,
1193 /// Initializer expression to set the value, if any.
1194 pub init: Option<&'hir Expr<'hir>>,
1197 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1198 /// desugaring. Otherwise will be `Normal`.
1199 pub source: LocalSource,
1202 /// Represents a single arm of a `match` expression, e.g.
1203 /// `<pat> (if <guard>) => <body>`.
1204 #[derive(Debug, HashStable_Generic)]
1205 pub struct Arm<'hir> {
1206 #[stable_hasher(ignore)]
1209 /// If this pattern and the optional guard matches, then `body` is evaluated.
1210 pub pat: &'hir Pat<'hir>,
1211 /// Optional guard clause.
1212 pub guard: Option<Guard<'hir>>,
1213 /// The expression the arm evaluates to if this arm matches.
1214 pub body: &'hir Expr<'hir>,
1217 #[derive(Debug, HashStable_Generic)]
1218 pub enum Guard<'hir> {
1219 If(&'hir Expr<'hir>),
1220 IfLet(&'hir Pat<'hir>, &'hir Expr<'hir>),
1223 #[derive(Debug, HashStable_Generic)]
1224 pub struct ExprField<'hir> {
1225 #[stable_hasher(ignore)]
1228 pub expr: &'hir Expr<'hir>,
1230 pub is_shorthand: bool,
1233 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1234 pub enum BlockCheckMode {
1236 UnsafeBlock(UnsafeSource),
1239 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1240 pub enum UnsafeSource {
1245 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Hash, Debug)]
1250 /// The body of a function, closure, or constant value. In the case of
1251 /// a function, the body contains not only the function body itself
1252 /// (which is an expression), but also the argument patterns, since
1253 /// those are something that the caller doesn't really care about.
1258 /// fn foo((x, y): (u32, u32)) -> u32 {
1263 /// Here, the `Body` associated with `foo()` would contain:
1265 /// - an `params` array containing the `(x, y)` pattern
1266 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1267 /// - `generator_kind` would be `None`
1269 /// All bodies have an **owner**, which can be accessed via the HIR
1270 /// map using `body_owner_def_id()`.
1272 pub struct Body<'hir> {
1273 pub params: &'hir [Param<'hir>],
1274 pub value: Expr<'hir>,
1275 pub generator_kind: Option<GeneratorKind>,
1279 pub fn id(&self) -> BodyId {
1280 BodyId { hir_id: self.value.hir_id }
1283 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1288 /// The type of source expression that caused this generator to be created.
1301 pub enum GeneratorKind {
1302 /// An explicit `async` block or the body of an async function.
1303 Async(AsyncGeneratorKind),
1305 /// A generator literal created via a `yield` inside a closure.
1309 impl fmt::Display for GeneratorKind {
1310 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1312 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1313 GeneratorKind::Gen => f.write_str("generator"),
1318 impl GeneratorKind {
1319 pub fn descr(&self) -> &'static str {
1321 GeneratorKind::Async(ask) => ask.descr(),
1322 GeneratorKind::Gen => "generator",
1327 /// In the case of a generator created as part of an async construct,
1328 /// which kind of async construct caused it to be created?
1330 /// This helps error messages but is also used to drive coercions in
1331 /// type-checking (see #60424).
1344 pub enum AsyncGeneratorKind {
1345 /// An explicit `async` block written by the user.
1348 /// An explicit `async` block written by the user.
1351 /// The `async` block generated as the body of an async function.
1355 impl fmt::Display for AsyncGeneratorKind {
1356 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1357 f.write_str(match self {
1358 AsyncGeneratorKind::Block => "`async` block",
1359 AsyncGeneratorKind::Closure => "`async` closure body",
1360 AsyncGeneratorKind::Fn => "`async fn` body",
1365 impl AsyncGeneratorKind {
1366 pub fn descr(&self) -> &'static str {
1368 AsyncGeneratorKind::Block => "`async` block",
1369 AsyncGeneratorKind::Closure => "`async` closure body",
1370 AsyncGeneratorKind::Fn => "`async fn` body",
1375 #[derive(Copy, Clone, Debug)]
1376 pub enum BodyOwnerKind {
1377 /// Functions and methods.
1383 /// Constants and associated constants.
1386 /// Initializer of a `static` item.
1390 impl BodyOwnerKind {
1391 pub fn is_fn_or_closure(self) -> bool {
1393 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1394 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1399 /// The kind of an item that requires const-checking.
1400 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1401 pub enum ConstContext {
1405 /// A `static` or `static mut`.
1408 /// A `const`, associated `const`, or other const context.
1410 /// Other contexts include:
1411 /// - Array length expressions
1412 /// - Enum discriminants
1413 /// - Const generics
1415 /// For the most part, other contexts are treated just like a regular `const`, so they are
1416 /// lumped into the same category.
1421 /// A description of this const context that can appear between backticks in an error message.
1423 /// E.g. `const` or `static mut`.
1424 pub fn keyword_name(self) -> &'static str {
1426 Self::Const => "const",
1427 Self::Static(Mutability::Not) => "static",
1428 Self::Static(Mutability::Mut) => "static mut",
1429 Self::ConstFn => "const fn",
1434 /// A colloquial, trivially pluralizable description of this const context for use in error
1436 impl fmt::Display for ConstContext {
1437 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1439 Self::Const => write!(f, "constant"),
1440 Self::Static(_) => write!(f, "static"),
1441 Self::ConstFn => write!(f, "constant function"),
1447 pub type Lit = Spanned<LitKind>;
1449 /// A constant (expression) that's not an item or associated item,
1450 /// but needs its own `DefId` for type-checking, const-eval, etc.
1451 /// These are usually found nested inside types (e.g., array lengths)
1452 /// or expressions (e.g., repeat counts), and also used to define
1453 /// explicit discriminant values for enum variants.
1455 /// You can check if this anon const is a default in a const param
1456 /// `const N: usize = { ... }` with `tcx.hir().opt_const_param_default_param_hir_id(..)`
1457 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1458 pub struct AnonConst {
1465 pub struct Expr<'hir> {
1467 pub kind: ExprKind<'hir>,
1472 pub fn precedence(&self) -> ExprPrecedence {
1474 ExprKind::Box(_) => ExprPrecedence::Box,
1475 ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1476 ExprKind::Array(_) => ExprPrecedence::Array,
1477 ExprKind::Call(..) => ExprPrecedence::Call,
1478 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1479 ExprKind::Tup(_) => ExprPrecedence::Tup,
1480 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1481 ExprKind::Unary(..) => ExprPrecedence::Unary,
1482 ExprKind::Lit(_) => ExprPrecedence::Lit,
1483 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1484 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1485 ExprKind::If(..) => ExprPrecedence::If,
1486 ExprKind::Loop(..) => ExprPrecedence::Loop,
1487 ExprKind::Match(..) => ExprPrecedence::Match,
1488 ExprKind::Closure(..) => ExprPrecedence::Closure,
1489 ExprKind::Block(..) => ExprPrecedence::Block,
1490 ExprKind::Assign(..) => ExprPrecedence::Assign,
1491 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1492 ExprKind::Field(..) => ExprPrecedence::Field,
1493 ExprKind::Index(..) => ExprPrecedence::Index,
1494 ExprKind::Path(..) => ExprPrecedence::Path,
1495 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1496 ExprKind::Break(..) => ExprPrecedence::Break,
1497 ExprKind::Continue(..) => ExprPrecedence::Continue,
1498 ExprKind::Ret(..) => ExprPrecedence::Ret,
1499 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1500 ExprKind::LlvmInlineAsm(..) => ExprPrecedence::InlineAsm,
1501 ExprKind::Struct(..) => ExprPrecedence::Struct,
1502 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1503 ExprKind::Yield(..) => ExprPrecedence::Yield,
1504 ExprKind::Err => ExprPrecedence::Err,
1508 // Whether this looks like a place expr, without checking for deref
1510 // This will return `true` in some potentially surprising cases such as
1511 // `CONSTANT.field`.
1512 pub fn is_syntactic_place_expr(&self) -> bool {
1513 self.is_place_expr(|_| true)
1516 /// Whether this is a place expression.
1518 /// `allow_projections_from` should return `true` if indexing a field or index expression based
1519 /// on the given expression should be considered a place expression.
1520 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1522 ExprKind::Path(QPath::Resolved(_, ref path)) => {
1523 matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static, _) | Res::Err)
1526 // Type ascription inherits its place expression kind from its
1528 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1529 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1531 ExprKind::Unary(UnOp::Deref, _) => true,
1533 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1534 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1537 // Lang item paths cannot currently be local variables or statics.
1538 ExprKind::Path(QPath::LangItem(..)) => false,
1540 // Partially qualified paths in expressions can only legally
1541 // refer to associated items which are always rvalues.
1542 ExprKind::Path(QPath::TypeRelative(..))
1543 | ExprKind::Call(..)
1544 | ExprKind::MethodCall(..)
1545 | ExprKind::Struct(..)
1548 | ExprKind::Match(..)
1549 | ExprKind::Closure(..)
1550 | ExprKind::Block(..)
1551 | ExprKind::Repeat(..)
1552 | ExprKind::Array(..)
1553 | ExprKind::Break(..)
1554 | ExprKind::Continue(..)
1556 | ExprKind::Loop(..)
1557 | ExprKind::Assign(..)
1558 | ExprKind::InlineAsm(..)
1559 | ExprKind::LlvmInlineAsm(..)
1560 | ExprKind::AssignOp(..)
1562 | ExprKind::ConstBlock(..)
1563 | ExprKind::Unary(..)
1565 | ExprKind::AddrOf(..)
1566 | ExprKind::Binary(..)
1567 | ExprKind::Yield(..)
1568 | ExprKind::Cast(..)
1569 | ExprKind::DropTemps(..)
1570 | ExprKind::Err => false,
1574 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1575 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1576 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1577 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1578 /// beyond remembering to call this function before doing analysis on it.
1579 pub fn peel_drop_temps(&self) -> &Self {
1580 let mut expr = self;
1581 while let ExprKind::DropTemps(inner) = &expr.kind {
1587 pub fn peel_blocks(&self) -> &Self {
1588 let mut expr = self;
1589 while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind {
1595 pub fn can_have_side_effects(&self) -> bool {
1596 match self.peel_drop_temps().kind {
1597 ExprKind::Path(_) | ExprKind::Lit(_) => false,
1598 ExprKind::Type(base, _)
1599 | ExprKind::Unary(_, base)
1600 | ExprKind::Field(base, _)
1601 | ExprKind::Index(base, _)
1602 | ExprKind::AddrOf(.., base)
1603 | ExprKind::Cast(base, _) => {
1604 // This isn't exactly true for `Index` and all `Unnary`, but we are using this
1605 // method exclusively for diagnostics and there's a *cultural* pressure against
1606 // them being used only for its side-effects.
1607 base.can_have_side_effects()
1609 ExprKind::Struct(_, fields, init) => fields
1611 .map(|field| field.expr)
1612 .chain(init.into_iter())
1613 .all(|e| e.can_have_side_effects()),
1615 ExprKind::Array(args)
1616 | ExprKind::Tup(args)
1620 ExprKind::Path(QPath::Resolved(
1622 Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. },
1627 ) => args.iter().all(|arg| arg.can_have_side_effects()),
1629 | ExprKind::Match(..)
1630 | ExprKind::MethodCall(..)
1631 | ExprKind::Call(..)
1632 | ExprKind::Closure(..)
1633 | ExprKind::Block(..)
1634 | ExprKind::Repeat(..)
1635 | ExprKind::Break(..)
1636 | ExprKind::Continue(..)
1638 | ExprKind::Loop(..)
1639 | ExprKind::Assign(..)
1640 | ExprKind::InlineAsm(..)
1641 | ExprKind::LlvmInlineAsm(..)
1642 | ExprKind::AssignOp(..)
1643 | ExprKind::ConstBlock(..)
1645 | ExprKind::Binary(..)
1646 | ExprKind::Yield(..)
1647 | ExprKind::DropTemps(..)
1648 | ExprKind::Err => true,
1653 /// Checks if the specified expression is a built-in range literal.
1654 /// (See: `LoweringContext::lower_expr()`).
1655 pub fn is_range_literal(expr: &Expr<'_>) -> bool {
1657 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1658 ExprKind::Struct(ref qpath, _, _) => matches!(
1663 | LangItem::RangeFrom
1664 | LangItem::RangeFull
1665 | LangItem::RangeToInclusive,
1670 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1671 ExprKind::Call(ref func, _) => {
1672 matches!(func.kind, ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, _)))
1679 #[derive(Debug, HashStable_Generic)]
1680 pub enum ExprKind<'hir> {
1681 /// A `box x` expression.
1682 Box(&'hir Expr<'hir>),
1683 /// Allow anonymous constants from an inline `const` block
1684 ConstBlock(AnonConst),
1685 /// An array (e.g., `[a, b, c, d]`).
1686 Array(&'hir [Expr<'hir>]),
1687 /// A function call.
1689 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1690 /// and the second field is the list of arguments.
1691 /// This also represents calling the constructor of
1692 /// tuple-like ADTs such as tuple structs and enum variants.
1693 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1694 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1696 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1697 /// (within the angle brackets).
1698 /// The first element of the vector of `Expr`s is the expression that evaluates
1699 /// to the object on which the method is being called on (the receiver),
1700 /// and the remaining elements are the rest of the arguments.
1701 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1702 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1703 /// The final `Span` represents the span of the function and arguments
1704 /// (e.g. `foo::<Bar, Baz>(a, b, c, d)` in `x.foo::<Bar, Baz>(a, b, c, d)`
1706 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1707 /// the `hir_id` of the `MethodCall` node itself.
1709 /// [`type_dependent_def_id`]: ../ty/struct.TypeckResults.html#method.type_dependent_def_id
1710 MethodCall(&'hir PathSegment<'hir>, Span, &'hir [Expr<'hir>], Span),
1711 /// A tuple (e.g., `(a, b, c, d)`).
1712 Tup(&'hir [Expr<'hir>]),
1713 /// A binary operation (e.g., `a + b`, `a * b`).
1714 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1715 /// A unary operation (e.g., `!x`, `*x`).
1716 Unary(UnOp, &'hir Expr<'hir>),
1717 /// A literal (e.g., `1`, `"foo"`).
1719 /// A cast (e.g., `foo as f64`).
1720 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1721 /// A type reference (e.g., `Foo`).
1722 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1723 /// Wraps the expression in a terminating scope.
1724 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1726 /// This construct only exists to tweak the drop order in HIR lowering.
1727 /// An example of that is the desugaring of `for` loops.
1728 DropTemps(&'hir Expr<'hir>),
1729 /// An `if` block, with an optional else block.
1731 /// I.e., `if <expr> { <expr> } else { <expr> }`.
1732 If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
1733 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1735 /// I.e., `'label: loop { <block> }`.
1737 /// The `Span` is the loop header (`for x in y`/`while let pat = expr`).
1738 Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span),
1739 /// A `match` block, with a source that indicates whether or not it is
1740 /// the result of a desugaring, and if so, which kind.
1741 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1742 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1744 /// The `Span` is the argument block `|...|`.
1746 /// This may also be a generator literal or an `async block` as indicated by the
1747 /// `Option<Movability>`.
1748 Closure(CaptureBy, &'hir FnDecl<'hir>, BodyId, Span, Option<Movability>),
1749 /// A block (e.g., `'label: { ... }`).
1750 Block(&'hir Block<'hir>, Option<Label>),
1752 /// An assignment (e.g., `a = foo()`).
1753 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1754 /// An assignment with an operator.
1757 AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1758 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1759 Field(&'hir Expr<'hir>, Ident),
1760 /// An indexing operation (`foo[2]`).
1761 Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1763 /// Path to a definition, possibly containing lifetime or type parameters.
1766 /// A referencing operation (i.e., `&a` or `&mut a`).
1767 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1768 /// A `break`, with an optional label to break.
1769 Break(Destination, Option<&'hir Expr<'hir>>),
1770 /// A `continue`, with an optional label.
1771 Continue(Destination),
1772 /// A `return`, with an optional value to be returned.
1773 Ret(Option<&'hir Expr<'hir>>),
1775 /// Inline assembly (from `asm!`), with its outputs and inputs.
1776 InlineAsm(&'hir InlineAsm<'hir>),
1777 /// Inline assembly (from `llvm_asm!`), with its outputs and inputs.
1778 LlvmInlineAsm(&'hir LlvmInlineAsm<'hir>),
1780 /// A struct or struct-like variant literal expression.
1782 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1783 /// where `base` is the `Option<Expr>`.
1784 Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], Option<&'hir Expr<'hir>>),
1786 /// An array literal constructed from one repeated element.
1788 /// E.g., `[1; 5]`. The first expression is the element
1789 /// to be repeated; the second is the number of times to repeat it.
1790 Repeat(&'hir Expr<'hir>, AnonConst),
1792 /// A suspension point for generators (i.e., `yield <expr>`).
1793 Yield(&'hir Expr<'hir>, YieldSource),
1795 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1799 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1801 /// To resolve the path to a `DefId`, call [`qpath_res`].
1803 /// [`qpath_res`]: ../rustc_middle/ty/struct.TypeckResults.html#method.qpath_res
1804 #[derive(Debug, HashStable_Generic)]
1805 pub enum QPath<'hir> {
1806 /// Path to a definition, optionally "fully-qualified" with a `Self`
1807 /// type, if the path points to an associated item in a trait.
1809 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1810 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1811 /// even though they both have the same two-segment `Clone::clone` `Path`.
1812 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
1814 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1815 /// Will be resolved by type-checking to an associated item.
1817 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1818 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1819 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1820 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
1822 /// Reference to a `#[lang = "foo"]` item.
1823 LangItem(LangItem, Span),
1826 impl<'hir> QPath<'hir> {
1827 /// Returns the span of this `QPath`.
1828 pub fn span(&self) -> Span {
1830 QPath::Resolved(_, path) => path.span,
1831 QPath::TypeRelative(qself, ps) => qself.span.to(ps.ident.span),
1832 QPath::LangItem(_, span) => span,
1836 /// Returns the span of the qself of this `QPath`. For example, `()` in
1837 /// `<() as Trait>::method`.
1838 pub fn qself_span(&self) -> Span {
1840 QPath::Resolved(_, path) => path.span,
1841 QPath::TypeRelative(qself, _) => qself.span,
1842 QPath::LangItem(_, span) => span,
1846 /// Returns the span of the last segment of this `QPath`. For example, `method` in
1847 /// `<() as Trait>::method`.
1848 pub fn last_segment_span(&self) -> Span {
1850 QPath::Resolved(_, path) => path.segments.last().unwrap().ident.span,
1851 QPath::TypeRelative(_, segment) => segment.ident.span,
1852 QPath::LangItem(_, span) => span,
1857 /// Hints at the original code for a let statement.
1858 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1859 pub enum LocalSource {
1860 /// A `match _ { .. }`.
1862 /// A desugared `for _ in _ { .. }` loop.
1864 /// When lowering async functions, we create locals within the `async move` so that
1865 /// all parameters are dropped after the future is polled.
1867 /// ```ignore (pseudo-Rust)
1868 /// async fn foo(<pattern> @ x: Type) {
1870 /// let <pattern> = x;
1875 /// A desugared `<expr>.await`.
1877 /// A desugared `expr = expr`, where the LHS is a tuple, struct or array.
1878 /// The span is that of the `=` sign.
1879 AssignDesugar(Span),
1882 /// Hints at the original code for a `match _ { .. }`.
1883 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
1884 #[derive(HashStable_Generic)]
1885 pub enum MatchSource {
1886 /// A `match _ { .. }`.
1888 /// An `if let _ = _ { .. }` (optionally with `else { .. }`).
1889 IfLetDesugar { contains_else_clause: bool },
1890 /// An `if let _ = _ => { .. }` match guard.
1892 /// A `while _ { .. }` (which was desugared to a `loop { match _ { .. } }`).
1894 /// A `while let _ = _ { .. }` (which was desugared to a
1895 /// `loop { match _ { .. } }`).
1897 /// A desugared `for _ in _ { .. }` loop.
1899 /// A desugared `?` operator.
1901 /// A desugared `<expr>.await`.
1906 pub fn name(self) -> &'static str {
1910 IfLetDesugar { .. } | IfLetGuardDesugar => "if",
1911 WhileDesugar | WhileLetDesugar => "while",
1912 ForLoopDesugar => "for",
1914 AwaitDesugar => ".await",
1919 /// The loop type that yielded an `ExprKind::Loop`.
1920 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1921 pub enum LoopSource {
1922 /// A `loop { .. }` loop.
1924 /// A `while _ { .. }` loop.
1926 /// A `while let _ = _ { .. }` loop.
1928 /// A `for _ in _ { .. }` loop.
1933 pub fn name(self) -> &'static str {
1935 LoopSource::Loop => "loop",
1936 LoopSource::While | LoopSource::WhileLet => "while",
1937 LoopSource::ForLoop => "for",
1942 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1943 pub enum LoopIdError {
1945 UnlabeledCfInWhileCondition,
1949 impl fmt::Display for LoopIdError {
1950 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1951 f.write_str(match self {
1952 LoopIdError::OutsideLoopScope => "not inside loop scope",
1953 LoopIdError::UnlabeledCfInWhileCondition => {
1954 "unlabeled control flow (break or continue) in while condition"
1956 LoopIdError::UnresolvedLabel => "label not found",
1961 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1962 pub struct Destination {
1963 // This is `Some(_)` iff there is an explicit user-specified `label
1964 pub label: Option<Label>,
1966 // These errors are caught and then reported during the diagnostics pass in
1967 // librustc_passes/loops.rs
1968 pub target_id: Result<HirId, LoopIdError>,
1971 /// The yield kind that caused an `ExprKind::Yield`.
1972 #[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
1973 pub enum YieldSource {
1974 /// An `<expr>.await`.
1975 Await { expr: Option<HirId> },
1976 /// A plain `yield`.
1981 pub fn is_await(&self) -> bool {
1983 YieldSource::Await { .. } => true,
1984 YieldSource::Yield => false,
1989 impl fmt::Display for YieldSource {
1990 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1991 f.write_str(match self {
1992 YieldSource::Await { .. } => "`await`",
1993 YieldSource::Yield => "`yield`",
1998 impl From<GeneratorKind> for YieldSource {
1999 fn from(kind: GeneratorKind) -> Self {
2001 // Guess based on the kind of the current generator.
2002 GeneratorKind::Gen => Self::Yield,
2003 GeneratorKind::Async(_) => Self::Await { expr: None },
2008 // N.B., if you change this, you'll probably want to change the corresponding
2009 // type structure in middle/ty.rs as well.
2010 #[derive(Debug, HashStable_Generic)]
2011 pub struct MutTy<'hir> {
2012 pub ty: &'hir Ty<'hir>,
2013 pub mutbl: Mutability,
2016 /// Represents a function's signature in a trait declaration,
2017 /// trait implementation, or a free function.
2018 #[derive(Debug, HashStable_Generic)]
2019 pub struct FnSig<'hir> {
2020 pub header: FnHeader,
2021 pub decl: &'hir FnDecl<'hir>,
2025 // The bodies for items are stored "out of line", in a separate
2026 // hashmap in the `Crate`. Here we just record the hir-id of the item
2027 // so it can fetched later.
2028 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
2029 pub struct TraitItemId {
2030 pub def_id: LocalDefId,
2035 pub fn hir_id(&self) -> HirId {
2036 // Items are always HIR owners.
2037 HirId::make_owner(self.def_id)
2041 /// Represents an item declaration within a trait declaration,
2042 /// possibly including a default implementation. A trait item is
2043 /// either required (meaning it doesn't have an implementation, just a
2044 /// signature) or provided (meaning it has a default implementation).
2046 pub struct TraitItem<'hir> {
2048 pub def_id: LocalDefId,
2049 pub generics: Generics<'hir>,
2050 pub kind: TraitItemKind<'hir>,
2054 impl TraitItem<'_> {
2056 pub fn hir_id(&self) -> HirId {
2057 // Items are always HIR owners.
2058 HirId::make_owner(self.def_id)
2061 pub fn trait_item_id(&self) -> TraitItemId {
2062 TraitItemId { def_id: self.def_id }
2066 /// Represents a trait method's body (or just argument names).
2067 #[derive(Encodable, Debug, HashStable_Generic)]
2068 pub enum TraitFn<'hir> {
2069 /// No default body in the trait, just a signature.
2070 Required(&'hir [Ident]),
2072 /// Both signature and body are provided in the trait.
2076 /// Represents a trait method or associated constant or type
2077 #[derive(Debug, HashStable_Generic)]
2078 pub enum TraitItemKind<'hir> {
2079 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
2080 Const(&'hir Ty<'hir>, Option<BodyId>),
2081 /// An associated function with an optional body.
2082 Fn(FnSig<'hir>, TraitFn<'hir>),
2083 /// An associated type with (possibly empty) bounds and optional concrete
2085 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
2088 // The bodies for items are stored "out of line", in a separate
2089 // hashmap in the `Crate`. Here we just record the hir-id of the item
2090 // so it can fetched later.
2091 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
2092 pub struct ImplItemId {
2093 pub def_id: LocalDefId,
2098 pub fn hir_id(&self) -> HirId {
2099 // Items are always HIR owners.
2100 HirId::make_owner(self.def_id)
2104 /// Represents anything within an `impl` block.
2106 pub struct ImplItem<'hir> {
2108 pub def_id: LocalDefId,
2109 pub vis: Visibility<'hir>,
2110 pub defaultness: Defaultness,
2111 pub generics: Generics<'hir>,
2112 pub kind: ImplItemKind<'hir>,
2118 pub fn hir_id(&self) -> HirId {
2119 // Items are always HIR owners.
2120 HirId::make_owner(self.def_id)
2123 pub fn impl_item_id(&self) -> ImplItemId {
2124 ImplItemId { def_id: self.def_id }
2128 /// Represents various kinds of content within an `impl`.
2129 #[derive(Debug, HashStable_Generic)]
2130 pub enum ImplItemKind<'hir> {
2131 /// An associated constant of the given type, set to the constant result
2132 /// of the expression.
2133 Const(&'hir Ty<'hir>, BodyId),
2134 /// An associated function implementation with the given signature and body.
2135 Fn(FnSig<'hir>, BodyId),
2136 /// An associated type.
2137 TyAlias(&'hir Ty<'hir>),
2140 // The name of the associated type for `Fn` return types.
2141 pub const FN_OUTPUT_NAME: Symbol = sym::Output;
2143 /// Bind a type to an associated type (i.e., `A = Foo`).
2145 /// Bindings like `A: Debug` are represented as a special type `A =
2146 /// $::Debug` that is understood by the astconv code.
2148 /// FIXME(alexreg): why have a separate type for the binding case,
2149 /// wouldn't it be better to make the `ty` field an enum like the
2153 /// enum TypeBindingKind {
2158 #[derive(Debug, HashStable_Generic)]
2159 pub struct TypeBinding<'hir> {
2161 #[stable_hasher(project(name))]
2163 pub gen_args: &'hir GenericArgs<'hir>,
2164 pub kind: TypeBindingKind<'hir>,
2168 // Represents the two kinds of type bindings.
2169 #[derive(Debug, HashStable_Generic)]
2170 pub enum TypeBindingKind<'hir> {
2171 /// E.g., `Foo<Bar: Send>`.
2172 Constraint { bounds: &'hir [GenericBound<'hir>] },
2173 /// E.g., `Foo<Bar = ()>`.
2174 Equality { ty: &'hir Ty<'hir> },
2177 impl TypeBinding<'_> {
2178 pub fn ty(&self) -> &Ty<'_> {
2180 TypeBindingKind::Equality { ref ty } => ty,
2181 _ => panic!("expected equality type binding for parenthesized generic args"),
2187 pub struct Ty<'hir> {
2189 pub kind: TyKind<'hir>,
2193 /// Not represented directly in the AST; referred to by name through a `ty_path`.
2194 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
2195 #[derive(HashStable_Generic)]
2206 /// All of the primitive types
2207 pub const ALL: [Self; 17] = [
2208 // any changes here should also be reflected in `PrimTy::from_name`
2209 Self::Int(IntTy::I8),
2210 Self::Int(IntTy::I16),
2211 Self::Int(IntTy::I32),
2212 Self::Int(IntTy::I64),
2213 Self::Int(IntTy::I128),
2214 Self::Int(IntTy::Isize),
2215 Self::Uint(UintTy::U8),
2216 Self::Uint(UintTy::U16),
2217 Self::Uint(UintTy::U32),
2218 Self::Uint(UintTy::U64),
2219 Self::Uint(UintTy::U128),
2220 Self::Uint(UintTy::Usize),
2221 Self::Float(FloatTy::F32),
2222 Self::Float(FloatTy::F64),
2228 /// Like [`PrimTy::name`], but returns a &str instead of a symbol.
2231 pub fn name_str(self) -> &'static str {
2233 PrimTy::Int(i) => i.name_str(),
2234 PrimTy::Uint(u) => u.name_str(),
2235 PrimTy::Float(f) => f.name_str(),
2236 PrimTy::Str => "str",
2237 PrimTy::Bool => "bool",
2238 PrimTy::Char => "char",
2242 pub fn name(self) -> Symbol {
2244 PrimTy::Int(i) => i.name(),
2245 PrimTy::Uint(u) => u.name(),
2246 PrimTy::Float(f) => f.name(),
2247 PrimTy::Str => sym::str,
2248 PrimTy::Bool => sym::bool,
2249 PrimTy::Char => sym::char,
2253 /// Returns the matching `PrimTy` for a `Symbol` such as "str" or "i32".
2254 /// Returns `None` if no matching type is found.
2255 pub fn from_name(name: Symbol) -> Option<Self> {
2256 let ty = match name {
2257 // any changes here should also be reflected in `PrimTy::ALL`
2258 sym::i8 => Self::Int(IntTy::I8),
2259 sym::i16 => Self::Int(IntTy::I16),
2260 sym::i32 => Self::Int(IntTy::I32),
2261 sym::i64 => Self::Int(IntTy::I64),
2262 sym::i128 => Self::Int(IntTy::I128),
2263 sym::isize => Self::Int(IntTy::Isize),
2264 sym::u8 => Self::Uint(UintTy::U8),
2265 sym::u16 => Self::Uint(UintTy::U16),
2266 sym::u32 => Self::Uint(UintTy::U32),
2267 sym::u64 => Self::Uint(UintTy::U64),
2268 sym::u128 => Self::Uint(UintTy::U128),
2269 sym::usize => Self::Uint(UintTy::Usize),
2270 sym::f32 => Self::Float(FloatTy::F32),
2271 sym::f64 => Self::Float(FloatTy::F64),
2272 sym::bool => Self::Bool,
2273 sym::char => Self::Char,
2274 sym::str => Self::Str,
2281 #[derive(Debug, HashStable_Generic)]
2282 pub struct BareFnTy<'hir> {
2283 pub unsafety: Unsafety,
2285 pub generic_params: &'hir [GenericParam<'hir>],
2286 pub decl: &'hir FnDecl<'hir>,
2287 pub param_names: &'hir [Ident],
2290 #[derive(Debug, HashStable_Generic)]
2291 pub struct OpaqueTy<'hir> {
2292 pub generics: Generics<'hir>,
2293 pub bounds: GenericBounds<'hir>,
2294 pub impl_trait_fn: Option<DefId>,
2295 pub origin: OpaqueTyOrigin,
2298 /// From whence the opaque type came.
2299 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2300 pub enum OpaqueTyOrigin {
2305 /// type aliases: `type Foo = impl Trait;`
2309 /// The various kinds of types recognized by the compiler.
2310 #[derive(Debug, HashStable_Generic)]
2311 pub enum TyKind<'hir> {
2312 /// A variable length slice (i.e., `[T]`).
2313 Slice(&'hir Ty<'hir>),
2314 /// A fixed length array (i.e., `[T; n]`).
2315 Array(&'hir Ty<'hir>, AnonConst),
2316 /// A raw pointer (i.e., `*const T` or `*mut T`).
2318 /// A reference (i.e., `&'a T` or `&'a mut T`).
2319 Rptr(Lifetime, MutTy<'hir>),
2320 /// A bare function (e.g., `fn(usize) -> bool`).
2321 BareFn(&'hir BareFnTy<'hir>),
2322 /// The never type (`!`).
2324 /// A tuple (`(A, B, C, D, ...)`).
2325 Tup(&'hir [Ty<'hir>]),
2326 /// A path to a type definition (`module::module::...::Type`), or an
2327 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2329 /// Type parameters may be stored in each `PathSegment`.
2331 /// A opaque type definition itself. This is currently only used for the
2332 /// `opaque type Foo: Trait` item that `impl Trait` in desugars to.
2334 /// The generic argument list contains the lifetimes (and in the future
2335 /// possibly parameters) that are actually bound on the `impl Trait`.
2336 OpaqueDef(ItemId, &'hir [GenericArg<'hir>]),
2337 /// A trait object type `Bound1 + Bound2 + Bound3`
2338 /// where `Bound` is a trait or a lifetime.
2339 TraitObject(&'hir [PolyTraitRef<'hir>], Lifetime, TraitObjectSyntax),
2342 /// `TyKind::Infer` means the type should be inferred instead of it having been
2343 /// specified. This can appear anywhere in a type.
2345 /// Placeholder for a type that has failed to be defined.
2349 #[derive(Debug, HashStable_Generic)]
2350 pub enum InlineAsmOperand<'hir> {
2352 reg: InlineAsmRegOrRegClass,
2356 reg: InlineAsmRegOrRegClass,
2358 expr: Option<Expr<'hir>>,
2361 reg: InlineAsmRegOrRegClass,
2366 reg: InlineAsmRegOrRegClass,
2368 in_expr: Expr<'hir>,
2369 out_expr: Option<Expr<'hir>>,
2372 anon_const: AnonConst,
2379 impl<'hir> InlineAsmOperand<'hir> {
2380 pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
2382 Self::In { reg, .. }
2383 | Self::Out { reg, .. }
2384 | Self::InOut { reg, .. }
2385 | Self::SplitInOut { reg, .. } => Some(reg),
2386 Self::Const { .. } | Self::Sym { .. } => None,
2391 #[derive(Debug, HashStable_Generic)]
2392 pub struct InlineAsm<'hir> {
2393 pub template: &'hir [InlineAsmTemplatePiece],
2394 pub operands: &'hir [(InlineAsmOperand<'hir>, Span)],
2395 pub options: InlineAsmOptions,
2396 pub line_spans: &'hir [Span],
2399 #[derive(Copy, Clone, Encodable, Decodable, Debug, Hash, HashStable_Generic, PartialEq)]
2400 pub struct LlvmInlineAsmOutput {
2401 pub constraint: Symbol,
2403 pub is_indirect: bool,
2407 // NOTE(eddyb) This is used within MIR as well, so unlike the rest of the HIR,
2408 // it needs to be `Clone` and `Decodable` and use plain `Vec<T>` instead of
2409 // arena-allocated slice.
2410 #[derive(Clone, Encodable, Decodable, Debug, Hash, HashStable_Generic, PartialEq)]
2411 pub struct LlvmInlineAsmInner {
2413 pub asm_str_style: StrStyle,
2414 pub outputs: Vec<LlvmInlineAsmOutput>,
2415 pub inputs: Vec<Symbol>,
2416 pub clobbers: Vec<Symbol>,
2418 pub alignstack: bool,
2419 pub dialect: LlvmAsmDialect,
2422 #[derive(Debug, HashStable_Generic)]
2423 pub struct LlvmInlineAsm<'hir> {
2424 pub inner: LlvmInlineAsmInner,
2425 pub outputs_exprs: &'hir [Expr<'hir>],
2426 pub inputs_exprs: &'hir [Expr<'hir>],
2429 /// Represents a parameter in a function header.
2430 #[derive(Debug, HashStable_Generic)]
2431 pub struct Param<'hir> {
2433 pub pat: &'hir Pat<'hir>,
2438 /// Represents the header (not the body) of a function declaration.
2439 #[derive(Debug, HashStable_Generic)]
2440 pub struct FnDecl<'hir> {
2441 /// The types of the function's parameters.
2443 /// Additional argument data is stored in the function's [body](Body::params).
2444 pub inputs: &'hir [Ty<'hir>],
2445 pub output: FnRetTy<'hir>,
2446 pub c_variadic: bool,
2447 /// Does the function have an implicit self?
2448 pub implicit_self: ImplicitSelfKind,
2451 /// Represents what type of implicit self a function has, if any.
2452 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2453 pub enum ImplicitSelfKind {
2454 /// Represents a `fn x(self);`.
2456 /// Represents a `fn x(mut self);`.
2458 /// Represents a `fn x(&self);`.
2460 /// Represents a `fn x(&mut self);`.
2462 /// Represents when a function does not have a self argument or
2463 /// when a function has a `self: X` argument.
2467 impl ImplicitSelfKind {
2468 /// Does this represent an implicit self?
2469 pub fn has_implicit_self(&self) -> bool {
2470 !matches!(*self, ImplicitSelfKind::None)
2474 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable, Debug)]
2475 #[derive(HashStable_Generic)]
2481 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable, HashStable_Generic)]
2482 pub enum Defaultness {
2483 Default { has_value: bool },
2488 pub fn has_value(&self) -> bool {
2490 Defaultness::Default { has_value } => has_value,
2491 Defaultness::Final => true,
2495 pub fn is_final(&self) -> bool {
2496 *self == Defaultness::Final
2499 pub fn is_default(&self) -> bool {
2500 matches!(*self, Defaultness::Default { .. })
2504 #[derive(Debug, HashStable_Generic)]
2505 pub enum FnRetTy<'hir> {
2506 /// Return type is not specified.
2508 /// Functions default to `()` and
2509 /// closures default to inference. Span points to where return
2510 /// type would be inserted.
2511 DefaultReturn(Span),
2512 /// Everything else.
2513 Return(&'hir Ty<'hir>),
2518 pub fn span(&self) -> Span {
2520 Self::DefaultReturn(span) => span,
2521 Self::Return(ref ty) => ty.span,
2526 #[derive(Encodable, Debug)]
2527 pub struct Mod<'hir> {
2528 /// A span from the first token past `{` to the last token until `}`.
2529 /// For `mod foo;`, the inner span ranges from the first token
2530 /// to the last token in the external file.
2532 pub item_ids: &'hir [ItemId],
2535 #[derive(Debug, HashStable_Generic)]
2536 pub struct EnumDef<'hir> {
2537 pub variants: &'hir [Variant<'hir>],
2540 #[derive(Debug, HashStable_Generic)]
2541 pub struct Variant<'hir> {
2542 /// Name of the variant.
2543 #[stable_hasher(project(name))]
2545 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2547 /// Fields and constructor id of the variant.
2548 pub data: VariantData<'hir>,
2549 /// Explicit discriminant (e.g., `Foo = 1`).
2550 pub disr_expr: Option<AnonConst>,
2555 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2557 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2558 /// Also produced for each element of a list `use`, e.g.
2559 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2562 /// Glob import, e.g., `use foo::*`.
2565 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2566 /// an additional `use foo::{}` for performing checks such as
2567 /// unstable feature gating. May be removed in the future.
2571 /// References to traits in impls.
2573 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2574 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2575 /// trait being referred to but just a unique `HirId` that serves as a key
2576 /// within the resolution map.
2577 #[derive(Clone, Debug, HashStable_Generic)]
2578 pub struct TraitRef<'hir> {
2579 pub path: &'hir Path<'hir>,
2580 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2581 #[stable_hasher(ignore)]
2582 pub hir_ref_id: HirId,
2586 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2587 pub fn trait_def_id(&self) -> Option<DefId> {
2588 match self.path.res {
2589 Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
2591 _ => unreachable!(),
2596 #[derive(Clone, Debug, HashStable_Generic)]
2597 pub struct PolyTraitRef<'hir> {
2598 /// The `'a` in `for<'a> Foo<&'a T>`.
2599 pub bound_generic_params: &'hir [GenericParam<'hir>],
2601 /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
2602 pub trait_ref: TraitRef<'hir>,
2607 pub type Visibility<'hir> = Spanned<VisibilityKind<'hir>>;
2610 pub enum VisibilityKind<'hir> {
2613 Restricted { path: &'hir Path<'hir>, hir_id: HirId },
2617 impl VisibilityKind<'_> {
2618 pub fn is_pub(&self) -> bool {
2619 matches!(*self, VisibilityKind::Public)
2622 pub fn is_pub_restricted(&self) -> bool {
2624 VisibilityKind::Public | VisibilityKind::Inherited => false,
2625 VisibilityKind::Crate(..) | VisibilityKind::Restricted { .. } => true,
2630 #[derive(Debug, HashStable_Generic)]
2631 pub struct FieldDef<'hir> {
2633 #[stable_hasher(project(name))]
2635 pub vis: Visibility<'hir>,
2637 pub ty: &'hir Ty<'hir>,
2641 // Still necessary in couple of places
2642 pub fn is_positional(&self) -> bool {
2643 let first = self.ident.as_str().as_bytes()[0];
2644 (b'0'..=b'9').contains(&first)
2648 /// Fields and constructor IDs of enum variants and structs.
2649 #[derive(Debug, HashStable_Generic)]
2650 pub enum VariantData<'hir> {
2651 /// A struct variant.
2653 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2654 Struct(&'hir [FieldDef<'hir>], /* recovered */ bool),
2655 /// A tuple variant.
2657 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2658 Tuple(&'hir [FieldDef<'hir>], HirId),
2661 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2665 impl VariantData<'hir> {
2666 /// Return the fields of this variant.
2667 pub fn fields(&self) -> &'hir [FieldDef<'hir>] {
2669 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2674 /// Return the `HirId` of this variant's constructor, if it has one.
2675 pub fn ctor_hir_id(&self) -> Option<HirId> {
2677 VariantData::Struct(_, _) => None,
2678 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2683 // The bodies for items are stored "out of line", in a separate
2684 // hashmap in the `Crate`. Here we just record the hir-id of the item
2685 // so it can fetched later.
2686 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug, Hash)]
2688 pub def_id: LocalDefId,
2693 pub fn hir_id(&self) -> HirId {
2694 // Items are always HIR owners.
2695 HirId::make_owner(self.def_id)
2701 /// The name might be a dummy name in case of anonymous items
2703 pub struct Item<'hir> {
2705 pub def_id: LocalDefId,
2706 pub kind: ItemKind<'hir>,
2707 pub vis: Visibility<'hir>,
2713 pub fn hir_id(&self) -> HirId {
2714 // Items are always HIR owners.
2715 HirId::make_owner(self.def_id)
2718 pub fn item_id(&self) -> ItemId {
2719 ItemId { def_id: self.def_id }
2723 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2724 #[derive(Encodable, Decodable, HashStable_Generic)]
2731 pub fn prefix_str(&self) -> &'static str {
2733 Self::Unsafe => "unsafe ",
2739 impl fmt::Display for Unsafety {
2740 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2741 f.write_str(match *self {
2742 Self::Unsafe => "unsafe",
2743 Self::Normal => "normal",
2748 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2749 #[derive(Encodable, Decodable, HashStable_Generic)]
2750 pub enum Constness {
2755 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2756 pub struct FnHeader {
2757 pub unsafety: Unsafety,
2758 pub constness: Constness,
2759 pub asyncness: IsAsync,
2764 pub fn is_const(&self) -> bool {
2765 matches!(&self.constness, Constness::Const)
2769 #[derive(Debug, HashStable_Generic)]
2770 pub enum ItemKind<'hir> {
2771 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2773 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2774 ExternCrate(Option<Symbol>),
2776 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2780 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2781 Use(&'hir Path<'hir>, UseKind),
2783 /// A `static` item.
2784 Static(&'hir Ty<'hir>, Mutability, BodyId),
2786 Const(&'hir Ty<'hir>, BodyId),
2787 /// A function declaration.
2788 Fn(FnSig<'hir>, Generics<'hir>, BodyId),
2791 /// An external module, e.g. `extern { .. }`.
2792 ForeignMod { abi: Abi, items: &'hir [ForeignItemRef<'hir>] },
2793 /// Module-level inline assembly (from `global_asm!`).
2794 GlobalAsm(&'hir InlineAsm<'hir>),
2795 /// A type alias, e.g., `type Foo = Bar<u8>`.
2796 TyAlias(&'hir Ty<'hir>, Generics<'hir>),
2797 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2798 OpaqueTy(OpaqueTy<'hir>),
2799 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2800 Enum(EnumDef<'hir>, Generics<'hir>),
2801 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2802 Struct(VariantData<'hir>, Generics<'hir>),
2803 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2804 Union(VariantData<'hir>, Generics<'hir>),
2805 /// A trait definition.
2806 Trait(IsAuto, Unsafety, Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
2808 TraitAlias(Generics<'hir>, GenericBounds<'hir>),
2810 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2814 #[derive(Debug, HashStable_Generic)]
2815 pub struct Impl<'hir> {
2816 pub unsafety: Unsafety,
2817 pub polarity: ImplPolarity,
2818 pub defaultness: Defaultness,
2819 // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata
2820 // decoding as `Span`s cannot be decoded when a `Session` is not available.
2821 pub defaultness_span: Option<Span>,
2822 pub constness: Constness,
2823 pub generics: Generics<'hir>,
2825 /// The trait being implemented, if any.
2826 pub of_trait: Option<TraitRef<'hir>>,
2828 pub self_ty: &'hir Ty<'hir>,
2829 pub items: &'hir [ImplItemRef<'hir>],
2833 pub fn generics(&self) -> Option<&Generics<'_>> {
2835 ItemKind::Fn(_, ref generics, _)
2836 | ItemKind::TyAlias(_, ref generics)
2837 | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
2838 | ItemKind::Enum(_, ref generics)
2839 | ItemKind::Struct(_, ref generics)
2840 | ItemKind::Union(_, ref generics)
2841 | ItemKind::Trait(_, _, ref generics, _, _)
2842 | ItemKind::Impl(Impl { ref generics, .. }) => generics,
2847 pub fn descr(&self) -> &'static str {
2849 ItemKind::ExternCrate(..) => "extern crate",
2850 ItemKind::Use(..) => "`use` import",
2851 ItemKind::Static(..) => "static item",
2852 ItemKind::Const(..) => "constant item",
2853 ItemKind::Fn(..) => "function",
2854 ItemKind::Mod(..) => "module",
2855 ItemKind::ForeignMod { .. } => "extern block",
2856 ItemKind::GlobalAsm(..) => "global asm item",
2857 ItemKind::TyAlias(..) => "type alias",
2858 ItemKind::OpaqueTy(..) => "opaque type",
2859 ItemKind::Enum(..) => "enum",
2860 ItemKind::Struct(..) => "struct",
2861 ItemKind::Union(..) => "union",
2862 ItemKind::Trait(..) => "trait",
2863 ItemKind::TraitAlias(..) => "trait alias",
2864 ItemKind::Impl(..) => "implementation",
2869 /// A reference from an trait to one of its associated items. This
2870 /// contains the item's id, naturally, but also the item's name and
2871 /// some other high-level details (like whether it is an associated
2872 /// type or method, and whether it is public). This allows other
2873 /// passes to find the impl they want without loading the ID (which
2874 /// means fewer edges in the incremental compilation graph).
2875 #[derive(Encodable, Debug, HashStable_Generic)]
2876 pub struct TraitItemRef {
2877 pub id: TraitItemId,
2878 #[stable_hasher(project(name))]
2880 pub kind: AssocItemKind,
2882 pub defaultness: Defaultness,
2885 /// A reference from an impl to one of its associated items. This
2886 /// contains the item's ID, naturally, but also the item's name and
2887 /// some other high-level details (like whether it is an associated
2888 /// type or method, and whether it is public). This allows other
2889 /// passes to find the impl they want without loading the ID (which
2890 /// means fewer edges in the incremental compilation graph).
2891 #[derive(Debug, HashStable_Generic)]
2892 pub struct ImplItemRef<'hir> {
2894 #[stable_hasher(project(name))]
2896 pub kind: AssocItemKind,
2898 pub vis: Visibility<'hir>,
2899 pub defaultness: Defaultness,
2902 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2903 pub enum AssocItemKind {
2905 Fn { has_self: bool },
2909 // The bodies for items are stored "out of line", in a separate
2910 // hashmap in the `Crate`. Here we just record the hir-id of the item
2911 // so it can fetched later.
2912 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
2913 pub struct ForeignItemId {
2914 pub def_id: LocalDefId,
2917 impl ForeignItemId {
2919 pub fn hir_id(&self) -> HirId {
2920 // Items are always HIR owners.
2921 HirId::make_owner(self.def_id)
2925 /// A reference from a foreign block to one of its items. This
2926 /// contains the item's ID, naturally, but also the item's name and
2927 /// some other high-level details (like whether it is an associated
2928 /// type or method, and whether it is public). This allows other
2929 /// passes to find the impl they want without loading the ID (which
2930 /// means fewer edges in the incremental compilation graph).
2931 #[derive(Debug, HashStable_Generic)]
2932 pub struct ForeignItemRef<'hir> {
2933 pub id: ForeignItemId,
2934 #[stable_hasher(project(name))]
2937 pub vis: Visibility<'hir>,
2941 pub struct ForeignItem<'hir> {
2943 pub kind: ForeignItemKind<'hir>,
2944 pub def_id: LocalDefId,
2946 pub vis: Visibility<'hir>,
2949 impl ForeignItem<'_> {
2951 pub fn hir_id(&self) -> HirId {
2952 // Items are always HIR owners.
2953 HirId::make_owner(self.def_id)
2956 pub fn foreign_item_id(&self) -> ForeignItemId {
2957 ForeignItemId { def_id: self.def_id }
2961 /// An item within an `extern` block.
2962 #[derive(Debug, HashStable_Generic)]
2963 pub enum ForeignItemKind<'hir> {
2964 /// A foreign function.
2965 Fn(&'hir FnDecl<'hir>, &'hir [Ident], Generics<'hir>),
2966 /// A foreign static item (`static ext: u8`).
2967 Static(&'hir Ty<'hir>, Mutability),
2972 /// A variable captured by a closure.
2973 #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)]
2975 // First span where it is accessed (there can be multiple).
2979 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2980 // has length > 0 if the trait is found through an chain of imports, starting with the
2981 // import/use statement in the scope where the trait is used.
2982 #[derive(Encodable, Decodable, Clone, Debug)]
2983 pub struct TraitCandidate {
2985 pub import_ids: SmallVec<[LocalDefId; 1]>,
2988 #[derive(Copy, Clone, Debug, HashStable_Generic)]
2989 pub enum OwnerNode<'hir> {
2990 Item(&'hir Item<'hir>),
2991 ForeignItem(&'hir ForeignItem<'hir>),
2992 TraitItem(&'hir TraitItem<'hir>),
2993 ImplItem(&'hir ImplItem<'hir>),
2994 MacroDef(&'hir MacroDef<'hir>),
2995 Crate(&'hir Mod<'hir>),
2998 impl<'hir> OwnerNode<'hir> {
2999 pub fn ident(&self) -> Option<Ident> {
3001 OwnerNode::Item(Item { ident, .. })
3002 | OwnerNode::ForeignItem(ForeignItem { ident, .. })
3003 | OwnerNode::ImplItem(ImplItem { ident, .. })
3004 | OwnerNode::TraitItem(TraitItem { ident, .. })
3005 | OwnerNode::MacroDef(MacroDef { ident, .. }) => Some(*ident),
3006 OwnerNode::Crate(..) => None,
3010 pub fn span(&self) -> Span {
3012 OwnerNode::Item(Item { span, .. })
3013 | OwnerNode::ForeignItem(ForeignItem { span, .. })
3014 | OwnerNode::ImplItem(ImplItem { span, .. })
3015 | OwnerNode::TraitItem(TraitItem { span, .. })
3016 | OwnerNode::MacroDef(MacroDef { span, .. })
3017 | OwnerNode::Crate(Mod { inner: span, .. }) => *span,
3021 pub fn fn_decl(&self) -> Option<&FnDecl<'hir>> {
3023 OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3024 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3025 | OwnerNode::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3026 OwnerNode::ForeignItem(ForeignItem {
3027 kind: ForeignItemKind::Fn(fn_decl, _, _),
3029 }) => Some(fn_decl),
3034 pub fn body_id(&self) -> Option<BodyId> {
3036 OwnerNode::TraitItem(TraitItem {
3037 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3040 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3041 | OwnerNode::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3046 pub fn generics(&self) -> Option<&'hir Generics<'hir>> {
3048 OwnerNode::TraitItem(TraitItem { generics, .. })
3049 | OwnerNode::ImplItem(ImplItem { generics, .. }) => Some(generics),
3050 OwnerNode::Item(item) => item.kind.generics(),
3055 pub fn def_id(self) -> LocalDefId {
3057 OwnerNode::Item(Item { def_id, .. })
3058 | OwnerNode::TraitItem(TraitItem { def_id, .. })
3059 | OwnerNode::ImplItem(ImplItem { def_id, .. })
3060 | OwnerNode::ForeignItem(ForeignItem { def_id, .. })
3061 | OwnerNode::MacroDef(MacroDef { def_id, .. }) => *def_id,
3062 OwnerNode::Crate(..) => crate::CRATE_HIR_ID.owner,
3066 pub fn expect_item(self) -> &'hir Item<'hir> {
3068 OwnerNode::Item(n) => n,
3073 pub fn expect_foreign_item(self) -> &'hir ForeignItem<'hir> {
3075 OwnerNode::ForeignItem(n) => n,
3080 pub fn expect_impl_item(self) -> &'hir ImplItem<'hir> {
3082 OwnerNode::ImplItem(n) => n,
3087 pub fn expect_trait_item(self) -> &'hir TraitItem<'hir> {
3089 OwnerNode::TraitItem(n) => n,
3094 pub fn expect_macro_def(self) -> &'hir MacroDef<'hir> {
3096 OwnerNode::MacroDef(n) => n,
3102 impl<'hir> Into<OwnerNode<'hir>> for &'hir Item<'hir> {
3103 fn into(self) -> OwnerNode<'hir> {
3104 OwnerNode::Item(self)
3108 impl<'hir> Into<OwnerNode<'hir>> for &'hir ForeignItem<'hir> {
3109 fn into(self) -> OwnerNode<'hir> {
3110 OwnerNode::ForeignItem(self)
3114 impl<'hir> Into<OwnerNode<'hir>> for &'hir ImplItem<'hir> {
3115 fn into(self) -> OwnerNode<'hir> {
3116 OwnerNode::ImplItem(self)
3120 impl<'hir> Into<OwnerNode<'hir>> for &'hir TraitItem<'hir> {
3121 fn into(self) -> OwnerNode<'hir> {
3122 OwnerNode::TraitItem(self)
3126 impl<'hir> Into<OwnerNode<'hir>> for &'hir MacroDef<'hir> {
3127 fn into(self) -> OwnerNode<'hir> {
3128 OwnerNode::MacroDef(self)
3132 impl<'hir> Into<Node<'hir>> for OwnerNode<'hir> {
3133 fn into(self) -> Node<'hir> {
3135 OwnerNode::Item(n) => Node::Item(n),
3136 OwnerNode::ForeignItem(n) => Node::ForeignItem(n),
3137 OwnerNode::ImplItem(n) => Node::ImplItem(n),
3138 OwnerNode::TraitItem(n) => Node::TraitItem(n),
3139 OwnerNode::MacroDef(n) => Node::MacroDef(n),
3140 OwnerNode::Crate(n) => Node::Crate(n),
3145 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3146 pub enum Node<'hir> {
3147 Param(&'hir Param<'hir>),
3148 Item(&'hir Item<'hir>),
3149 ForeignItem(&'hir ForeignItem<'hir>),
3150 TraitItem(&'hir TraitItem<'hir>),
3151 ImplItem(&'hir ImplItem<'hir>),
3152 Variant(&'hir Variant<'hir>),
3153 Field(&'hir FieldDef<'hir>),
3154 AnonConst(&'hir AnonConst),
3155 Expr(&'hir Expr<'hir>),
3156 Stmt(&'hir Stmt<'hir>),
3157 PathSegment(&'hir PathSegment<'hir>),
3159 TraitRef(&'hir TraitRef<'hir>),
3160 Binding(&'hir Pat<'hir>),
3161 Pat(&'hir Pat<'hir>),
3162 Arm(&'hir Arm<'hir>),
3163 Block(&'hir Block<'hir>),
3164 Local(&'hir Local<'hir>),
3165 MacroDef(&'hir MacroDef<'hir>),
3167 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
3168 /// with synthesized constructors.
3169 Ctor(&'hir VariantData<'hir>),
3171 Lifetime(&'hir Lifetime),
3172 GenericParam(&'hir GenericParam<'hir>),
3173 Visibility(&'hir Visibility<'hir>),
3175 Crate(&'hir Mod<'hir>),
3177 Infer(&'hir InferArg),
3180 impl<'hir> Node<'hir> {
3181 pub fn ident(&self) -> Option<Ident> {
3183 Node::TraitItem(TraitItem { ident, .. })
3184 | Node::ImplItem(ImplItem { ident, .. })
3185 | Node::ForeignItem(ForeignItem { ident, .. })
3186 | Node::Field(FieldDef { ident, .. })
3187 | Node::Variant(Variant { ident, .. })
3188 | Node::MacroDef(MacroDef { ident, .. })
3189 | Node::Item(Item { ident, .. }) => Some(*ident),
3194 pub fn fn_decl(&self) -> Option<&FnDecl<'hir>> {
3196 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3197 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3198 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3199 Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
3206 pub fn body_id(&self) -> Option<BodyId> {
3208 Node::TraitItem(TraitItem {
3209 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3212 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3213 | Node::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3218 pub fn generics(&self) -> Option<&'hir Generics<'hir>> {
3220 Node::TraitItem(TraitItem { generics, .. })
3221 | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
3222 Node::Item(item) => item.kind.generics(),
3227 pub fn hir_id(&self) -> Option<HirId> {
3229 Node::Item(Item { def_id, .. })
3230 | Node::TraitItem(TraitItem { def_id, .. })
3231 | Node::ImplItem(ImplItem { def_id, .. })
3232 | Node::ForeignItem(ForeignItem { def_id, .. })
3233 | Node::MacroDef(MacroDef { def_id, .. }) => Some(HirId::make_owner(*def_id)),
3234 Node::Field(FieldDef { hir_id, .. })
3235 | Node::AnonConst(AnonConst { hir_id, .. })
3236 | Node::Expr(Expr { hir_id, .. })
3237 | Node::Stmt(Stmt { hir_id, .. })
3238 | Node::Ty(Ty { hir_id, .. })
3239 | Node::Binding(Pat { hir_id, .. })
3240 | Node::Pat(Pat { hir_id, .. })
3241 | Node::Arm(Arm { hir_id, .. })
3242 | Node::Block(Block { hir_id, .. })
3243 | Node::Local(Local { hir_id, .. })
3244 | Node::Lifetime(Lifetime { hir_id, .. })
3245 | Node::Param(Param { hir_id, .. })
3246 | Node::Infer(InferArg { hir_id, .. })
3247 | Node::GenericParam(GenericParam { hir_id, .. }) => Some(*hir_id),
3248 Node::TraitRef(TraitRef { hir_ref_id, .. }) => Some(*hir_ref_id),
3249 Node::PathSegment(PathSegment { hir_id, .. }) => *hir_id,
3250 Node::Variant(Variant { id, .. }) => Some(*id),
3251 Node::Ctor(variant) => variant.ctor_hir_id(),
3252 Node::Crate(_) | Node::Visibility(_) => None,
3256 /// Returns `Constness::Const` when this node is a const fn/impl.
3257 pub fn constness(&self) -> Constness {
3260 kind: ItemKind::Fn(FnSig { header: FnHeader { constness, .. }, .. }, ..),
3263 | Node::TraitItem(TraitItem {
3264 kind: TraitItemKind::Fn(FnSig { header: FnHeader { constness, .. }, .. }, ..),
3267 | Node::ImplItem(ImplItem {
3268 kind: ImplItemKind::Fn(FnSig { header: FnHeader { constness, .. }, .. }, ..),
3271 | Node::Item(Item { kind: ItemKind::Impl(Impl { constness, .. }), .. }) => *constness,
3273 _ => Constness::NotConst,
3277 pub fn as_owner(self) -> Option<OwnerNode<'hir>> {
3279 Node::Item(i) => Some(OwnerNode::Item(i)),
3280 Node::ForeignItem(i) => Some(OwnerNode::ForeignItem(i)),
3281 Node::TraitItem(i) => Some(OwnerNode::TraitItem(i)),
3282 Node::ImplItem(i) => Some(OwnerNode::ImplItem(i)),
3283 Node::MacroDef(i) => Some(OwnerNode::MacroDef(i)),
3284 Node::Crate(i) => Some(OwnerNode::Crate(i)),
3290 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3291 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
3293 rustc_data_structures::static_assert_size!(super::Block<'static>, 48);
3294 rustc_data_structures::static_assert_size!(super::Expr<'static>, 64);
3295 rustc_data_structures::static_assert_size!(super::Pat<'static>, 88);
3296 rustc_data_structures::static_assert_size!(super::QPath<'static>, 24);
3297 rustc_data_structures::static_assert_size!(super::Ty<'static>, 72);
3299 rustc_data_structures::static_assert_size!(super::Item<'static>, 184);
3300 rustc_data_structures::static_assert_size!(super::TraitItem<'static>, 128);
3301 rustc_data_structures::static_assert_size!(super::ImplItem<'static>, 152);
3302 rustc_data_structures::static_assert_size!(super::ForeignItem<'static>, 136);