1 // ignore-tidy-filelength
2 use crate::def::{CtorKind, DefKind, Namespace, Res};
3 use crate::def_id::DefId;
4 crate use crate::hir_id::HirId;
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::{AttrVec, Attribute, FloatTy, IntTy, Label, LitKind, StrStyle, 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::sync::{par_for_each_in, Send, Sync};
14 use rustc_macros::HashStable_Generic;
15 use rustc_span::source_map::{SourceMap, Spanned};
16 use rustc_span::symbol::{kw, sym, Ident, Symbol};
17 use rustc_span::{def_id::LocalDefId, BytePos};
18 use rustc_span::{MultiSpan, Span, DUMMY_SP};
19 use rustc_target::asm::InlineAsmRegOrRegClass;
20 use rustc_target::spec::abi::Abi;
22 use smallvec::SmallVec;
23 use std::collections::{BTreeMap, BTreeSet};
26 #[derive(Copy, Clone, Encodable, HashStable_Generic)]
31 /// Either "`'a`", referring to a named lifetime definition,
32 /// or "``" (i.e., `kw::Empty`), for elision placeholders.
34 /// HIR lowering inserts these placeholders in type paths that
35 /// refer to type definitions needing lifetime parameters,
36 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
37 pub name: LifetimeName,
40 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
41 #[derive(HashStable_Generic)]
43 /// Some user-given name like `T` or `'x`.
46 /// Synthetic name generated when user elided a lifetime in an impl header.
48 /// E.g., the lifetimes in cases like these:
51 /// impl Foo<'_> for u32
53 /// in that case, we rewrite to
55 /// impl<'f> Foo for &'f u32
56 /// impl<'f> Foo<'f> for u32
58 /// where `'f` is something like `Fresh(0)`. The indices are
59 /// unique per impl, but not necessarily continuous.
62 /// Indicates an illegal name was given and an error has been
63 /// reported (so we should squelch other derived errors). Occurs
64 /// when, e.g., `'_` is used in the wrong place.
69 pub fn ident(&self) -> Ident {
71 ParamName::Plain(ident) => ident,
72 ParamName::Fresh(_) | ParamName::Error => {
73 Ident::with_dummy_span(kw::UnderscoreLifetime)
78 pub fn normalize_to_macros_2_0(&self) -> ParamName {
80 ParamName::Plain(ident) => ParamName::Plain(ident.normalize_to_macros_2_0()),
81 param_name => param_name,
86 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
87 #[derive(HashStable_Generic)]
88 pub enum LifetimeName {
89 /// User-given names or fresh (synthetic) names.
92 /// User wrote nothing (e.g., the lifetime in `&u32`).
95 /// Implicit lifetime in a context like `dyn Foo`. This is
96 /// distinguished from implicit lifetimes elsewhere because the
97 /// lifetime that they default to must appear elsewhere within the
98 /// enclosing type. This means that, in an `impl Trait` context, we
99 /// don't have to create a parameter for them. That is, `impl
100 /// Trait<Item = &u32>` expands to an opaque type like `type
101 /// Foo<'a> = impl Trait<Item = &'a u32>`, but `impl Trait<item =
102 /// dyn Bar>` expands to `type Foo = impl Trait<Item = dyn Bar +
103 /// 'static>`. The latter uses `ImplicitObjectLifetimeDefault` so
104 /// that surrounding code knows not to create a lifetime
106 ImplicitObjectLifetimeDefault,
108 /// Indicates an error during lowering (usually `'_` in wrong place)
109 /// that was already reported.
112 /// User wrote specifies `'_`.
115 /// User wrote `'static`.
120 pub fn ident(&self) -> Ident {
122 LifetimeName::ImplicitObjectLifetimeDefault
123 | LifetimeName::Implicit
124 | LifetimeName::Error => Ident::invalid(),
125 LifetimeName::Underscore => Ident::with_dummy_span(kw::UnderscoreLifetime),
126 LifetimeName::Static => Ident::with_dummy_span(kw::StaticLifetime),
127 LifetimeName::Param(param_name) => param_name.ident(),
131 pub fn is_elided(&self) -> bool {
133 LifetimeName::ImplicitObjectLifetimeDefault
134 | LifetimeName::Implicit
135 | LifetimeName::Underscore => true,
137 // It might seem surprising that `Fresh(_)` counts as
138 // *not* elided -- but this is because, as far as the code
139 // in the compiler is concerned -- `Fresh(_)` variants act
140 // equivalently to "some fresh name". They correspond to
141 // early-bound regions on an impl, in other words.
142 LifetimeName::Error | LifetimeName::Param(_) | LifetimeName::Static => false,
146 fn is_static(&self) -> bool {
147 self == &LifetimeName::Static
150 pub fn normalize_to_macros_2_0(&self) -> LifetimeName {
152 LifetimeName::Param(param_name) => {
153 LifetimeName::Param(param_name.normalize_to_macros_2_0())
155 lifetime_name => lifetime_name,
160 impl fmt::Display for Lifetime {
161 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162 self.name.ident().fmt(f)
166 impl fmt::Debug for Lifetime {
167 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168 write!(f, "lifetime({}: {})", self.hir_id, self.name.ident())
173 pub fn is_elided(&self) -> bool {
174 self.name.is_elided()
177 pub fn is_static(&self) -> bool {
178 self.name.is_static()
182 /// A `Path` is essentially Rust's notion of a name; for instance,
183 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
184 /// along with a bunch of supporting information.
185 #[derive(Debug, HashStable_Generic)]
186 pub struct Path<'hir> {
188 /// The resolution for the path.
190 /// The segments in the path: the things separated by `::`.
191 pub segments: &'hir [PathSegment<'hir>],
195 pub fn is_global(&self) -> bool {
196 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
200 /// A segment of a path: an identifier, an optional lifetime, and a set of
202 #[derive(Debug, HashStable_Generic)]
203 pub struct PathSegment<'hir> {
204 /// The identifier portion of this path segment.
205 #[stable_hasher(project(name))]
207 // `id` and `res` are optional. We currently only use these in save-analysis,
208 // any path segments without these will not have save-analysis info and
209 // therefore will not have 'jump to def' in IDEs, but otherwise will not be
210 // affected. (In general, we don't bother to get the defs for synthesized
211 // segments, only for segments which have come from the AST).
212 pub hir_id: Option<HirId>,
213 pub res: Option<Res>,
215 /// Type/lifetime parameters attached to this path. They come in
216 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
217 /// this is more than just simple syntactic sugar; the use of
218 /// parens affects the region binding rules, so we preserve the
220 pub args: Option<&'hir GenericArgs<'hir>>,
222 /// Whether to infer remaining type parameters, if any.
223 /// This only applies to expression and pattern paths, and
224 /// out of those only the segments with no type parameters
225 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
226 pub infer_args: bool,
229 impl<'hir> PathSegment<'hir> {
230 /// Converts an identifier to the corresponding segment.
231 pub fn from_ident(ident: Ident) -> PathSegment<'hir> {
232 PathSegment { ident, hir_id: None, res: None, infer_args: true, args: None }
235 pub fn invalid() -> Self {
236 Self::from_ident(Ident::invalid())
239 pub fn args(&self) -> &GenericArgs<'hir> {
240 if let Some(ref args) = self.args {
243 const DUMMY: &GenericArgs<'_> = &GenericArgs::none();
249 #[derive(Encodable, Debug, HashStable_Generic)]
250 pub struct ConstArg {
251 pub value: AnonConst,
255 #[derive(Debug, HashStable_Generic)]
256 pub enum GenericArg<'hir> {
262 impl GenericArg<'_> {
263 pub fn span(&self) -> Span {
265 GenericArg::Lifetime(l) => l.span,
266 GenericArg::Type(t) => t.span,
267 GenericArg::Const(c) => c.span,
271 pub fn id(&self) -> HirId {
273 GenericArg::Lifetime(l) => l.hir_id,
274 GenericArg::Type(t) => t.hir_id,
275 GenericArg::Const(c) => c.value.hir_id,
279 pub fn is_const(&self) -> bool {
280 matches!(self, GenericArg::Const(_))
283 pub fn is_synthetic(&self) -> bool {
284 matches!(self, GenericArg::Lifetime(lifetime) if lifetime.name.ident() == Ident::invalid())
287 pub fn descr(&self) -> &'static str {
289 GenericArg::Lifetime(_) => "lifetime",
290 GenericArg::Type(_) => "type",
291 GenericArg::Const(_) => "constant",
295 pub fn to_ord(&self, feats: &rustc_feature::Features) -> ast::ParamKindOrd {
297 GenericArg::Lifetime(_) => ast::ParamKindOrd::Lifetime,
298 GenericArg::Type(_) => ast::ParamKindOrd::Type,
299 GenericArg::Const(_) => ast::ParamKindOrd::Const { unordered: feats.const_generics },
304 #[derive(Debug, HashStable_Generic)]
305 pub struct GenericArgs<'hir> {
306 /// The generic arguments for this path segment.
307 pub args: &'hir [GenericArg<'hir>],
308 /// Bindings (equality constraints) on associated types, if present.
309 /// E.g., `Foo<A = Bar>`.
310 pub bindings: &'hir [TypeBinding<'hir>],
311 /// Were arguments written in parenthesized form `Fn(T) -> U`?
312 /// This is required mostly for pretty-printing and diagnostics,
313 /// but also for changing lifetime elision rules to be "function-like".
314 pub parenthesized: bool,
317 impl GenericArgs<'_> {
318 pub const fn none() -> Self {
319 Self { args: &[], bindings: &[], parenthesized: false }
322 pub fn inputs(&self) -> &[Ty<'_>] {
323 if self.parenthesized {
324 for arg in self.args {
326 GenericArg::Lifetime(_) => {}
327 GenericArg::Type(ref ty) => {
328 if let TyKind::Tup(ref tys) = ty.kind {
333 GenericArg::Const(_) => {}
337 panic!("GenericArgs::inputs: not a `Fn(T) -> U`");
340 pub fn own_counts(&self) -> GenericParamCount {
341 // We could cache this as a property of `GenericParamCount`, but
342 // the aim is to refactor this away entirely eventually and the
343 // presence of this method will be a constant reminder.
344 let mut own_counts: GenericParamCount = Default::default();
346 for arg in self.args {
348 GenericArg::Lifetime(_) => own_counts.lifetimes += 1,
349 GenericArg::Type(_) => own_counts.types += 1,
350 GenericArg::Const(_) => own_counts.consts += 1,
357 pub fn span(&self) -> Option<Span> {
360 .filter(|arg| !arg.is_synthetic())
361 .map(|arg| arg.span())
362 .reduce(|span1, span2| span1.to(span2))
365 /// Returns span encompassing arguments and their surrounding `<>` or `()`
366 pub fn span_ext(&self, sm: &SourceMap) -> Option<Span> {
367 let mut span = self.span()?;
369 let (o, c) = if self.parenthesized { ('(', ')') } else { ('<', '>') };
371 if let Ok(snippet) = sm.span_to_snippet(span) {
372 let snippet = snippet.as_bytes();
374 if snippet[0] != (o as u8) || snippet[snippet.len() - 1] != (c as u8) {
375 span = sm.span_extend_to_prev_char(span, o, true);
376 span = span.with_lo(span.lo() - BytePos(1));
378 span = sm.span_extend_to_next_char(span, c, true);
379 span = span.with_hi(span.hi() + BytePos(1));
386 pub fn is_empty(&self) -> bool {
391 /// A modifier on a bound, currently this is only used for `?Sized`, where the
392 /// modifier is `Maybe`. Negative bounds should also be handled here.
393 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
394 #[derive(HashStable_Generic)]
395 pub enum TraitBoundModifier {
401 /// The AST represents all type param bounds as types.
402 /// `typeck::collect::compute_bounds` matches these against
403 /// the "special" built-in traits (see `middle::lang_items`) and
404 /// detects `Copy`, `Send` and `Sync`.
405 #[derive(Debug, HashStable_Generic)]
406 pub enum GenericBound<'hir> {
407 Trait(PolyTraitRef<'hir>, TraitBoundModifier),
408 // FIXME(davidtwco): Introduce `PolyTraitRef::LangItem`
409 LangItemTrait(LangItem, Span, HirId, &'hir GenericArgs<'hir>),
413 impl GenericBound<'_> {
414 pub fn trait_ref(&self) -> Option<&TraitRef<'_>> {
416 GenericBound::Trait(data, _) => Some(&data.trait_ref),
421 pub fn span(&self) -> Span {
423 GenericBound::Trait(t, ..) => t.span,
424 GenericBound::LangItemTrait(_, span, ..) => *span,
425 GenericBound::Outlives(l) => l.span,
430 pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
432 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
433 pub enum LifetimeParamKind {
434 // Indicates that the lifetime definition was explicitly declared (e.g., in
435 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
438 // Indicates that the lifetime definition was synthetically added
439 // as a result of an in-band lifetime usage (e.g., in
440 // `fn foo(x: &'a u8) -> &'a u8 { x }`).
443 // Indication that the lifetime was elided (e.g., in both cases in
444 // `fn foo(x: &u8) -> &'_ u8 { x }`).
447 // Indication that the lifetime name was somehow in error.
451 #[derive(Debug, HashStable_Generic)]
452 pub enum GenericParamKind<'hir> {
453 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
455 kind: LifetimeParamKind,
458 default: Option<&'hir Ty<'hir>>,
459 synthetic: Option<SyntheticTyParamKind>,
463 /// Optional default value for the const generic param
464 default: Option<AnonConst>,
468 #[derive(Debug, HashStable_Generic)]
469 pub struct GenericParam<'hir> {
472 pub attrs: &'hir [Attribute],
473 pub bounds: GenericBounds<'hir>,
475 pub pure_wrt_drop: bool,
476 pub kind: GenericParamKind<'hir>,
479 impl GenericParam<'hir> {
480 pub fn bounds_span(&self) -> Option<Span> {
481 self.bounds.iter().fold(None, |span, bound| {
482 let span = span.map(|s| s.to(bound.span())).unwrap_or_else(|| bound.span());
490 pub struct GenericParamCount {
491 pub lifetimes: usize,
496 /// Represents lifetimes and type parameters attached to a declaration
497 /// of a function, enum, trait, etc.
498 #[derive(Debug, HashStable_Generic)]
499 pub struct Generics<'hir> {
500 pub params: &'hir [GenericParam<'hir>],
501 pub where_clause: WhereClause<'hir>,
505 impl Generics<'hir> {
506 pub const fn empty() -> Generics<'hir> {
509 where_clause: WhereClause { predicates: &[], span: DUMMY_SP },
514 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'_>> {
515 for param in self.params {
516 if name == param.name.ident().name {
523 pub fn spans(&self) -> MultiSpan {
524 if self.params.is_empty() {
527 self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
532 /// Synthetic type parameters are converted to another form during lowering; this allows
533 /// us to track the original form they had, and is useful for error messages.
534 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
535 #[derive(HashStable_Generic)]
536 pub enum SyntheticTyParamKind {
538 // Created by the `#[rustc_synthetic]` attribute.
542 /// A where-clause in a definition.
543 #[derive(Debug, HashStable_Generic)]
544 pub struct WhereClause<'hir> {
545 pub predicates: &'hir [WherePredicate<'hir>],
546 // Only valid if predicates aren't empty.
550 impl WhereClause<'_> {
551 pub fn span(&self) -> Option<Span> {
552 if self.predicates.is_empty() { None } else { Some(self.span) }
555 /// The `WhereClause` under normal circumstances points at either the predicates or the empty
556 /// space where the `where` clause should be. Only of use for diagnostic suggestions.
557 pub fn span_for_predicates_or_empty_place(&self) -> Span {
561 /// `Span` where further predicates would be suggested, accounting for trailing commas, like
562 /// in `fn foo<T>(t: T) where T: Foo,` so we don't suggest two trailing commas.
563 pub fn tail_span_for_suggestion(&self) -> Span {
564 let end = self.span_for_predicates_or_empty_place().shrink_to_hi();
565 self.predicates.last().map_or(end, |p| p.span()).shrink_to_hi().to(end)
569 /// A single predicate in a where-clause.
570 #[derive(Debug, HashStable_Generic)]
571 pub enum WherePredicate<'hir> {
572 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
573 BoundPredicate(WhereBoundPredicate<'hir>),
574 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
575 RegionPredicate(WhereRegionPredicate<'hir>),
576 /// An equality predicate (unsupported).
577 EqPredicate(WhereEqPredicate<'hir>),
580 impl WherePredicate<'_> {
581 pub fn span(&self) -> Span {
583 WherePredicate::BoundPredicate(p) => p.span,
584 WherePredicate::RegionPredicate(p) => p.span,
585 WherePredicate::EqPredicate(p) => p.span,
590 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
591 #[derive(Debug, HashStable_Generic)]
592 pub struct WhereBoundPredicate<'hir> {
594 /// Any generics from a `for` binding.
595 pub bound_generic_params: &'hir [GenericParam<'hir>],
596 /// The type being bounded.
597 pub bounded_ty: &'hir Ty<'hir>,
598 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
599 pub bounds: GenericBounds<'hir>,
602 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
603 #[derive(Debug, HashStable_Generic)]
604 pub struct WhereRegionPredicate<'hir> {
606 pub lifetime: Lifetime,
607 pub bounds: GenericBounds<'hir>,
610 /// An equality predicate (e.g., `T = int`); currently unsupported.
611 #[derive(Debug, HashStable_Generic)]
612 pub struct WhereEqPredicate<'hir> {
615 pub lhs_ty: &'hir Ty<'hir>,
616 pub rhs_ty: &'hir Ty<'hir>,
619 #[derive(Default, Encodable, Debug, HashStable_Generic)]
620 pub struct ModuleItems {
621 // Use BTreeSets here so items are in the same order as in the
622 // list of all items in Crate
623 pub items: BTreeSet<ItemId>,
624 pub trait_items: BTreeSet<TraitItemId>,
625 pub impl_items: BTreeSet<ImplItemId>,
626 pub foreign_items: BTreeSet<ForeignItemId>,
629 /// A type representing only the top-level module.
630 #[derive(Encodable, Debug, HashStable_Generic)]
631 pub struct CrateItem<'hir> {
632 pub module: Mod<'hir>,
633 pub attrs: &'hir [Attribute],
637 /// The top-level data structure that stores the entire contents of
638 /// the crate currently being compiled.
640 /// For more details, see the [rustc dev guide].
642 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
644 pub struct Crate<'hir> {
645 pub item: CrateItem<'hir>,
646 pub exported_macros: &'hir [MacroDef<'hir>],
647 // Attributes from non-exported macros, kept only for collecting the library feature list.
648 pub non_exported_macro_attrs: &'hir [Attribute],
650 // N.B., we use a `BTreeMap` here so that `visit_all_items` iterates
651 // over the ids in increasing order. In principle it should not
652 // matter what order we visit things in, but in *practice* it
653 // does, because it can affect the order in which errors are
654 // detected, which in turn can make UI tests yield
655 // slightly different results.
656 pub items: BTreeMap<ItemId, Item<'hir>>,
658 pub trait_items: BTreeMap<TraitItemId, TraitItem<'hir>>,
659 pub impl_items: BTreeMap<ImplItemId, ImplItem<'hir>>,
660 pub foreign_items: BTreeMap<ForeignItemId, ForeignItem<'hir>>,
661 pub bodies: BTreeMap<BodyId, Body<'hir>>,
662 pub trait_impls: BTreeMap<DefId, Vec<LocalDefId>>,
664 /// A list of the body ids written out in the order in which they
665 /// appear in the crate. If you're going to process all the bodies
666 /// in the crate, you should iterate over this list rather than the keys
668 pub body_ids: Vec<BodyId>,
670 /// A list of modules written out in the order in which they
671 /// appear in the crate. This includes the main crate module.
672 pub modules: BTreeMap<LocalDefId, ModuleItems>,
673 /// A list of proc macro HirIds, written out in the order in which
674 /// they are declared in the static array generated by proc_macro_harness.
675 pub proc_macros: Vec<HirId>,
677 pub trait_map: BTreeMap<HirId, Vec<TraitCandidate>>,
681 pub fn item(&self, id: ItemId) -> &Item<'hir> {
685 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem<'hir> {
686 &self.trait_items[&id]
689 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem<'hir> {
690 &self.impl_items[&id]
693 pub fn foreign_item(&self, id: ForeignItemId) -> &ForeignItem<'hir> {
694 &self.foreign_items[&id]
697 pub fn body(&self, id: BodyId) -> &Body<'hir> {
703 /// Visits all items in the crate in some deterministic (but
704 /// unspecified) order. If you just need to process every item,
705 /// but don't care about nesting, this method is the best choice.
707 /// If you do care about nesting -- usually because your algorithm
708 /// follows lexical scoping rules -- then you want a different
709 /// approach. You should override `visit_nested_item` in your
710 /// visitor and then call `intravisit::walk_crate` instead.
711 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
713 V: itemlikevisit::ItemLikeVisitor<'hir>,
715 for item in self.items.values() {
716 visitor.visit_item(item);
719 for trait_item in self.trait_items.values() {
720 visitor.visit_trait_item(trait_item);
723 for impl_item in self.impl_items.values() {
724 visitor.visit_impl_item(impl_item);
727 for foreign_item in self.foreign_items.values() {
728 visitor.visit_foreign_item(foreign_item);
732 /// A parallel version of `visit_all_item_likes`.
733 pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
735 V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send,
739 par_for_each_in(&self.items, |(_, item)| {
740 visitor.visit_item(item);
744 par_for_each_in(&self.trait_items, |(_, trait_item)| {
745 visitor.visit_trait_item(trait_item);
749 par_for_each_in(&self.impl_items, |(_, impl_item)| {
750 visitor.visit_impl_item(impl_item);
754 par_for_each_in(&self.foreign_items, |(_, foreign_item)| {
755 visitor.visit_foreign_item(foreign_item);
762 /// A macro definition, in this crate or imported from another.
764 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
766 pub struct MacroDef<'hir> {
768 pub vis: Visibility<'hir>,
769 pub attrs: &'hir [Attribute],
770 pub def_id: LocalDefId,
772 pub ast: ast::MacroDef,
776 pub fn hir_id(&self) -> HirId {
777 HirId::make_owner(self.def_id)
781 /// A block of statements `{ .. }`, which may have a label (in this case the
782 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
783 /// the `rules` being anything but `DefaultBlock`.
784 #[derive(Debug, HashStable_Generic)]
785 pub struct Block<'hir> {
786 /// Statements in a block.
787 pub stmts: &'hir [Stmt<'hir>],
788 /// An expression at the end of the block
789 /// without a semicolon, if any.
790 pub expr: Option<&'hir Expr<'hir>>,
791 #[stable_hasher(ignore)]
793 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
794 pub rules: BlockCheckMode,
796 /// If true, then there may exist `break 'a` values that aim to
797 /// break out of this block early.
798 /// Used by `'label: {}` blocks and by `try {}` blocks.
799 pub targeted_by_break: bool,
802 #[derive(Debug, HashStable_Generic)]
803 pub struct Pat<'hir> {
804 #[stable_hasher(ignore)]
806 pub kind: PatKind<'hir>,
808 // Whether to use default binding modes.
809 // At present, this is false only for destructuring assignment.
810 pub default_binding_modes: bool,
813 impl<'hir> Pat<'hir> {
814 // FIXME(#19596) this is a workaround, but there should be a better way
815 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) -> bool {
822 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
823 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
824 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
825 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
826 Slice(before, slice, after) => {
827 before.iter().chain(slice.iter()).chain(after.iter()).all(|p| p.walk_short_(it))
832 /// Walk the pattern in left-to-right order,
833 /// short circuiting (with `.all(..)`) if `false` is returned.
835 /// Note that when visiting e.g. `Tuple(ps)`,
836 /// if visiting `ps[0]` returns `false`,
837 /// then `ps[1]` will not be visited.
838 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) -> bool {
839 self.walk_short_(&mut it)
842 // FIXME(#19596) this is a workaround, but there should be a better way
843 fn walk_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) {
850 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
851 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
852 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
853 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
854 Slice(before, slice, after) => {
855 before.iter().chain(slice.iter()).chain(after.iter()).for_each(|p| p.walk_(it))
860 /// Walk the pattern in left-to-right order.
862 /// If `it(pat)` returns `false`, the children are not visited.
863 pub fn walk(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) {
867 /// Walk the pattern in left-to-right order.
869 /// If you always want to recurse, prefer this method over `walk`.
870 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
878 /// A single field in a struct pattern.
880 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
881 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
882 /// except `is_shorthand` is true.
883 #[derive(Debug, HashStable_Generic)]
884 pub struct FieldPat<'hir> {
885 #[stable_hasher(ignore)]
887 /// The identifier for the field.
888 #[stable_hasher(project(name))]
890 /// The pattern the field is destructured to.
891 pub pat: &'hir Pat<'hir>,
892 pub is_shorthand: bool,
896 /// Explicit binding annotations given in the HIR for a binding. Note
897 /// that this is not the final binding *mode* that we infer after type
899 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
900 pub enum BindingAnnotation {
901 /// No binding annotation given: this means that the final binding mode
902 /// will depend on whether we have skipped through a `&` reference
903 /// when matching. For example, the `x` in `Some(x)` will have binding
904 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
905 /// ultimately be inferred to be by-reference.
907 /// Note that implicit reference skipping is not implemented yet (#42640).
910 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
913 /// Annotated as `ref`, like `ref x`
916 /// Annotated as `ref mut x`.
920 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
926 impl fmt::Display for RangeEnd {
927 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
928 f.write_str(match self {
929 RangeEnd::Included => "..=",
930 RangeEnd::Excluded => "..",
935 #[derive(Debug, HashStable_Generic)]
936 pub enum PatKind<'hir> {
937 /// Represents a wildcard pattern (i.e., `_`).
940 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
941 /// The `HirId` is the canonical ID for the variable being bound,
942 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
943 /// which is the pattern ID of the first `x`.
944 Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
946 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
947 /// The `bool` is `true` in the presence of a `..`.
948 Struct(QPath<'hir>, &'hir [FieldPat<'hir>], bool),
950 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
951 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
952 /// `0 <= position <= subpats.len()`
953 TupleStruct(QPath<'hir>, &'hir [&'hir Pat<'hir>], Option<usize>),
955 /// An or-pattern `A | B | C`.
956 /// Invariant: `pats.len() >= 2`.
957 Or(&'hir [&'hir Pat<'hir>]),
959 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
962 /// A tuple pattern (e.g., `(a, b)`).
963 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
964 /// `0 <= position <= subpats.len()`
965 Tuple(&'hir [&'hir Pat<'hir>], Option<usize>),
968 Box(&'hir Pat<'hir>),
970 /// A reference pattern (e.g., `&mut (a, b)`).
971 Ref(&'hir Pat<'hir>, Mutability),
974 Lit(&'hir Expr<'hir>),
976 /// A range pattern (e.g., `1..=2` or `1..2`).
977 Range(Option<&'hir Expr<'hir>>, Option<&'hir Expr<'hir>>, RangeEnd),
979 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
981 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
982 /// If `slice` exists, then `after` can be non-empty.
984 /// The representation for e.g., `[a, b, .., c, d]` is:
986 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
988 Slice(&'hir [&'hir Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [&'hir Pat<'hir>]),
991 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
993 /// The `+` operator (addition).
995 /// The `-` operator (subtraction).
997 /// The `*` operator (multiplication).
999 /// The `/` operator (division).
1001 /// The `%` operator (modulus).
1003 /// The `&&` operator (logical and).
1005 /// The `||` operator (logical or).
1007 /// The `^` operator (bitwise xor).
1009 /// The `&` operator (bitwise and).
1011 /// The `|` operator (bitwise or).
1013 /// The `<<` operator (shift left).
1015 /// The `>>` operator (shift right).
1017 /// The `==` operator (equality).
1019 /// The `<` operator (less than).
1021 /// The `<=` operator (less than or equal to).
1023 /// The `!=` operator (not equal to).
1025 /// The `>=` operator (greater than or equal to).
1027 /// The `>` operator (greater than).
1032 pub fn as_str(self) -> &'static str {
1034 BinOpKind::Add => "+",
1035 BinOpKind::Sub => "-",
1036 BinOpKind::Mul => "*",
1037 BinOpKind::Div => "/",
1038 BinOpKind::Rem => "%",
1039 BinOpKind::And => "&&",
1040 BinOpKind::Or => "||",
1041 BinOpKind::BitXor => "^",
1042 BinOpKind::BitAnd => "&",
1043 BinOpKind::BitOr => "|",
1044 BinOpKind::Shl => "<<",
1045 BinOpKind::Shr => ">>",
1046 BinOpKind::Eq => "==",
1047 BinOpKind::Lt => "<",
1048 BinOpKind::Le => "<=",
1049 BinOpKind::Ne => "!=",
1050 BinOpKind::Ge => ">=",
1051 BinOpKind::Gt => ">",
1055 pub fn is_lazy(self) -> bool {
1056 matches!(self, BinOpKind::And | BinOpKind::Or)
1059 pub fn is_shift(self) -> bool {
1060 matches!(self, BinOpKind::Shl | BinOpKind::Shr)
1063 pub fn is_comparison(self) -> bool {
1070 | BinOpKind::Ge => true,
1082 | BinOpKind::Shr => false,
1086 /// Returns `true` if the binary operator takes its arguments by value.
1087 pub fn is_by_value(self) -> bool {
1088 !self.is_comparison()
1092 impl Into<ast::BinOpKind> for BinOpKind {
1093 fn into(self) -> ast::BinOpKind {
1095 BinOpKind::Add => ast::BinOpKind::Add,
1096 BinOpKind::Sub => ast::BinOpKind::Sub,
1097 BinOpKind::Mul => ast::BinOpKind::Mul,
1098 BinOpKind::Div => ast::BinOpKind::Div,
1099 BinOpKind::Rem => ast::BinOpKind::Rem,
1100 BinOpKind::And => ast::BinOpKind::And,
1101 BinOpKind::Or => ast::BinOpKind::Or,
1102 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1103 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1104 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1105 BinOpKind::Shl => ast::BinOpKind::Shl,
1106 BinOpKind::Shr => ast::BinOpKind::Shr,
1107 BinOpKind::Eq => ast::BinOpKind::Eq,
1108 BinOpKind::Lt => ast::BinOpKind::Lt,
1109 BinOpKind::Le => ast::BinOpKind::Le,
1110 BinOpKind::Ne => ast::BinOpKind::Ne,
1111 BinOpKind::Ge => ast::BinOpKind::Ge,
1112 BinOpKind::Gt => ast::BinOpKind::Gt,
1117 pub type BinOp = Spanned<BinOpKind>;
1119 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1121 /// The `*` operator (deferencing).
1123 /// The `!` operator (logical negation).
1125 /// The `-` operator (negation).
1130 pub fn as_str(self) -> &'static str {
1138 /// Returns `true` if the unary operator takes its argument by value.
1139 pub fn is_by_value(self) -> bool {
1140 matches!(self, Self::Neg | Self::Not)
1145 #[derive(Debug, HashStable_Generic)]
1146 pub struct Stmt<'hir> {
1148 pub kind: StmtKind<'hir>,
1152 /// The contents of a statement.
1153 #[derive(Debug, HashStable_Generic)]
1154 pub enum StmtKind<'hir> {
1155 /// A local (`let`) binding.
1156 Local(&'hir Local<'hir>),
1158 /// An item binding.
1161 /// An expression without a trailing semi-colon (must have unit type).
1162 Expr(&'hir Expr<'hir>),
1164 /// An expression with a trailing semi-colon (may have any type).
1165 Semi(&'hir Expr<'hir>),
1168 impl<'hir> StmtKind<'hir> {
1169 pub fn attrs(&self, get_item: impl FnOnce(ItemId) -> &'hir Item<'hir>) -> &'hir [Attribute] {
1171 StmtKind::Local(ref l) => &l.attrs,
1172 StmtKind::Item(ref item_id) => &get_item(*item_id).attrs,
1173 StmtKind::Expr(ref e) | StmtKind::Semi(ref e) => &e.attrs,
1178 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1179 #[derive(Debug, HashStable_Generic)]
1180 pub struct Local<'hir> {
1181 pub pat: &'hir Pat<'hir>,
1182 /// Type annotation, if any (otherwise the type will be inferred).
1183 pub ty: Option<&'hir Ty<'hir>>,
1184 /// Initializer expression to set the value, if any.
1185 pub init: Option<&'hir Expr<'hir>>,
1189 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1190 /// desugaring. Otherwise will be `Normal`.
1191 pub source: LocalSource,
1194 /// Represents a single arm of a `match` expression, e.g.
1195 /// `<pat> (if <guard>) => <body>`.
1196 #[derive(Debug, HashStable_Generic)]
1197 pub struct Arm<'hir> {
1198 #[stable_hasher(ignore)]
1201 pub attrs: &'hir [Attribute],
1202 /// If this pattern and the optional guard matches, then `body` is evaluated.
1203 pub pat: &'hir Pat<'hir>,
1204 /// Optional guard clause.
1205 pub guard: Option<Guard<'hir>>,
1206 /// The expression the arm evaluates to if this arm matches.
1207 pub body: &'hir Expr<'hir>,
1210 #[derive(Debug, HashStable_Generic)]
1211 pub enum Guard<'hir> {
1212 If(&'hir Expr<'hir>),
1213 IfLet(&'hir Pat<'hir>, &'hir Expr<'hir>),
1216 #[derive(Debug, HashStable_Generic)]
1217 pub struct Field<'hir> {
1218 #[stable_hasher(ignore)]
1221 pub expr: &'hir Expr<'hir>,
1223 pub is_shorthand: bool,
1226 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1227 pub enum BlockCheckMode {
1229 UnsafeBlock(UnsafeSource),
1230 PushUnsafeBlock(UnsafeSource),
1231 PopUnsafeBlock(UnsafeSource),
1234 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1235 pub enum UnsafeSource {
1240 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Hash, Debug)]
1245 /// The body of a function, closure, or constant value. In the case of
1246 /// a function, the body contains not only the function body itself
1247 /// (which is an expression), but also the argument patterns, since
1248 /// those are something that the caller doesn't really care about.
1253 /// fn foo((x, y): (u32, u32)) -> u32 {
1258 /// Here, the `Body` associated with `foo()` would contain:
1260 /// - an `params` array containing the `(x, y)` pattern
1261 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1262 /// - `generator_kind` would be `None`
1264 /// All bodies have an **owner**, which can be accessed via the HIR
1265 /// map using `body_owner_def_id()`.
1267 pub struct Body<'hir> {
1268 pub params: &'hir [Param<'hir>],
1269 pub value: Expr<'hir>,
1270 pub generator_kind: Option<GeneratorKind>,
1274 pub fn id(&self) -> BodyId {
1275 BodyId { hir_id: self.value.hir_id }
1278 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1283 /// The type of source expression that caused this generator to be created.
1296 pub enum GeneratorKind {
1297 /// An explicit `async` block or the body of an async function.
1298 Async(AsyncGeneratorKind),
1300 /// A generator literal created via a `yield` inside a closure.
1304 impl fmt::Display for GeneratorKind {
1305 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1307 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1308 GeneratorKind::Gen => f.write_str("generator"),
1313 impl GeneratorKind {
1314 pub fn descr(&self) -> &'static str {
1316 GeneratorKind::Async(ask) => ask.descr(),
1317 GeneratorKind::Gen => "generator",
1322 /// In the case of a generator created as part of an async construct,
1323 /// which kind of async construct caused it to be created?
1325 /// This helps error messages but is also used to drive coercions in
1326 /// type-checking (see #60424).
1339 pub enum AsyncGeneratorKind {
1340 /// An explicit `async` block written by the user.
1343 /// An explicit `async` block written by the user.
1346 /// The `async` block generated as the body of an async function.
1350 impl fmt::Display for AsyncGeneratorKind {
1351 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1352 f.write_str(match self {
1353 AsyncGeneratorKind::Block => "`async` block",
1354 AsyncGeneratorKind::Closure => "`async` closure body",
1355 AsyncGeneratorKind::Fn => "`async fn` body",
1360 impl AsyncGeneratorKind {
1361 pub fn descr(&self) -> &'static str {
1363 AsyncGeneratorKind::Block => "`async` block",
1364 AsyncGeneratorKind::Closure => "`async` closure body",
1365 AsyncGeneratorKind::Fn => "`async fn` body",
1370 #[derive(Copy, Clone, Debug)]
1371 pub enum BodyOwnerKind {
1372 /// Functions and methods.
1378 /// Constants and associated constants.
1381 /// Initializer of a `static` item.
1385 impl BodyOwnerKind {
1386 pub fn is_fn_or_closure(self) -> bool {
1388 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1389 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1394 /// The kind of an item that requires const-checking.
1395 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1396 pub enum ConstContext {
1400 /// A `static` or `static mut`.
1403 /// A `const`, associated `const`, or other const context.
1405 /// Other contexts include:
1406 /// - Array length expressions
1407 /// - Enum discriminants
1408 /// - Const generics
1410 /// For the most part, other contexts are treated just like a regular `const`, so they are
1411 /// lumped into the same category.
1416 /// A description of this const context that can appear between backticks in an error message.
1418 /// E.g. `const` or `static mut`.
1419 pub fn keyword_name(self) -> &'static str {
1421 Self::Const => "const",
1422 Self::Static(Mutability::Not) => "static",
1423 Self::Static(Mutability::Mut) => "static mut",
1424 Self::ConstFn => "const fn",
1429 /// A colloquial, trivially pluralizable description of this const context for use in error
1431 impl fmt::Display for ConstContext {
1432 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1434 Self::Const => write!(f, "constant"),
1435 Self::Static(_) => write!(f, "static"),
1436 Self::ConstFn => write!(f, "constant function"),
1442 pub type Lit = Spanned<LitKind>;
1444 /// A constant (expression) that's not an item or associated item,
1445 /// but needs its own `DefId` for type-checking, const-eval, etc.
1446 /// These are usually found nested inside types (e.g., array lengths)
1447 /// or expressions (e.g., repeat counts), and also used to define
1448 /// explicit discriminant values for enum variants.
1449 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1450 pub struct AnonConst {
1457 pub struct Expr<'hir> {
1459 pub kind: ExprKind<'hir>,
1465 pub fn precedence(&self) -> ExprPrecedence {
1467 ExprKind::Box(_) => ExprPrecedence::Box,
1468 ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1469 ExprKind::Array(_) => ExprPrecedence::Array,
1470 ExprKind::Call(..) => ExprPrecedence::Call,
1471 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1472 ExprKind::Tup(_) => ExprPrecedence::Tup,
1473 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1474 ExprKind::Unary(..) => ExprPrecedence::Unary,
1475 ExprKind::Lit(_) => ExprPrecedence::Lit,
1476 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1477 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1478 ExprKind::If(..) => ExprPrecedence::If,
1479 ExprKind::Loop(..) => ExprPrecedence::Loop,
1480 ExprKind::Match(..) => ExprPrecedence::Match,
1481 ExprKind::Closure(..) => ExprPrecedence::Closure,
1482 ExprKind::Block(..) => ExprPrecedence::Block,
1483 ExprKind::Assign(..) => ExprPrecedence::Assign,
1484 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1485 ExprKind::Field(..) => ExprPrecedence::Field,
1486 ExprKind::Index(..) => ExprPrecedence::Index,
1487 ExprKind::Path(..) => ExprPrecedence::Path,
1488 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1489 ExprKind::Break(..) => ExprPrecedence::Break,
1490 ExprKind::Continue(..) => ExprPrecedence::Continue,
1491 ExprKind::Ret(..) => ExprPrecedence::Ret,
1492 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1493 ExprKind::LlvmInlineAsm(..) => ExprPrecedence::InlineAsm,
1494 ExprKind::Struct(..) => ExprPrecedence::Struct,
1495 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1496 ExprKind::Yield(..) => ExprPrecedence::Yield,
1497 ExprKind::Err => ExprPrecedence::Err,
1501 // Whether this looks like a place expr, without checking for deref
1503 // This will return `true` in some potentially surprising cases such as
1504 // `CONSTANT.field`.
1505 pub fn is_syntactic_place_expr(&self) -> bool {
1506 self.is_place_expr(|_| true)
1509 /// Whether this is a place expression.
1511 /// `allow_projections_from` should return `true` if indexing a field or index expression based
1512 /// on the given expression should be considered a place expression.
1513 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1515 ExprKind::Path(QPath::Resolved(_, ref path)) => {
1516 matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static, _) | Res::Err)
1519 // Type ascription inherits its place expression kind from its
1521 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1522 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1524 ExprKind::Unary(UnOp::Deref, _) => true,
1526 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1527 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1530 // Lang item paths cannot currently be local variables or statics.
1531 ExprKind::Path(QPath::LangItem(..)) => false,
1533 // Partially qualified paths in expressions can only legally
1534 // refer to associated items which are always rvalues.
1535 ExprKind::Path(QPath::TypeRelative(..))
1536 | ExprKind::Call(..)
1537 | ExprKind::MethodCall(..)
1538 | ExprKind::Struct(..)
1541 | ExprKind::Match(..)
1542 | ExprKind::Closure(..)
1543 | ExprKind::Block(..)
1544 | ExprKind::Repeat(..)
1545 | ExprKind::Array(..)
1546 | ExprKind::Break(..)
1547 | ExprKind::Continue(..)
1549 | ExprKind::Loop(..)
1550 | ExprKind::Assign(..)
1551 | ExprKind::InlineAsm(..)
1552 | ExprKind::LlvmInlineAsm(..)
1553 | ExprKind::AssignOp(..)
1555 | ExprKind::ConstBlock(..)
1556 | ExprKind::Unary(..)
1558 | ExprKind::AddrOf(..)
1559 | ExprKind::Binary(..)
1560 | ExprKind::Yield(..)
1561 | ExprKind::Cast(..)
1562 | ExprKind::DropTemps(..)
1563 | ExprKind::Err => false,
1567 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1568 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1569 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1570 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1571 /// beyond remembering to call this function before doing analysis on it.
1572 pub fn peel_drop_temps(&self) -> &Self {
1573 let mut expr = self;
1574 while let ExprKind::DropTemps(inner) = &expr.kind {
1580 pub fn peel_blocks(&self) -> &Self {
1581 let mut expr = self;
1582 while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind {
1588 pub fn can_have_side_effects(&self) -> bool {
1589 match self.peel_drop_temps().kind {
1590 ExprKind::Path(_) | ExprKind::Lit(_) => false,
1591 ExprKind::Type(base, _)
1592 | ExprKind::Unary(_, base)
1593 | ExprKind::Field(base, _)
1594 | ExprKind::Index(base, _)
1595 | ExprKind::AddrOf(.., base)
1596 | ExprKind::Cast(base, _) => {
1597 // This isn't exactly true for `Index` and all `Unnary`, but we are using this
1598 // method exclusively for diagnostics and there's a *cultural* pressure against
1599 // them being used only for its side-effects.
1600 base.can_have_side_effects()
1602 ExprKind::Struct(_, fields, init) => fields
1604 .map(|field| field.expr)
1605 .chain(init.into_iter())
1606 .all(|e| e.can_have_side_effects()),
1608 ExprKind::Array(args)
1609 | ExprKind::Tup(args)
1613 ExprKind::Path(QPath::Resolved(
1615 Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. },
1620 ) => args.iter().all(|arg| arg.can_have_side_effects()),
1622 | ExprKind::Match(..)
1623 | ExprKind::MethodCall(..)
1624 | ExprKind::Call(..)
1625 | ExprKind::Closure(..)
1626 | ExprKind::Block(..)
1627 | ExprKind::Repeat(..)
1628 | ExprKind::Break(..)
1629 | ExprKind::Continue(..)
1631 | ExprKind::Loop(..)
1632 | ExprKind::Assign(..)
1633 | ExprKind::InlineAsm(..)
1634 | ExprKind::LlvmInlineAsm(..)
1635 | ExprKind::AssignOp(..)
1636 | ExprKind::ConstBlock(..)
1638 | ExprKind::Binary(..)
1639 | ExprKind::Yield(..)
1640 | ExprKind::DropTemps(..)
1641 | ExprKind::Err => true,
1646 /// Checks if the specified expression is a built-in range literal.
1647 /// (See: `LoweringContext::lower_expr()`).
1648 pub fn is_range_literal(expr: &Expr<'_>) -> bool {
1650 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1651 ExprKind::Struct(ref qpath, _, _) => matches!(
1656 | LangItem::RangeFrom
1657 | LangItem::RangeFull
1658 | LangItem::RangeToInclusive,
1663 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1664 ExprKind::Call(ref func, _) => {
1665 matches!(func.kind, ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, _)))
1672 #[derive(Debug, HashStable_Generic)]
1673 pub enum ExprKind<'hir> {
1674 /// A `box x` expression.
1675 Box(&'hir Expr<'hir>),
1676 /// Allow anonymous constants from an inline `const` block
1677 ConstBlock(AnonConst),
1678 /// An array (e.g., `[a, b, c, d]`).
1679 Array(&'hir [Expr<'hir>]),
1680 /// A function call.
1682 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1683 /// and the second field is the list of arguments.
1684 /// This also represents calling the constructor of
1685 /// tuple-like ADTs such as tuple structs and enum variants.
1686 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1687 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1689 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1690 /// (within the angle brackets).
1691 /// The first element of the vector of `Expr`s is the expression that evaluates
1692 /// to the object on which the method is being called on (the receiver),
1693 /// and the remaining elements are the rest of the arguments.
1694 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1695 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1696 /// The final `Span` represents the span of the function and arguments
1697 /// (e.g. `foo::<Bar, Baz>(a, b, c, d)` in `x.foo::<Bar, Baz>(a, b, c, d)`
1699 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1700 /// the `hir_id` of the `MethodCall` node itself.
1702 /// [`type_dependent_def_id`]: ../ty/struct.TypeckResults.html#method.type_dependent_def_id
1703 MethodCall(&'hir PathSegment<'hir>, Span, &'hir [Expr<'hir>], Span),
1704 /// A tuple (e.g., `(a, b, c, d)`).
1705 Tup(&'hir [Expr<'hir>]),
1706 /// A binary operation (e.g., `a + b`, `a * b`).
1707 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1708 /// A unary operation (e.g., `!x`, `*x`).
1709 Unary(UnOp, &'hir Expr<'hir>),
1710 /// A literal (e.g., `1`, `"foo"`).
1712 /// A cast (e.g., `foo as f64`).
1713 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1714 /// A type reference (e.g., `Foo`).
1715 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1716 /// Wraps the expression in a terminating scope.
1717 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1719 /// This construct only exists to tweak the drop order in HIR lowering.
1720 /// An example of that is the desugaring of `for` loops.
1721 DropTemps(&'hir Expr<'hir>),
1722 /// An `if` block, with an optional else block.
1724 /// I.e., `if <expr> { <expr> } else { <expr> }`.
1725 If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
1726 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1728 /// I.e., `'label: loop { <block> }`.
1730 /// The `Span` is the loop header (`for x in y`/`while let pat = expr`).
1731 Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span),
1732 /// A `match` block, with a source that indicates whether or not it is
1733 /// the result of a desugaring, and if so, which kind.
1734 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1735 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1737 /// The `Span` is the argument block `|...|`.
1739 /// This may also be a generator literal or an `async block` as indicated by the
1740 /// `Option<Movability>`.
1741 Closure(CaptureBy, &'hir FnDecl<'hir>, BodyId, Span, Option<Movability>),
1742 /// A block (e.g., `'label: { ... }`).
1743 Block(&'hir Block<'hir>, Option<Label>),
1745 /// An assignment (e.g., `a = foo()`).
1746 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1747 /// An assignment with an operator.
1750 AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1751 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1752 Field(&'hir Expr<'hir>, Ident),
1753 /// An indexing operation (`foo[2]`).
1754 Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1756 /// Path to a definition, possibly containing lifetime or type parameters.
1759 /// A referencing operation (i.e., `&a` or `&mut a`).
1760 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1761 /// A `break`, with an optional label to break.
1762 Break(Destination, Option<&'hir Expr<'hir>>),
1763 /// A `continue`, with an optional label.
1764 Continue(Destination),
1765 /// A `return`, with an optional value to be returned.
1766 Ret(Option<&'hir Expr<'hir>>),
1768 /// Inline assembly (from `asm!`), with its outputs and inputs.
1769 InlineAsm(&'hir InlineAsm<'hir>),
1770 /// Inline assembly (from `llvm_asm!`), with its outputs and inputs.
1771 LlvmInlineAsm(&'hir LlvmInlineAsm<'hir>),
1773 /// A struct or struct-like variant literal expression.
1775 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1776 /// where `base` is the `Option<Expr>`.
1777 Struct(&'hir QPath<'hir>, &'hir [Field<'hir>], Option<&'hir Expr<'hir>>),
1779 /// An array literal constructed from one repeated element.
1781 /// E.g., `[1; 5]`. The first expression is the element
1782 /// to be repeated; the second is the number of times to repeat it.
1783 Repeat(&'hir Expr<'hir>, AnonConst),
1785 /// A suspension point for generators (i.e., `yield <expr>`).
1786 Yield(&'hir Expr<'hir>, YieldSource),
1788 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1792 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1794 /// To resolve the path to a `DefId`, call [`qpath_res`].
1796 /// [`qpath_res`]: ../rustc_middle/ty/struct.TypeckResults.html#method.qpath_res
1797 #[derive(Debug, HashStable_Generic)]
1798 pub enum QPath<'hir> {
1799 /// Path to a definition, optionally "fully-qualified" with a `Self`
1800 /// type, if the path points to an associated item in a trait.
1802 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1803 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1804 /// even though they both have the same two-segment `Clone::clone` `Path`.
1805 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
1807 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1808 /// Will be resolved by type-checking to an associated item.
1810 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1811 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1812 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1813 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
1815 /// Reference to a `#[lang = "foo"]` item.
1816 LangItem(LangItem, Span),
1819 impl<'hir> QPath<'hir> {
1820 /// Returns the span of this `QPath`.
1821 pub fn span(&self) -> Span {
1823 QPath::Resolved(_, path) => path.span,
1824 QPath::TypeRelative(_, ps) => ps.ident.span,
1825 QPath::LangItem(_, span) => span,
1829 /// Returns the span of the qself of this `QPath`. For example, `()` in
1830 /// `<() as Trait>::method`.
1831 pub fn qself_span(&self) -> Span {
1833 QPath::Resolved(_, path) => path.span,
1834 QPath::TypeRelative(qself, _) => qself.span,
1835 QPath::LangItem(_, span) => span,
1839 /// Returns the span of the last segment of this `QPath`. For example, `method` in
1840 /// `<() as Trait>::method`.
1841 pub fn last_segment_span(&self) -> Span {
1843 QPath::Resolved(_, path) => path.segments.last().unwrap().ident.span,
1844 QPath::TypeRelative(_, segment) => segment.ident.span,
1845 QPath::LangItem(_, span) => span,
1850 /// Hints at the original code for a let statement.
1851 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1852 pub enum LocalSource {
1853 /// A `match _ { .. }`.
1855 /// A desugared `for _ in _ { .. }` loop.
1857 /// When lowering async functions, we create locals within the `async move` so that
1858 /// all parameters are dropped after the future is polled.
1860 /// ```ignore (pseudo-Rust)
1861 /// async fn foo(<pattern> @ x: Type) {
1863 /// let <pattern> = x;
1868 /// A desugared `<expr>.await`.
1870 /// A desugared `expr = expr`, where the LHS is a tuple, struct or array.
1871 /// The span is that of the `=` sign.
1872 AssignDesugar(Span),
1875 /// Hints at the original code for a `match _ { .. }`.
1876 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
1877 #[derive(HashStable_Generic)]
1878 pub enum MatchSource {
1879 /// A `match _ { .. }`.
1881 /// An `if let _ = _ { .. }` (optionally with `else { .. }`).
1882 IfLetDesugar { contains_else_clause: bool },
1883 /// An `if let _ = _ => { .. }` match guard.
1885 /// A `while _ { .. }` (which was desugared to a `loop { match _ { .. } }`).
1887 /// A `while let _ = _ { .. }` (which was desugared to a
1888 /// `loop { match _ { .. } }`).
1890 /// A desugared `for _ in _ { .. }` loop.
1892 /// A desugared `?` operator.
1894 /// A desugared `<expr>.await`.
1899 pub fn name(self) -> &'static str {
1903 IfLetDesugar { .. } | IfLetGuardDesugar => "if",
1904 WhileDesugar | WhileLetDesugar => "while",
1905 ForLoopDesugar => "for",
1907 AwaitDesugar => ".await",
1912 /// The loop type that yielded an `ExprKind::Loop`.
1913 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1914 pub enum LoopSource {
1915 /// A `loop { .. }` loop.
1917 /// A `while _ { .. }` loop.
1919 /// A `while let _ = _ { .. }` loop.
1921 /// A `for _ in _ { .. }` loop.
1926 pub fn name(self) -> &'static str {
1928 LoopSource::Loop => "loop",
1929 LoopSource::While | LoopSource::WhileLet => "while",
1930 LoopSource::ForLoop => "for",
1935 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1936 pub enum LoopIdError {
1938 UnlabeledCfInWhileCondition,
1942 impl fmt::Display for LoopIdError {
1943 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1944 f.write_str(match self {
1945 LoopIdError::OutsideLoopScope => "not inside loop scope",
1946 LoopIdError::UnlabeledCfInWhileCondition => {
1947 "unlabeled control flow (break or continue) in while condition"
1949 LoopIdError::UnresolvedLabel => "label not found",
1954 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1955 pub struct Destination {
1956 // This is `Some(_)` iff there is an explicit user-specified `label
1957 pub label: Option<Label>,
1959 // These errors are caught and then reported during the diagnostics pass in
1960 // librustc_passes/loops.rs
1961 pub target_id: Result<HirId, LoopIdError>,
1964 /// The yield kind that caused an `ExprKind::Yield`.
1965 #[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
1966 pub enum YieldSource {
1967 /// An `<expr>.await`.
1968 Await { expr: Option<HirId> },
1969 /// A plain `yield`.
1974 pub fn is_await(&self) -> bool {
1976 YieldSource::Await { .. } => true,
1977 YieldSource::Yield => false,
1982 impl fmt::Display for YieldSource {
1983 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1984 f.write_str(match self {
1985 YieldSource::Await { .. } => "`await`",
1986 YieldSource::Yield => "`yield`",
1991 impl From<GeneratorKind> for YieldSource {
1992 fn from(kind: GeneratorKind) -> Self {
1994 // Guess based on the kind of the current generator.
1995 GeneratorKind::Gen => Self::Yield,
1996 GeneratorKind::Async(_) => Self::Await { expr: None },
2001 // N.B., if you change this, you'll probably want to change the corresponding
2002 // type structure in middle/ty.rs as well.
2003 #[derive(Debug, HashStable_Generic)]
2004 pub struct MutTy<'hir> {
2005 pub ty: &'hir Ty<'hir>,
2006 pub mutbl: Mutability,
2009 /// Represents a function's signature in a trait declaration,
2010 /// trait implementation, or a free function.
2011 #[derive(Debug, HashStable_Generic)]
2012 pub struct FnSig<'hir> {
2013 pub header: FnHeader,
2014 pub decl: &'hir FnDecl<'hir>,
2018 // The bodies for items are stored "out of line", in a separate
2019 // hashmap in the `Crate`. Here we just record the hir-id of the item
2020 // so it can fetched later.
2021 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
2022 pub struct TraitItemId {
2023 pub def_id: LocalDefId,
2027 pub fn hir_id(&self) -> HirId {
2028 // Items are always HIR owners.
2029 HirId::make_owner(self.def_id)
2033 /// Represents an item declaration within a trait declaration,
2034 /// possibly including a default implementation. A trait item is
2035 /// either required (meaning it doesn't have an implementation, just a
2036 /// signature) or provided (meaning it has a default implementation).
2038 pub struct TraitItem<'hir> {
2040 pub def_id: LocalDefId,
2041 pub attrs: &'hir [Attribute],
2042 pub generics: Generics<'hir>,
2043 pub kind: TraitItemKind<'hir>,
2047 impl TraitItem<'_> {
2048 pub fn hir_id(&self) -> HirId {
2049 // Items are always HIR owners.
2050 HirId::make_owner(self.def_id)
2053 pub fn trait_item_id(&self) -> TraitItemId {
2054 TraitItemId { def_id: self.def_id }
2058 /// Represents a trait method's body (or just argument names).
2059 #[derive(Encodable, Debug, HashStable_Generic)]
2060 pub enum TraitFn<'hir> {
2061 /// No default body in the trait, just a signature.
2062 Required(&'hir [Ident]),
2064 /// Both signature and body are provided in the trait.
2068 /// Represents a trait method or associated constant or type
2069 #[derive(Debug, HashStable_Generic)]
2070 pub enum TraitItemKind<'hir> {
2071 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
2072 Const(&'hir Ty<'hir>, Option<BodyId>),
2073 /// An associated function with an optional body.
2074 Fn(FnSig<'hir>, TraitFn<'hir>),
2075 /// An associated type with (possibly empty) bounds and optional concrete
2077 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
2080 // The bodies for items are stored "out of line", in a separate
2081 // hashmap in the `Crate`. Here we just record the hir-id of the item
2082 // so it can fetched later.
2083 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
2084 pub struct ImplItemId {
2085 pub def_id: LocalDefId,
2089 pub fn hir_id(&self) -> HirId {
2090 // Items are always HIR owners.
2091 HirId::make_owner(self.def_id)
2095 /// Represents anything within an `impl` block.
2097 pub struct ImplItem<'hir> {
2099 pub def_id: LocalDefId,
2100 pub vis: Visibility<'hir>,
2101 pub defaultness: Defaultness,
2102 pub attrs: &'hir [Attribute],
2103 pub generics: Generics<'hir>,
2104 pub kind: ImplItemKind<'hir>,
2109 pub fn hir_id(&self) -> HirId {
2110 // Items are always HIR owners.
2111 HirId::make_owner(self.def_id)
2114 pub fn impl_item_id(&self) -> ImplItemId {
2115 ImplItemId { def_id: self.def_id }
2119 /// Represents various kinds of content within an `impl`.
2120 #[derive(Debug, HashStable_Generic)]
2121 pub enum ImplItemKind<'hir> {
2122 /// An associated constant of the given type, set to the constant result
2123 /// of the expression.
2124 Const(&'hir Ty<'hir>, BodyId),
2125 /// An associated function implementation with the given signature and body.
2126 Fn(FnSig<'hir>, BodyId),
2127 /// An associated type.
2128 TyAlias(&'hir Ty<'hir>),
2131 impl ImplItemKind<'_> {
2132 pub fn namespace(&self) -> Namespace {
2134 ImplItemKind::TyAlias(..) => Namespace::TypeNS,
2135 ImplItemKind::Const(..) | ImplItemKind::Fn(..) => Namespace::ValueNS,
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 pub fn name_str(self) -> &'static str {
2230 PrimTy::Int(i) => i.name_str(),
2231 PrimTy::Uint(u) => u.name_str(),
2232 PrimTy::Float(f) => f.name_str(),
2233 PrimTy::Str => "str",
2234 PrimTy::Bool => "bool",
2235 PrimTy::Char => "char",
2239 pub fn name(self) -> Symbol {
2241 PrimTy::Int(i) => i.name(),
2242 PrimTy::Uint(u) => u.name(),
2243 PrimTy::Float(f) => f.name(),
2244 PrimTy::Str => sym::str,
2245 PrimTy::Bool => sym::bool,
2246 PrimTy::Char => sym::char,
2250 /// Returns the matching `PrimTy` for a `Symbol` such as "str" or "i32".
2251 /// Returns `None` if no matching type is found.
2252 pub fn from_name(name: Symbol) -> Option<Self> {
2253 let ty = match name {
2254 // any changes here should also be reflected in `PrimTy::ALL`
2255 sym::i8 => Self::Int(IntTy::I8),
2256 sym::i16 => Self::Int(IntTy::I16),
2257 sym::i32 => Self::Int(IntTy::I32),
2258 sym::i64 => Self::Int(IntTy::I64),
2259 sym::i128 => Self::Int(IntTy::I128),
2260 sym::isize => Self::Int(IntTy::Isize),
2261 sym::u8 => Self::Uint(UintTy::U8),
2262 sym::u16 => Self::Uint(UintTy::U16),
2263 sym::u32 => Self::Uint(UintTy::U32),
2264 sym::u64 => Self::Uint(UintTy::U64),
2265 sym::u128 => Self::Uint(UintTy::U128),
2266 sym::usize => Self::Uint(UintTy::Usize),
2267 sym::f32 => Self::Float(FloatTy::F32),
2268 sym::f64 => Self::Float(FloatTy::F64),
2269 sym::bool => Self::Bool,
2270 sym::char => Self::Char,
2271 sym::str => Self::Str,
2278 #[derive(Debug, HashStable_Generic)]
2279 pub struct BareFnTy<'hir> {
2280 pub unsafety: Unsafety,
2282 pub generic_params: &'hir [GenericParam<'hir>],
2283 pub decl: &'hir FnDecl<'hir>,
2284 pub param_names: &'hir [Ident],
2287 #[derive(Debug, HashStable_Generic)]
2288 pub struct OpaqueTy<'hir> {
2289 pub generics: Generics<'hir>,
2290 pub bounds: GenericBounds<'hir>,
2291 pub impl_trait_fn: Option<DefId>,
2292 pub origin: OpaqueTyOrigin,
2295 /// From whence the opaque type came.
2296 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2297 pub enum OpaqueTyOrigin {
2302 /// `let _: impl Trait = ...`
2304 /// Impl trait in type aliases, consts, statics, bounds.
2308 /// The various kinds of types recognized by the compiler.
2309 #[derive(Debug, HashStable_Generic)]
2310 pub enum TyKind<'hir> {
2311 /// A variable length slice (i.e., `[T]`).
2312 Slice(&'hir Ty<'hir>),
2313 /// A fixed length array (i.e., `[T; n]`).
2314 Array(&'hir Ty<'hir>, AnonConst),
2315 /// A raw pointer (i.e., `*const T` or `*mut T`).
2317 /// A reference (i.e., `&'a T` or `&'a mut T`).
2318 Rptr(Lifetime, MutTy<'hir>),
2319 /// A bare function (e.g., `fn(usize) -> bool`).
2320 BareFn(&'hir BareFnTy<'hir>),
2321 /// The never type (`!`).
2323 /// A tuple (`(A, B, C, D, ...)`).
2324 Tup(&'hir [Ty<'hir>]),
2325 /// A path to a type definition (`module::module::...::Type`), or an
2326 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2328 /// Type parameters may be stored in each `PathSegment`.
2330 /// A opaque type definition itself. This is currently only used for the
2331 /// `opaque type Foo: Trait` item that `impl Trait` in desugars to.
2333 /// The generic argument list contains the lifetimes (and in the future
2334 /// possibly parameters) that are actually bound on the `impl Trait`.
2335 OpaqueDef(ItemId, &'hir [GenericArg<'hir>]),
2336 /// A trait object type `Bound1 + Bound2 + Bound3`
2337 /// where `Bound` is a trait or a lifetime.
2338 TraitObject(&'hir [PolyTraitRef<'hir>], Lifetime),
2341 /// `TyKind::Infer` means the type should be inferred instead of it having been
2342 /// specified. This can appear anywhere in a type.
2344 /// Placeholder for a type that has failed to be defined.
2348 #[derive(Debug, HashStable_Generic)]
2349 pub enum InlineAsmOperand<'hir> {
2351 reg: InlineAsmRegOrRegClass,
2355 reg: InlineAsmRegOrRegClass,
2357 expr: Option<Expr<'hir>>,
2360 reg: InlineAsmRegOrRegClass,
2365 reg: InlineAsmRegOrRegClass,
2367 in_expr: Expr<'hir>,
2368 out_expr: Option<Expr<'hir>>,
2378 impl<'hir> InlineAsmOperand<'hir> {
2379 pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
2381 Self::In { reg, .. }
2382 | Self::Out { reg, .. }
2383 | Self::InOut { reg, .. }
2384 | Self::SplitInOut { reg, .. } => Some(reg),
2385 Self::Const { .. } | Self::Sym { .. } => None,
2390 #[derive(Debug, HashStable_Generic)]
2391 pub struct InlineAsm<'hir> {
2392 pub template: &'hir [InlineAsmTemplatePiece],
2393 pub operands: &'hir [(InlineAsmOperand<'hir>, Span)],
2394 pub options: InlineAsmOptions,
2395 pub line_spans: &'hir [Span],
2398 #[derive(Copy, Clone, Encodable, Decodable, Debug, Hash, HashStable_Generic, PartialEq)]
2399 pub struct LlvmInlineAsmOutput {
2400 pub constraint: Symbol,
2402 pub is_indirect: bool,
2406 // NOTE(eddyb) This is used within MIR as well, so unlike the rest of the HIR,
2407 // it needs to be `Clone` and `Decodable` and use plain `Vec<T>` instead of
2408 // arena-allocated slice.
2409 #[derive(Clone, Encodable, Decodable, Debug, Hash, HashStable_Generic, PartialEq)]
2410 pub struct LlvmInlineAsmInner {
2412 pub asm_str_style: StrStyle,
2413 pub outputs: Vec<LlvmInlineAsmOutput>,
2414 pub inputs: Vec<Symbol>,
2415 pub clobbers: Vec<Symbol>,
2417 pub alignstack: bool,
2418 pub dialect: LlvmAsmDialect,
2421 #[derive(Debug, HashStable_Generic)]
2422 pub struct LlvmInlineAsm<'hir> {
2423 pub inner: LlvmInlineAsmInner,
2424 pub outputs_exprs: &'hir [Expr<'hir>],
2425 pub inputs_exprs: &'hir [Expr<'hir>],
2428 /// Represents a parameter in a function header.
2429 #[derive(Debug, HashStable_Generic)]
2430 pub struct Param<'hir> {
2431 pub attrs: &'hir [Attribute],
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>),
2517 pub fn span(&self) -> Span {
2519 Self::DefaultReturn(span) => span,
2520 Self::Return(ref ty) => ty.span,
2525 #[derive(Encodable, Debug)]
2526 pub struct Mod<'hir> {
2527 /// A span from the first token past `{` to the last token until `}`.
2528 /// For `mod foo;`, the inner span ranges from the first token
2529 /// to the last token in the external file.
2531 pub item_ids: &'hir [ItemId],
2534 #[derive(Encodable, Debug, HashStable_Generic)]
2535 pub struct GlobalAsm {
2539 #[derive(Debug, HashStable_Generic)]
2540 pub struct EnumDef<'hir> {
2541 pub variants: &'hir [Variant<'hir>],
2544 #[derive(Debug, HashStable_Generic)]
2545 pub struct Variant<'hir> {
2546 /// Name of the variant.
2547 #[stable_hasher(project(name))]
2549 /// Attributes of the variant.
2550 pub attrs: &'hir [Attribute],
2551 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2553 /// Fields and constructor id of the variant.
2554 pub data: VariantData<'hir>,
2555 /// Explicit discriminant (e.g., `Foo = 1`).
2556 pub disr_expr: Option<AnonConst>,
2561 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2563 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2564 /// Also produced for each element of a list `use`, e.g.
2565 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2568 /// Glob import, e.g., `use foo::*`.
2571 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2572 /// an additional `use foo::{}` for performing checks such as
2573 /// unstable feature gating. May be removed in the future.
2577 /// References to traits in impls.
2579 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2580 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2581 /// trait being referred to but just a unique `HirId` that serves as a key
2582 /// within the resolution map.
2583 #[derive(Debug, HashStable_Generic)]
2584 pub struct TraitRef<'hir> {
2585 pub path: &'hir Path<'hir>,
2586 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2587 #[stable_hasher(ignore)]
2588 pub hir_ref_id: HirId,
2592 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2593 pub fn trait_def_id(&self) -> Option<DefId> {
2594 match self.path.res {
2595 Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
2597 _ => unreachable!(),
2602 #[derive(Debug, HashStable_Generic)]
2603 pub struct PolyTraitRef<'hir> {
2604 /// The `'a` in `for<'a> Foo<&'a T>`.
2605 pub bound_generic_params: &'hir [GenericParam<'hir>],
2607 /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
2608 pub trait_ref: TraitRef<'hir>,
2613 pub type Visibility<'hir> = Spanned<VisibilityKind<'hir>>;
2616 pub enum VisibilityKind<'hir> {
2619 Restricted { path: &'hir Path<'hir>, hir_id: HirId },
2623 impl VisibilityKind<'_> {
2624 pub fn is_pub(&self) -> bool {
2625 matches!(*self, VisibilityKind::Public)
2628 pub fn is_pub_restricted(&self) -> bool {
2630 VisibilityKind::Public | VisibilityKind::Inherited => false,
2631 VisibilityKind::Crate(..) | VisibilityKind::Restricted { .. } => true,
2636 #[derive(Debug, HashStable_Generic)]
2637 pub struct StructField<'hir> {
2639 #[stable_hasher(project(name))]
2641 pub vis: Visibility<'hir>,
2643 pub ty: &'hir Ty<'hir>,
2644 pub attrs: &'hir [Attribute],
2647 impl StructField<'_> {
2648 // Still necessary in couple of places
2649 pub fn is_positional(&self) -> bool {
2650 let first = self.ident.as_str().as_bytes()[0];
2651 (b'0'..=b'9').contains(&first)
2655 /// Fields and constructor IDs of enum variants and structs.
2656 #[derive(Debug, HashStable_Generic)]
2657 pub enum VariantData<'hir> {
2658 /// A struct variant.
2660 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2661 Struct(&'hir [StructField<'hir>], /* recovered */ bool),
2662 /// A tuple variant.
2664 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2665 Tuple(&'hir [StructField<'hir>], HirId),
2668 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2672 impl VariantData<'hir> {
2673 /// Return the fields of this variant.
2674 pub fn fields(&self) -> &'hir [StructField<'hir>] {
2676 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2681 /// Return the `HirId` of this variant's constructor, if it has one.
2682 pub fn ctor_hir_id(&self) -> Option<HirId> {
2684 VariantData::Struct(_, _) => None,
2685 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2690 // The bodies for items are stored "out of line", in a separate
2691 // hashmap in the `Crate`. Here we just record the hir-id of the item
2692 // so it can fetched later.
2693 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug, Hash)]
2695 pub def_id: LocalDefId,
2699 pub fn hir_id(&self) -> HirId {
2700 // Items are always HIR owners.
2701 HirId::make_owner(self.def_id)
2707 /// The name might be a dummy name in case of anonymous items
2709 pub struct Item<'hir> {
2711 pub def_id: LocalDefId,
2712 pub attrs: &'hir [Attribute],
2713 pub kind: ItemKind<'hir>,
2714 pub vis: Visibility<'hir>,
2719 pub fn hir_id(&self) -> HirId {
2720 // Items are always HIR owners.
2721 HirId::make_owner(self.def_id)
2724 pub fn item_id(&self) -> ItemId {
2725 ItemId { def_id: self.def_id }
2729 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2730 #[derive(Encodable, Decodable, HashStable_Generic)]
2737 pub fn prefix_str(&self) -> &'static str {
2739 Self::Unsafe => "unsafe ",
2745 impl fmt::Display for Unsafety {
2746 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2747 f.write_str(match *self {
2748 Self::Unsafe => "unsafe",
2749 Self::Normal => "normal",
2754 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2755 #[derive(Encodable, Decodable, HashStable_Generic)]
2756 pub enum Constness {
2761 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2762 pub struct FnHeader {
2763 pub unsafety: Unsafety,
2764 pub constness: Constness,
2765 pub asyncness: IsAsync,
2770 pub fn is_const(&self) -> bool {
2771 matches!(&self.constness, Constness::Const)
2775 #[derive(Debug, HashStable_Generic)]
2776 pub enum ItemKind<'hir> {
2777 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2779 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2780 ExternCrate(Option<Symbol>),
2782 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2786 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2787 Use(&'hir Path<'hir>, UseKind),
2789 /// A `static` item.
2790 Static(&'hir Ty<'hir>, Mutability, BodyId),
2792 Const(&'hir Ty<'hir>, BodyId),
2793 /// A function declaration.
2794 Fn(FnSig<'hir>, Generics<'hir>, BodyId),
2797 /// An external module, e.g. `extern { .. }`.
2798 ForeignMod { abi: Abi, items: &'hir [ForeignItemRef<'hir>] },
2799 /// Module-level inline assembly (from `global_asm!`).
2800 GlobalAsm(&'hir GlobalAsm),
2801 /// A type alias, e.g., `type Foo = Bar<u8>`.
2802 TyAlias(&'hir Ty<'hir>, Generics<'hir>),
2803 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2804 OpaqueTy(OpaqueTy<'hir>),
2805 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2806 Enum(EnumDef<'hir>, Generics<'hir>),
2807 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2808 Struct(VariantData<'hir>, Generics<'hir>),
2809 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2810 Union(VariantData<'hir>, Generics<'hir>),
2811 /// A trait definition.
2812 Trait(IsAuto, Unsafety, Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
2814 TraitAlias(Generics<'hir>, GenericBounds<'hir>),
2816 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2820 #[derive(Debug, HashStable_Generic)]
2821 pub struct Impl<'hir> {
2822 pub unsafety: Unsafety,
2823 pub polarity: ImplPolarity,
2824 pub defaultness: Defaultness,
2825 // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata
2826 // decoding as `Span`s cannot be decoded when a `Session` is not available.
2827 pub defaultness_span: Option<Span>,
2828 pub constness: Constness,
2829 pub generics: Generics<'hir>,
2831 /// The trait being implemented, if any.
2832 pub of_trait: Option<TraitRef<'hir>>,
2834 pub self_ty: &'hir Ty<'hir>,
2835 pub items: &'hir [ImplItemRef<'hir>],
2839 pub fn generics(&self) -> Option<&Generics<'_>> {
2841 ItemKind::Fn(_, ref generics, _)
2842 | ItemKind::TyAlias(_, ref generics)
2843 | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
2844 | ItemKind::Enum(_, ref generics)
2845 | ItemKind::Struct(_, ref generics)
2846 | ItemKind::Union(_, ref generics)
2847 | ItemKind::Trait(_, _, ref generics, _, _)
2848 | ItemKind::Impl(Impl { ref generics, .. }) => generics,
2854 /// A reference from an trait to one of its associated items. This
2855 /// contains the item's id, naturally, but also the item's name and
2856 /// some other high-level details (like whether it is an associated
2857 /// type or method, and whether it is public). This allows other
2858 /// passes to find the impl they want without loading the ID (which
2859 /// means fewer edges in the incremental compilation graph).
2860 #[derive(Encodable, Debug, HashStable_Generic)]
2861 pub struct TraitItemRef {
2862 pub id: TraitItemId,
2863 #[stable_hasher(project(name))]
2865 pub kind: AssocItemKind,
2867 pub defaultness: Defaultness,
2870 /// A reference from an impl to one of its associated items. This
2871 /// contains the item's ID, naturally, but also the item's name and
2872 /// some other high-level details (like whether it is an associated
2873 /// type or method, and whether it is public). This allows other
2874 /// passes to find the impl they want without loading the ID (which
2875 /// means fewer edges in the incremental compilation graph).
2876 #[derive(Debug, HashStable_Generic)]
2877 pub struct ImplItemRef<'hir> {
2879 #[stable_hasher(project(name))]
2881 pub kind: AssocItemKind,
2883 pub vis: Visibility<'hir>,
2884 pub defaultness: Defaultness,
2887 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2888 pub enum AssocItemKind {
2890 Fn { has_self: bool },
2894 // The bodies for items are stored "out of line", in a separate
2895 // hashmap in the `Crate`. Here we just record the hir-id of the item
2896 // so it can fetched later.
2897 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
2898 pub struct ForeignItemId {
2899 pub def_id: LocalDefId,
2902 impl ForeignItemId {
2903 pub fn hir_id(&self) -> HirId {
2904 // Items are always HIR owners.
2905 HirId::make_owner(self.def_id)
2909 /// A reference from a foreign block to one of its items. This
2910 /// contains the item's ID, naturally, but also the item's name and
2911 /// some other high-level details (like whether it is an associated
2912 /// type or method, and whether it is public). This allows other
2913 /// passes to find the impl they want without loading the ID (which
2914 /// means fewer edges in the incremental compilation graph).
2915 #[derive(Debug, HashStable_Generic)]
2916 pub struct ForeignItemRef<'hir> {
2917 pub id: ForeignItemId,
2918 #[stable_hasher(project(name))]
2921 pub vis: Visibility<'hir>,
2925 pub struct ForeignItem<'hir> {
2927 pub attrs: &'hir [Attribute],
2928 pub kind: ForeignItemKind<'hir>,
2929 pub def_id: LocalDefId,
2931 pub vis: Visibility<'hir>,
2934 impl ForeignItem<'_> {
2935 pub fn hir_id(&self) -> HirId {
2936 // Items are always HIR owners.
2937 HirId::make_owner(self.def_id)
2940 pub fn foreign_item_id(&self) -> ForeignItemId {
2941 ForeignItemId { def_id: self.def_id }
2945 /// An item within an `extern` block.
2946 #[derive(Debug, HashStable_Generic)]
2947 pub enum ForeignItemKind<'hir> {
2948 /// A foreign function.
2949 Fn(&'hir FnDecl<'hir>, &'hir [Ident], Generics<'hir>),
2950 /// A foreign static item (`static ext: u8`).
2951 Static(&'hir Ty<'hir>, Mutability),
2956 /// A variable captured by a closure.
2957 #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)]
2959 // First span where it is accessed (there can be multiple).
2963 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2964 // has length > 0 if the trait is found through an chain of imports, starting with the
2965 // import/use statement in the scope where the trait is used.
2966 #[derive(Encodable, Decodable, Clone, Debug)]
2967 pub struct TraitCandidate {
2969 pub import_ids: SmallVec<[LocalDefId; 1]>,
2972 #[derive(Copy, Clone, Debug, HashStable_Generic)]
2973 pub enum Node<'hir> {
2974 Param(&'hir Param<'hir>),
2975 Item(&'hir Item<'hir>),
2976 ForeignItem(&'hir ForeignItem<'hir>),
2977 TraitItem(&'hir TraitItem<'hir>),
2978 ImplItem(&'hir ImplItem<'hir>),
2979 Variant(&'hir Variant<'hir>),
2980 Field(&'hir StructField<'hir>),
2981 AnonConst(&'hir AnonConst),
2982 Expr(&'hir Expr<'hir>),
2983 Stmt(&'hir Stmt<'hir>),
2984 PathSegment(&'hir PathSegment<'hir>),
2986 TraitRef(&'hir TraitRef<'hir>),
2987 Binding(&'hir Pat<'hir>),
2988 Pat(&'hir Pat<'hir>),
2989 Arm(&'hir Arm<'hir>),
2990 Block(&'hir Block<'hir>),
2991 Local(&'hir Local<'hir>),
2992 MacroDef(&'hir MacroDef<'hir>),
2994 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
2995 /// with synthesized constructors.
2996 Ctor(&'hir VariantData<'hir>),
2998 Lifetime(&'hir Lifetime),
2999 GenericParam(&'hir GenericParam<'hir>),
3000 Visibility(&'hir Visibility<'hir>),
3002 Crate(&'hir CrateItem<'hir>),
3005 impl<'hir> Node<'hir> {
3006 pub fn ident(&self) -> Option<Ident> {
3008 Node::TraitItem(TraitItem { ident, .. })
3009 | Node::ImplItem(ImplItem { ident, .. })
3010 | Node::ForeignItem(ForeignItem { ident, .. })
3011 | Node::Field(StructField { ident, .. })
3012 | Node::Variant(Variant { ident, .. })
3013 | Node::MacroDef(MacroDef { ident, .. })
3014 | Node::Item(Item { ident, .. }) => Some(*ident),
3019 pub fn fn_decl(&self) -> Option<&FnDecl<'hir>> {
3021 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3022 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3023 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3024 Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
3031 pub fn body_id(&self) -> Option<BodyId> {
3033 Node::TraitItem(TraitItem {
3034 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3037 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3038 | Node::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3043 pub fn generics(&self) -> Option<&'hir Generics<'hir>> {
3045 Node::TraitItem(TraitItem { generics, .. })
3046 | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
3047 Node::Item(item) => item.kind.generics(),
3052 pub fn hir_id(&self) -> Option<HirId> {
3054 Node::Item(Item { def_id, .. })
3055 | Node::TraitItem(TraitItem { def_id, .. })
3056 | Node::ImplItem(ImplItem { def_id, .. })
3057 | Node::ForeignItem(ForeignItem { def_id, .. })
3058 | Node::MacroDef(MacroDef { def_id, .. }) => Some(HirId::make_owner(*def_id)),
3059 Node::Field(StructField { hir_id, .. })
3060 | Node::AnonConst(AnonConst { hir_id, .. })
3061 | Node::Expr(Expr { hir_id, .. })
3062 | Node::Stmt(Stmt { hir_id, .. })
3063 | Node::Ty(Ty { hir_id, .. })
3064 | Node::Binding(Pat { hir_id, .. })
3065 | Node::Pat(Pat { hir_id, .. })
3066 | Node::Arm(Arm { hir_id, .. })
3067 | Node::Block(Block { hir_id, .. })
3068 | Node::Local(Local { hir_id, .. })
3069 | Node::Lifetime(Lifetime { hir_id, .. })
3070 | Node::Param(Param { hir_id, .. })
3071 | Node::GenericParam(GenericParam { hir_id, .. }) => Some(*hir_id),
3072 Node::TraitRef(TraitRef { hir_ref_id, .. }) => Some(*hir_ref_id),
3073 Node::PathSegment(PathSegment { hir_id, .. }) => *hir_id,
3074 Node::Variant(Variant { id, .. }) => Some(*id),
3075 Node::Ctor(variant) => variant.ctor_hir_id(),
3076 Node::Crate(_) | Node::Visibility(_) => None,
3081 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3082 #[cfg(target_arch = "x86_64")]
3084 rustc_data_structures::static_assert_size!(super::Block<'static>, 48);
3085 rustc_data_structures::static_assert_size!(super::Expr<'static>, 72);
3086 rustc_data_structures::static_assert_size!(super::Pat<'static>, 88);
3087 rustc_data_structures::static_assert_size!(super::QPath<'static>, 24);
3088 rustc_data_structures::static_assert_size!(super::Ty<'static>, 72);
3090 rustc_data_structures::static_assert_size!(super::Item<'static>, 200);
3091 rustc_data_structures::static_assert_size!(super::TraitItem<'static>, 144);
3092 rustc_data_structures::static_assert_size!(super::ImplItem<'static>, 168);
3093 rustc_data_structures::static_assert_size!(super::ForeignItem<'static>, 152);