]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir/src/hir.rs
Rollup merge of #89687 - Nicholas-Baron:move_read2_abbreviated, r=Mark-Simulacrum
[rust.git] / compiler / rustc_hir / src / hir.rs
1 use crate::def::{CtorKind, DefKind, Res};
2 use crate::def_id::{DefId, CRATE_DEF_ID};
3 crate use crate::hir_id::{HirId, ItemLocalId};
4 use crate::LangItem;
5
6 use rustc_ast::util::parser::ExprPrecedence;
7 use rustc_ast::{self as ast, CrateSugar, LlvmAsmDialect};
8 use rustc_ast::{Attribute, FloatTy, IntTy, Label, LitKind, StrStyle, TraitObjectSyntax, UintTy};
9 pub use rustc_ast::{BorrowKind, ImplPolarity, IsAuto};
10 pub use rustc_ast::{CaptureBy, Movability, Mutability};
11 use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
12 use rustc_data_structures::fx::FxHashMap;
13 use rustc_index::vec::IndexVec;
14 use rustc_macros::HashStable_Generic;
15 use rustc_span::source_map::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;
21
22 use smallvec::SmallVec;
23 use std::collections::BTreeMap;
24 use std::fmt;
25
26 #[derive(Copy, Clone, Encodable, HashStable_Generic)]
27 pub struct Lifetime {
28     pub hir_id: HirId,
29     pub span: Span,
30
31     /// Either "`'a`", referring to a named lifetime definition,
32     /// or "``" (i.e., `kw::Empty`), for elision placeholders.
33     ///
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,
38 }
39
40 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
41 #[derive(HashStable_Generic)]
42 pub enum ParamName {
43     /// Some user-given name like `T` or `'x`.
44     Plain(Ident),
45
46     /// Synthetic name generated when user elided a lifetime in an impl header.
47     ///
48     /// E.g., the lifetimes in cases like these:
49     ///
50     ///     impl Foo for &u32
51     ///     impl Foo<'_> for u32
52     ///
53     /// in that case, we rewrite to
54     ///
55     ///     impl<'f> Foo for &'f u32
56     ///     impl<'f> Foo<'f> for u32
57     ///
58     /// where `'f` is something like `Fresh(0)`. The indices are
59     /// unique per impl, but not necessarily continuous.
60     Fresh(usize),
61
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.
65     Error,
66 }
67
68 impl ParamName {
69     pub fn ident(&self) -> Ident {
70         match *self {
71             ParamName::Plain(ident) => ident,
72             ParamName::Fresh(_) | ParamName::Error => {
73                 Ident::with_dummy_span(kw::UnderscoreLifetime)
74             }
75         }
76     }
77
78     pub fn normalize_to_macros_2_0(&self) -> ParamName {
79         match *self {
80             ParamName::Plain(ident) => ParamName::Plain(ident.normalize_to_macros_2_0()),
81             param_name => param_name,
82         }
83     }
84 }
85
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.
90     Param(ParamName),
91
92     /// User wrote nothing (e.g., the lifetime in `&u32`).
93     Implicit,
94
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
105     /// parameter.
106     ImplicitObjectLifetimeDefault,
107
108     /// Indicates an error during lowering (usually `'_` in wrong place)
109     /// that was already reported.
110     Error,
111
112     /// User wrote specifies `'_`.
113     Underscore,
114
115     /// User wrote `'static`.
116     Static,
117 }
118
119 impl LifetimeName {
120     pub fn ident(&self) -> Ident {
121         match *self {
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(),
128         }
129     }
130
131     pub fn is_elided(&self) -> bool {
132         match self {
133             LifetimeName::ImplicitObjectLifetimeDefault
134             | LifetimeName::Implicit
135             | LifetimeName::Underscore => true,
136
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,
143         }
144     }
145
146     fn is_static(&self) -> bool {
147         self == &LifetimeName::Static
148     }
149
150     pub fn normalize_to_macros_2_0(&self) -> LifetimeName {
151         match *self {
152             LifetimeName::Param(param_name) => {
153                 LifetimeName::Param(param_name.normalize_to_macros_2_0())
154             }
155             lifetime_name => lifetime_name,
156         }
157     }
158 }
159
160 impl fmt::Display for Lifetime {
161     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162         self.name.ident().fmt(f)
163     }
164 }
165
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())
169     }
170 }
171
172 impl Lifetime {
173     pub fn is_elided(&self) -> bool {
174         self.name.is_elided()
175     }
176
177     pub fn is_static(&self) -> bool {
178         self.name.is_static()
179     }
180 }
181
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> {
187     pub span: Span,
188     /// The resolution for the path.
189     pub res: Res,
190     /// The segments in the path: the things separated by `::`.
191     pub segments: &'hir [PathSegment<'hir>],
192 }
193
194 impl Path<'_> {
195     pub fn is_global(&self) -> bool {
196         !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
197     }
198 }
199
200 /// A segment of a path: an identifier, an optional lifetime, and a set of
201 /// types.
202 #[derive(Debug, HashStable_Generic)]
203 pub struct PathSegment<'hir> {
204     /// The identifier portion of this path segment.
205     #[stable_hasher(project(name))]
206     pub ident: Ident,
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>,
214
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
219     /// distinction.
220     pub args: Option<&'hir GenericArgs<'hir>>,
221
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,
227 }
228
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 }
233     }
234
235     pub fn invalid() -> Self {
236         Self::from_ident(Ident::invalid())
237     }
238
239     pub fn args(&self) -> &GenericArgs<'hir> {
240         if let Some(ref args) = self.args {
241             args
242         } else {
243             const DUMMY: &GenericArgs<'_> = &GenericArgs::none();
244             DUMMY
245         }
246     }
247 }
248
249 #[derive(Encodable, Debug, HashStable_Generic)]
250 pub struct ConstArg {
251     pub value: AnonConst,
252     pub span: Span,
253 }
254
255 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
256 pub enum InferKind {
257     Const,
258     Type,
259 }
260
261 impl InferKind {
262     #[inline]
263     pub fn is_type(self) -> bool {
264         matches!(self, InferKind::Type)
265     }
266 }
267
268 #[derive(Encodable, Debug, HashStable_Generic)]
269 pub struct InferArg {
270     pub hir_id: HirId,
271     pub kind: InferKind,
272     pub span: Span,
273 }
274
275 impl InferArg {
276     pub fn to_ty(&self) -> Ty<'_> {
277         Ty { kind: TyKind::Infer, span: self.span, hir_id: self.hir_id }
278     }
279 }
280
281 #[derive(Debug, HashStable_Generic)]
282 pub enum GenericArg<'hir> {
283     Lifetime(Lifetime),
284     Type(Ty<'hir>),
285     Const(ConstArg),
286     Infer(InferArg),
287 }
288
289 impl GenericArg<'_> {
290     pub fn span(&self) -> Span {
291         match self {
292             GenericArg::Lifetime(l) => l.span,
293             GenericArg::Type(t) => t.span,
294             GenericArg::Const(c) => c.span,
295             GenericArg::Infer(i) => i.span,
296         }
297     }
298
299     pub fn id(&self) -> HirId {
300         match self {
301             GenericArg::Lifetime(l) => l.hir_id,
302             GenericArg::Type(t) => t.hir_id,
303             GenericArg::Const(c) => c.value.hir_id,
304             GenericArg::Infer(i) => i.hir_id,
305         }
306     }
307
308     pub fn is_const(&self) -> bool {
309         matches!(self, GenericArg::Const(_))
310     }
311
312     pub fn is_synthetic(&self) -> bool {
313         matches!(self, GenericArg::Lifetime(lifetime) if lifetime.name.ident() == Ident::invalid())
314     }
315
316     pub fn descr(&self) -> &'static str {
317         match self {
318             GenericArg::Lifetime(_) => "lifetime",
319             GenericArg::Type(_) => "type",
320             GenericArg::Const(_) => "constant",
321             GenericArg::Infer(_) => "inferred",
322         }
323     }
324
325     pub fn to_ord(&self, feats: &rustc_feature::Features) -> ast::ParamKindOrd {
326         match self {
327             GenericArg::Lifetime(_) => ast::ParamKindOrd::Lifetime,
328             GenericArg::Type(_) => ast::ParamKindOrd::Type,
329             GenericArg::Const(_) => {
330                 ast::ParamKindOrd::Const { unordered: feats.unordered_const_ty_params() }
331             }
332             GenericArg::Infer(_) => ast::ParamKindOrd::Infer,
333         }
334     }
335 }
336
337 #[derive(Debug, HashStable_Generic)]
338 pub struct GenericArgs<'hir> {
339     /// The generic arguments for this path segment.
340     pub args: &'hir [GenericArg<'hir>],
341     /// Bindings (equality constraints) on associated types, if present.
342     /// E.g., `Foo<A = Bar>`.
343     pub bindings: &'hir [TypeBinding<'hir>],
344     /// Were arguments written in parenthesized form `Fn(T) -> U`?
345     /// This is required mostly for pretty-printing and diagnostics,
346     /// but also for changing lifetime elision rules to be "function-like".
347     pub parenthesized: bool,
348     /// The span encompassing arguments and the surrounding brackets `<>` or `()`
349     ///       Foo<A, B, AssocTy = D>           Fn(T, U, V) -> W
350     ///          ^^^^^^^^^^^^^^^^^^^             ^^^^^^^^^
351     /// Note that this may be:
352     /// - empty, if there are no generic brackets (but there may be hidden lifetimes)
353     /// - dummy, if this was generated while desugaring
354     pub span_ext: Span,
355 }
356
357 impl GenericArgs<'_> {
358     pub const fn none() -> Self {
359         Self { args: &[], bindings: &[], parenthesized: false, span_ext: DUMMY_SP }
360     }
361
362     pub fn inputs(&self) -> &[Ty<'_>] {
363         if self.parenthesized {
364             for arg in self.args {
365                 match arg {
366                     GenericArg::Lifetime(_) => {}
367                     GenericArg::Type(ref ty) => {
368                         if let TyKind::Tup(ref tys) = ty.kind {
369                             return tys;
370                         }
371                         break;
372                     }
373                     GenericArg::Const(_) => {}
374                     GenericArg::Infer(_) => {}
375                 }
376             }
377         }
378         panic!("GenericArgs::inputs: not a `Fn(T) -> U`");
379     }
380
381     #[inline]
382     pub fn has_type_params(&self) -> bool {
383         self.args.iter().any(|arg| matches!(arg, GenericArg::Type(_)))
384     }
385
386     pub fn has_err(&self) -> bool {
387         self.args.iter().any(|arg| match arg {
388             GenericArg::Type(ty) => matches!(ty.kind, TyKind::Err),
389             _ => false,
390         }) || self.bindings.iter().any(|arg| match arg.kind {
391             TypeBindingKind::Equality { ty } => matches!(ty.kind, TyKind::Err),
392             _ => false,
393         })
394     }
395
396     #[inline]
397     pub fn num_type_params(&self) -> usize {
398         self.args.iter().filter(|arg| matches!(arg, GenericArg::Type(_))).count()
399     }
400
401     #[inline]
402     pub fn num_lifetime_params(&self) -> usize {
403         self.args.iter().filter(|arg| matches!(arg, GenericArg::Lifetime(_))).count()
404     }
405
406     #[inline]
407     pub fn has_lifetime_params(&self) -> bool {
408         self.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)))
409     }
410
411     #[inline]
412     pub fn num_generic_params(&self) -> usize {
413         self.args.iter().filter(|arg| !matches!(arg, GenericArg::Lifetime(_))).count()
414     }
415
416     /// The span encompassing the text inside the surrounding brackets.
417     /// It will also include bindings if they aren't in the form `-> Ret`
418     /// Returns `None` if the span is empty (e.g. no brackets) or dummy
419     pub fn span(&self) -> Option<Span> {
420         let span_ext = self.span_ext()?;
421         Some(span_ext.with_lo(span_ext.lo() + BytePos(1)).with_hi(span_ext.hi() - BytePos(1)))
422     }
423
424     /// Returns span encompassing arguments and their surrounding `<>` or `()`
425     pub fn span_ext(&self) -> Option<Span> {
426         Some(self.span_ext).filter(|span| !span.is_empty())
427     }
428
429     pub fn is_empty(&self) -> bool {
430         self.args.is_empty()
431     }
432 }
433
434 /// A modifier on a bound, currently this is only used for `?Sized`, where the
435 /// modifier is `Maybe`. Negative bounds should also be handled here.
436 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
437 #[derive(HashStable_Generic)]
438 pub enum TraitBoundModifier {
439     None,
440     Maybe,
441     MaybeConst,
442 }
443
444 /// The AST represents all type param bounds as types.
445 /// `typeck::collect::compute_bounds` matches these against
446 /// the "special" built-in traits (see `middle::lang_items`) and
447 /// detects `Copy`, `Send` and `Sync`.
448 #[derive(Clone, Debug, HashStable_Generic)]
449 pub enum GenericBound<'hir> {
450     Trait(PolyTraitRef<'hir>, TraitBoundModifier),
451     // FIXME(davidtwco): Introduce `PolyTraitRef::LangItem`
452     LangItemTrait(LangItem, Span, HirId, &'hir GenericArgs<'hir>),
453     Outlives(Lifetime),
454 }
455
456 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
457 rustc_data_structures::static_assert_size!(GenericBound<'_>, 48);
458
459 impl GenericBound<'_> {
460     pub fn trait_ref(&self) -> Option<&TraitRef<'_>> {
461         match self {
462             GenericBound::Trait(data, _) => Some(&data.trait_ref),
463             _ => None,
464         }
465     }
466
467     pub fn span(&self) -> Span {
468         match self {
469             GenericBound::Trait(t, ..) => t.span,
470             GenericBound::LangItemTrait(_, span, ..) => *span,
471             GenericBound::Outlives(l) => l.span,
472         }
473     }
474 }
475
476 pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
477
478 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
479 pub enum LifetimeParamKind {
480     // Indicates that the lifetime definition was explicitly declared (e.g., in
481     // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
482     Explicit,
483
484     // Indicates that the lifetime definition was synthetically added
485     // as a result of an in-band lifetime usage (e.g., in
486     // `fn foo(x: &'a u8) -> &'a u8 { x }`).
487     InBand,
488
489     // Indication that the lifetime was elided (e.g., in both cases in
490     // `fn foo(x: &u8) -> &'_ u8 { x }`).
491     Elided,
492
493     // Indication that the lifetime name was somehow in error.
494     Error,
495 }
496
497 #[derive(Debug, HashStable_Generic)]
498 pub enum GenericParamKind<'hir> {
499     /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
500     Lifetime {
501         kind: LifetimeParamKind,
502     },
503     Type {
504         default: Option<&'hir Ty<'hir>>,
505         synthetic: Option<SyntheticTyParamKind>,
506     },
507     Const {
508         ty: &'hir Ty<'hir>,
509         /// Optional default value for the const generic param
510         default: Option<AnonConst>,
511     },
512 }
513
514 #[derive(Debug, HashStable_Generic)]
515 pub struct GenericParam<'hir> {
516     pub hir_id: HirId,
517     pub name: ParamName,
518     pub bounds: GenericBounds<'hir>,
519     pub span: Span,
520     pub pure_wrt_drop: bool,
521     pub kind: GenericParamKind<'hir>,
522 }
523
524 impl GenericParam<'hir> {
525     pub fn bounds_span(&self) -> Option<Span> {
526         self.bounds.iter().fold(None, |span, bound| {
527             let span = span.map(|s| s.to(bound.span())).unwrap_or_else(|| bound.span());
528
529             Some(span)
530         })
531     }
532 }
533
534 #[derive(Default)]
535 pub struct GenericParamCount {
536     pub lifetimes: usize,
537     pub types: usize,
538     pub consts: usize,
539     pub infer: usize,
540 }
541
542 /// Represents lifetimes and type parameters attached to a declaration
543 /// of a function, enum, trait, etc.
544 #[derive(Debug, HashStable_Generic)]
545 pub struct Generics<'hir> {
546     pub params: &'hir [GenericParam<'hir>],
547     pub where_clause: WhereClause<'hir>,
548     pub span: Span,
549 }
550
551 impl Generics<'hir> {
552     pub const fn empty() -> Generics<'hir> {
553         Generics {
554             params: &[],
555             where_clause: WhereClause { predicates: &[], span: DUMMY_SP },
556             span: DUMMY_SP,
557         }
558     }
559
560     pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'_>> {
561         for param in self.params {
562             if name == param.name.ident().name {
563                 return Some(param);
564             }
565         }
566         None
567     }
568
569     pub fn spans(&self) -> MultiSpan {
570         if self.params.is_empty() {
571             self.span.into()
572         } else {
573             self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
574         }
575     }
576 }
577
578 /// Synthetic type parameters are converted to another form during lowering; this allows
579 /// us to track the original form they had, and is useful for error messages.
580 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
581 #[derive(HashStable_Generic)]
582 pub enum SyntheticTyParamKind {
583     ImplTrait,
584     // Created by the `#[rustc_synthetic]` attribute.
585     FromAttr,
586 }
587
588 /// A where-clause in a definition.
589 #[derive(Debug, HashStable_Generic)]
590 pub struct WhereClause<'hir> {
591     pub predicates: &'hir [WherePredicate<'hir>],
592     // Only valid if predicates aren't empty.
593     pub span: Span,
594 }
595
596 impl WhereClause<'_> {
597     pub fn span(&self) -> Option<Span> {
598         if self.predicates.is_empty() { None } else { Some(self.span) }
599     }
600
601     /// The `WhereClause` under normal circumstances points at either the predicates or the empty
602     /// space where the `where` clause should be. Only of use for diagnostic suggestions.
603     pub fn span_for_predicates_or_empty_place(&self) -> Span {
604         self.span
605     }
606
607     /// `Span` where further predicates would be suggested, accounting for trailing commas, like
608     ///  in `fn foo<T>(t: T) where T: Foo,` so we don't suggest two trailing commas.
609     pub fn tail_span_for_suggestion(&self) -> Span {
610         let end = self.span_for_predicates_or_empty_place().shrink_to_hi();
611         self.predicates.last().map_or(end, |p| p.span()).shrink_to_hi().to(end)
612     }
613 }
614
615 /// A single predicate in a where-clause.
616 #[derive(Debug, HashStable_Generic)]
617 pub enum WherePredicate<'hir> {
618     /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
619     BoundPredicate(WhereBoundPredicate<'hir>),
620     /// A lifetime predicate (e.g., `'a: 'b + 'c`).
621     RegionPredicate(WhereRegionPredicate<'hir>),
622     /// An equality predicate (unsupported).
623     EqPredicate(WhereEqPredicate<'hir>),
624 }
625
626 impl WherePredicate<'_> {
627     pub fn span(&self) -> Span {
628         match self {
629             WherePredicate::BoundPredicate(p) => p.span,
630             WherePredicate::RegionPredicate(p) => p.span,
631             WherePredicate::EqPredicate(p) => p.span,
632         }
633     }
634 }
635
636 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
637 #[derive(Debug, HashStable_Generic)]
638 pub struct WhereBoundPredicate<'hir> {
639     pub span: Span,
640     /// Any generics from a `for` binding.
641     pub bound_generic_params: &'hir [GenericParam<'hir>],
642     /// The type being bounded.
643     pub bounded_ty: &'hir Ty<'hir>,
644     /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
645     pub bounds: GenericBounds<'hir>,
646 }
647
648 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
649 #[derive(Debug, HashStable_Generic)]
650 pub struct WhereRegionPredicate<'hir> {
651     pub span: Span,
652     pub lifetime: Lifetime,
653     pub bounds: GenericBounds<'hir>,
654 }
655
656 /// An equality predicate (e.g., `T = int`); currently unsupported.
657 #[derive(Debug, HashStable_Generic)]
658 pub struct WhereEqPredicate<'hir> {
659     pub hir_id: HirId,
660     pub span: Span,
661     pub lhs_ty: &'hir Ty<'hir>,
662     pub rhs_ty: &'hir Ty<'hir>,
663 }
664
665 /// The top-level data structure that stores the entire contents of
666 /// the crate currently being compiled.
667 ///
668 /// For more details, see the [rustc dev guide].
669 ///
670 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
671 #[derive(Debug)]
672 pub struct Crate<'hir> {
673     pub owners: IndexVec<LocalDefId, Option<OwnerNode<'hir>>>,
674     pub bodies: BTreeMap<BodyId, Body<'hir>>,
675
676     /// Map indicating what traits are in scope for places where this
677     /// is relevant; generated by resolve.
678     pub trait_map: FxHashMap<LocalDefId, FxHashMap<ItemLocalId, Box<[TraitCandidate]>>>,
679
680     /// Collected attributes from HIR nodes.
681     pub attrs: BTreeMap<HirId, &'hir [Attribute]>,
682 }
683
684 impl Crate<'hir> {
685     pub fn module(&self) -> &'hir Mod<'hir> {
686         if let Some(OwnerNode::Crate(m)) = self.owners[CRATE_DEF_ID] { m } else { panic!() }
687     }
688
689     pub fn item(&self, id: ItemId) -> &'hir Item<'hir> {
690         self.owners[id.def_id].as_ref().unwrap().expect_item()
691     }
692
693     pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> {
694         self.owners[id.def_id].as_ref().unwrap().expect_trait_item()
695     }
696
697     pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> {
698         self.owners[id.def_id].as_ref().unwrap().expect_impl_item()
699     }
700
701     pub fn foreign_item(&self, id: ForeignItemId) -> &'hir ForeignItem<'hir> {
702         self.owners[id.def_id].as_ref().unwrap().expect_foreign_item()
703     }
704
705     pub fn body(&self, id: BodyId) -> &Body<'hir> {
706         &self.bodies[&id]
707     }
708 }
709
710 /// A block of statements `{ .. }`, which may have a label (in this case the
711 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
712 /// the `rules` being anything but `DefaultBlock`.
713 #[derive(Debug, HashStable_Generic)]
714 pub struct Block<'hir> {
715     /// Statements in a block.
716     pub stmts: &'hir [Stmt<'hir>],
717     /// An expression at the end of the block
718     /// without a semicolon, if any.
719     pub expr: Option<&'hir Expr<'hir>>,
720     #[stable_hasher(ignore)]
721     pub hir_id: HirId,
722     /// Distinguishes between `unsafe { ... }` and `{ ... }`.
723     pub rules: BlockCheckMode,
724     pub span: Span,
725     /// If true, then there may exist `break 'a` values that aim to
726     /// break out of this block early.
727     /// Used by `'label: {}` blocks and by `try {}` blocks.
728     pub targeted_by_break: bool,
729 }
730
731 #[derive(Debug, HashStable_Generic)]
732 pub struct Pat<'hir> {
733     #[stable_hasher(ignore)]
734     pub hir_id: HirId,
735     pub kind: PatKind<'hir>,
736     pub span: Span,
737     // Whether to use default binding modes.
738     // At present, this is false only for destructuring assignment.
739     pub default_binding_modes: bool,
740 }
741
742 impl<'hir> Pat<'hir> {
743     // FIXME(#19596) this is a workaround, but there should be a better way
744     fn walk_short_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) -> bool {
745         if !it(self) {
746             return false;
747         }
748
749         use PatKind::*;
750         match self.kind {
751             Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
752             Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
753             Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
754             TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
755             Slice(before, slice, after) => {
756                 before.iter().chain(slice).chain(after.iter()).all(|p| p.walk_short_(it))
757             }
758         }
759     }
760
761     /// Walk the pattern in left-to-right order,
762     /// short circuiting (with `.all(..)`) if `false` is returned.
763     ///
764     /// Note that when visiting e.g. `Tuple(ps)`,
765     /// if visiting `ps[0]` returns `false`,
766     /// then `ps[1]` will not be visited.
767     pub fn walk_short(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) -> bool {
768         self.walk_short_(&mut it)
769     }
770
771     // FIXME(#19596) this is a workaround, but there should be a better way
772     fn walk_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) {
773         if !it(self) {
774             return;
775         }
776
777         use PatKind::*;
778         match self.kind {
779             Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
780             Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
781             Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
782             TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
783             Slice(before, slice, after) => {
784                 before.iter().chain(slice).chain(after.iter()).for_each(|p| p.walk_(it))
785             }
786         }
787     }
788
789     /// Walk the pattern in left-to-right order.
790     ///
791     /// If `it(pat)` returns `false`, the children are not visited.
792     pub fn walk(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) {
793         self.walk_(&mut it)
794     }
795
796     /// Walk the pattern in left-to-right order.
797     ///
798     /// If you always want to recurse, prefer this method over `walk`.
799     pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
800         self.walk(|p| {
801             it(p);
802             true
803         })
804     }
805 }
806
807 /// A single field in a struct pattern.
808 ///
809 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
810 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
811 /// except `is_shorthand` is true.
812 #[derive(Debug, HashStable_Generic)]
813 pub struct PatField<'hir> {
814     #[stable_hasher(ignore)]
815     pub hir_id: HirId,
816     /// The identifier for the field.
817     #[stable_hasher(project(name))]
818     pub ident: Ident,
819     /// The pattern the field is destructured to.
820     pub pat: &'hir Pat<'hir>,
821     pub is_shorthand: bool,
822     pub span: Span,
823 }
824
825 /// Explicit binding annotations given in the HIR for a binding. Note
826 /// that this is not the final binding *mode* that we infer after type
827 /// inference.
828 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
829 pub enum BindingAnnotation {
830     /// No binding annotation given: this means that the final binding mode
831     /// will depend on whether we have skipped through a `&` reference
832     /// when matching. For example, the `x` in `Some(x)` will have binding
833     /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
834     /// ultimately be inferred to be by-reference.
835     ///
836     /// Note that implicit reference skipping is not implemented yet (#42640).
837     Unannotated,
838
839     /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
840     Mutable,
841
842     /// Annotated as `ref`, like `ref x`
843     Ref,
844
845     /// Annotated as `ref mut x`.
846     RefMut,
847 }
848
849 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
850 pub enum RangeEnd {
851     Included,
852     Excluded,
853 }
854
855 impl fmt::Display for RangeEnd {
856     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
857         f.write_str(match self {
858             RangeEnd::Included => "..=",
859             RangeEnd::Excluded => "..",
860         })
861     }
862 }
863
864 #[derive(Debug, HashStable_Generic)]
865 pub enum PatKind<'hir> {
866     /// Represents a wildcard pattern (i.e., `_`).
867     Wild,
868
869     /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
870     /// The `HirId` is the canonical ID for the variable being bound,
871     /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
872     /// which is the pattern ID of the first `x`.
873     Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
874
875     /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
876     /// The `bool` is `true` in the presence of a `..`.
877     Struct(QPath<'hir>, &'hir [PatField<'hir>], bool),
878
879     /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
880     /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
881     /// `0 <= position <= subpats.len()`
882     TupleStruct(QPath<'hir>, &'hir [Pat<'hir>], Option<usize>),
883
884     /// An or-pattern `A | B | C`.
885     /// Invariant: `pats.len() >= 2`.
886     Or(&'hir [Pat<'hir>]),
887
888     /// A path pattern for a unit struct/variant or a (maybe-associated) constant.
889     Path(QPath<'hir>),
890
891     /// A tuple pattern (e.g., `(a, b)`).
892     /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
893     /// `0 <= position <= subpats.len()`
894     Tuple(&'hir [Pat<'hir>], Option<usize>),
895
896     /// A `box` pattern.
897     Box(&'hir Pat<'hir>),
898
899     /// A reference pattern (e.g., `&mut (a, b)`).
900     Ref(&'hir Pat<'hir>, Mutability),
901
902     /// A literal.
903     Lit(&'hir Expr<'hir>),
904
905     /// A range pattern (e.g., `1..=2` or `1..2`).
906     Range(Option<&'hir Expr<'hir>>, Option<&'hir Expr<'hir>>, RangeEnd),
907
908     /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
909     ///
910     /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
911     /// If `slice` exists, then `after` can be non-empty.
912     ///
913     /// The representation for e.g., `[a, b, .., c, d]` is:
914     /// ```
915     /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
916     /// ```
917     Slice(&'hir [Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [Pat<'hir>]),
918 }
919
920 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
921 pub enum BinOpKind {
922     /// The `+` operator (addition).
923     Add,
924     /// The `-` operator (subtraction).
925     Sub,
926     /// The `*` operator (multiplication).
927     Mul,
928     /// The `/` operator (division).
929     Div,
930     /// The `%` operator (modulus).
931     Rem,
932     /// The `&&` operator (logical and).
933     And,
934     /// The `||` operator (logical or).
935     Or,
936     /// The `^` operator (bitwise xor).
937     BitXor,
938     /// The `&` operator (bitwise and).
939     BitAnd,
940     /// The `|` operator (bitwise or).
941     BitOr,
942     /// The `<<` operator (shift left).
943     Shl,
944     /// The `>>` operator (shift right).
945     Shr,
946     /// The `==` operator (equality).
947     Eq,
948     /// The `<` operator (less than).
949     Lt,
950     /// The `<=` operator (less than or equal to).
951     Le,
952     /// The `!=` operator (not equal to).
953     Ne,
954     /// The `>=` operator (greater than or equal to).
955     Ge,
956     /// The `>` operator (greater than).
957     Gt,
958 }
959
960 impl BinOpKind {
961     pub fn as_str(self) -> &'static str {
962         match self {
963             BinOpKind::Add => "+",
964             BinOpKind::Sub => "-",
965             BinOpKind::Mul => "*",
966             BinOpKind::Div => "/",
967             BinOpKind::Rem => "%",
968             BinOpKind::And => "&&",
969             BinOpKind::Or => "||",
970             BinOpKind::BitXor => "^",
971             BinOpKind::BitAnd => "&",
972             BinOpKind::BitOr => "|",
973             BinOpKind::Shl => "<<",
974             BinOpKind::Shr => ">>",
975             BinOpKind::Eq => "==",
976             BinOpKind::Lt => "<",
977             BinOpKind::Le => "<=",
978             BinOpKind::Ne => "!=",
979             BinOpKind::Ge => ">=",
980             BinOpKind::Gt => ">",
981         }
982     }
983
984     pub fn is_lazy(self) -> bool {
985         matches!(self, BinOpKind::And | BinOpKind::Or)
986     }
987
988     pub fn is_shift(self) -> bool {
989         matches!(self, BinOpKind::Shl | BinOpKind::Shr)
990     }
991
992     pub fn is_comparison(self) -> bool {
993         match self {
994             BinOpKind::Eq
995             | BinOpKind::Lt
996             | BinOpKind::Le
997             | BinOpKind::Ne
998             | BinOpKind::Gt
999             | BinOpKind::Ge => true,
1000             BinOpKind::And
1001             | BinOpKind::Or
1002             | BinOpKind::Add
1003             | BinOpKind::Sub
1004             | BinOpKind::Mul
1005             | BinOpKind::Div
1006             | BinOpKind::Rem
1007             | BinOpKind::BitXor
1008             | BinOpKind::BitAnd
1009             | BinOpKind::BitOr
1010             | BinOpKind::Shl
1011             | BinOpKind::Shr => false,
1012         }
1013     }
1014
1015     /// Returns `true` if the binary operator takes its arguments by value.
1016     pub fn is_by_value(self) -> bool {
1017         !self.is_comparison()
1018     }
1019 }
1020
1021 impl Into<ast::BinOpKind> for BinOpKind {
1022     fn into(self) -> ast::BinOpKind {
1023         match self {
1024             BinOpKind::Add => ast::BinOpKind::Add,
1025             BinOpKind::Sub => ast::BinOpKind::Sub,
1026             BinOpKind::Mul => ast::BinOpKind::Mul,
1027             BinOpKind::Div => ast::BinOpKind::Div,
1028             BinOpKind::Rem => ast::BinOpKind::Rem,
1029             BinOpKind::And => ast::BinOpKind::And,
1030             BinOpKind::Or => ast::BinOpKind::Or,
1031             BinOpKind::BitXor => ast::BinOpKind::BitXor,
1032             BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1033             BinOpKind::BitOr => ast::BinOpKind::BitOr,
1034             BinOpKind::Shl => ast::BinOpKind::Shl,
1035             BinOpKind::Shr => ast::BinOpKind::Shr,
1036             BinOpKind::Eq => ast::BinOpKind::Eq,
1037             BinOpKind::Lt => ast::BinOpKind::Lt,
1038             BinOpKind::Le => ast::BinOpKind::Le,
1039             BinOpKind::Ne => ast::BinOpKind::Ne,
1040             BinOpKind::Ge => ast::BinOpKind::Ge,
1041             BinOpKind::Gt => ast::BinOpKind::Gt,
1042         }
1043     }
1044 }
1045
1046 pub type BinOp = Spanned<BinOpKind>;
1047
1048 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1049 pub enum UnOp {
1050     /// The `*` operator (deferencing).
1051     Deref,
1052     /// The `!` operator (logical negation).
1053     Not,
1054     /// The `-` operator (negation).
1055     Neg,
1056 }
1057
1058 impl UnOp {
1059     pub fn as_str(self) -> &'static str {
1060         match self {
1061             Self::Deref => "*",
1062             Self::Not => "!",
1063             Self::Neg => "-",
1064         }
1065     }
1066
1067     /// Returns `true` if the unary operator takes its argument by value.
1068     pub fn is_by_value(self) -> bool {
1069         matches!(self, Self::Neg | Self::Not)
1070     }
1071 }
1072
1073 /// A statement.
1074 #[derive(Debug, HashStable_Generic)]
1075 pub struct Stmt<'hir> {
1076     pub hir_id: HirId,
1077     pub kind: StmtKind<'hir>,
1078     pub span: Span,
1079 }
1080
1081 /// The contents of a statement.
1082 #[derive(Debug, HashStable_Generic)]
1083 pub enum StmtKind<'hir> {
1084     /// A local (`let`) binding.
1085     Local(&'hir Local<'hir>),
1086
1087     /// An item binding.
1088     Item(ItemId),
1089
1090     /// An expression without a trailing semi-colon (must have unit type).
1091     Expr(&'hir Expr<'hir>),
1092
1093     /// An expression with a trailing semi-colon (may have any type).
1094     Semi(&'hir Expr<'hir>),
1095 }
1096
1097 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1098 #[derive(Debug, HashStable_Generic)]
1099 pub struct Local<'hir> {
1100     pub pat: &'hir Pat<'hir>,
1101     /// Type annotation, if any (otherwise the type will be inferred).
1102     pub ty: Option<&'hir Ty<'hir>>,
1103     /// Initializer expression to set the value, if any.
1104     pub init: Option<&'hir Expr<'hir>>,
1105     pub hir_id: HirId,
1106     pub span: Span,
1107     /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1108     /// desugaring. Otherwise will be `Normal`.
1109     pub source: LocalSource,
1110 }
1111
1112 /// Represents a single arm of a `match` expression, e.g.
1113 /// `<pat> (if <guard>) => <body>`.
1114 #[derive(Debug, HashStable_Generic)]
1115 pub struct Arm<'hir> {
1116     #[stable_hasher(ignore)]
1117     pub hir_id: HirId,
1118     pub span: Span,
1119     /// If this pattern and the optional guard matches, then `body` is evaluated.
1120     pub pat: &'hir Pat<'hir>,
1121     /// Optional guard clause.
1122     pub guard: Option<Guard<'hir>>,
1123     /// The expression the arm evaluates to if this arm matches.
1124     pub body: &'hir Expr<'hir>,
1125 }
1126
1127 #[derive(Debug, HashStable_Generic)]
1128 pub enum Guard<'hir> {
1129     If(&'hir Expr<'hir>),
1130     // FIXME use ExprKind::Let for this.
1131     IfLet(&'hir Pat<'hir>, &'hir Expr<'hir>),
1132 }
1133
1134 #[derive(Debug, HashStable_Generic)]
1135 pub struct ExprField<'hir> {
1136     #[stable_hasher(ignore)]
1137     pub hir_id: HirId,
1138     pub ident: Ident,
1139     pub expr: &'hir Expr<'hir>,
1140     pub span: Span,
1141     pub is_shorthand: bool,
1142 }
1143
1144 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1145 pub enum BlockCheckMode {
1146     DefaultBlock,
1147     UnsafeBlock(UnsafeSource),
1148 }
1149
1150 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1151 pub enum UnsafeSource {
1152     CompilerGenerated,
1153     UserProvided,
1154 }
1155
1156 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Hash, Debug)]
1157 pub struct BodyId {
1158     pub hir_id: HirId,
1159 }
1160
1161 /// The body of a function, closure, or constant value. In the case of
1162 /// a function, the body contains not only the function body itself
1163 /// (which is an expression), but also the argument patterns, since
1164 /// those are something that the caller doesn't really care about.
1165 ///
1166 /// # Examples
1167 ///
1168 /// ```
1169 /// fn foo((x, y): (u32, u32)) -> u32 {
1170 ///     x + y
1171 /// }
1172 /// ```
1173 ///
1174 /// Here, the `Body` associated with `foo()` would contain:
1175 ///
1176 /// - an `params` array containing the `(x, y)` pattern
1177 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1178 /// - `generator_kind` would be `None`
1179 ///
1180 /// All bodies have an **owner**, which can be accessed via the HIR
1181 /// map using `body_owner_def_id()`.
1182 #[derive(Debug)]
1183 pub struct Body<'hir> {
1184     pub params: &'hir [Param<'hir>],
1185     pub value: Expr<'hir>,
1186     pub generator_kind: Option<GeneratorKind>,
1187 }
1188
1189 impl Body<'hir> {
1190     pub fn id(&self) -> BodyId {
1191         BodyId { hir_id: self.value.hir_id }
1192     }
1193
1194     pub fn generator_kind(&self) -> Option<GeneratorKind> {
1195         self.generator_kind
1196     }
1197 }
1198
1199 /// The type of source expression that caused this generator to be created.
1200 #[derive(
1201     Clone,
1202     PartialEq,
1203     PartialOrd,
1204     Eq,
1205     Hash,
1206     HashStable_Generic,
1207     Encodable,
1208     Decodable,
1209     Debug,
1210     Copy
1211 )]
1212 pub enum GeneratorKind {
1213     /// An explicit `async` block or the body of an async function.
1214     Async(AsyncGeneratorKind),
1215
1216     /// A generator literal created via a `yield` inside a closure.
1217     Gen,
1218 }
1219
1220 impl fmt::Display for GeneratorKind {
1221     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1222         match self {
1223             GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1224             GeneratorKind::Gen => f.write_str("generator"),
1225         }
1226     }
1227 }
1228
1229 impl GeneratorKind {
1230     pub fn descr(&self) -> &'static str {
1231         match self {
1232             GeneratorKind::Async(ask) => ask.descr(),
1233             GeneratorKind::Gen => "generator",
1234         }
1235     }
1236 }
1237
1238 /// In the case of a generator created as part of an async construct,
1239 /// which kind of async construct caused it to be created?
1240 ///
1241 /// This helps error messages but is also used to drive coercions in
1242 /// type-checking (see #60424).
1243 #[derive(
1244     Clone,
1245     PartialEq,
1246     PartialOrd,
1247     Eq,
1248     Hash,
1249     HashStable_Generic,
1250     Encodable,
1251     Decodable,
1252     Debug,
1253     Copy
1254 )]
1255 pub enum AsyncGeneratorKind {
1256     /// An explicit `async` block written by the user.
1257     Block,
1258
1259     /// An explicit `async` block written by the user.
1260     Closure,
1261
1262     /// The `async` block generated as the body of an async function.
1263     Fn,
1264 }
1265
1266 impl fmt::Display for AsyncGeneratorKind {
1267     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1268         f.write_str(match self {
1269             AsyncGeneratorKind::Block => "`async` block",
1270             AsyncGeneratorKind::Closure => "`async` closure body",
1271             AsyncGeneratorKind::Fn => "`async fn` body",
1272         })
1273     }
1274 }
1275
1276 impl AsyncGeneratorKind {
1277     pub fn descr(&self) -> &'static str {
1278         match self {
1279             AsyncGeneratorKind::Block => "`async` block",
1280             AsyncGeneratorKind::Closure => "`async` closure body",
1281             AsyncGeneratorKind::Fn => "`async fn` body",
1282         }
1283     }
1284 }
1285
1286 #[derive(Copy, Clone, Debug)]
1287 pub enum BodyOwnerKind {
1288     /// Functions and methods.
1289     Fn,
1290
1291     /// Closures
1292     Closure,
1293
1294     /// Constants and associated constants.
1295     Const,
1296
1297     /// Initializer of a `static` item.
1298     Static(Mutability),
1299 }
1300
1301 impl BodyOwnerKind {
1302     pub fn is_fn_or_closure(self) -> bool {
1303         match self {
1304             BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1305             BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1306         }
1307     }
1308 }
1309
1310 /// The kind of an item that requires const-checking.
1311 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1312 pub enum ConstContext {
1313     /// A `const fn`.
1314     ConstFn,
1315
1316     /// A `static` or `static mut`.
1317     Static(Mutability),
1318
1319     /// A `const`, associated `const`, or other const context.
1320     ///
1321     /// Other contexts include:
1322     /// - Array length expressions
1323     /// - Enum discriminants
1324     /// - Const generics
1325     ///
1326     /// For the most part, other contexts are treated just like a regular `const`, so they are
1327     /// lumped into the same category.
1328     Const,
1329 }
1330
1331 impl ConstContext {
1332     /// A description of this const context that can appear between backticks in an error message.
1333     ///
1334     /// E.g. `const` or `static mut`.
1335     pub fn keyword_name(self) -> &'static str {
1336         match self {
1337             Self::Const => "const",
1338             Self::Static(Mutability::Not) => "static",
1339             Self::Static(Mutability::Mut) => "static mut",
1340             Self::ConstFn => "const fn",
1341         }
1342     }
1343 }
1344
1345 /// A colloquial, trivially pluralizable description of this const context for use in error
1346 /// messages.
1347 impl fmt::Display for ConstContext {
1348     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1349         match *self {
1350             Self::Const => write!(f, "constant"),
1351             Self::Static(_) => write!(f, "static"),
1352             Self::ConstFn => write!(f, "constant function"),
1353         }
1354     }
1355 }
1356
1357 /// A literal.
1358 pub type Lit = Spanned<LitKind>;
1359
1360 /// A constant (expression) that's not an item or associated item,
1361 /// but needs its own `DefId` for type-checking, const-eval, etc.
1362 /// These are usually found nested inside types (e.g., array lengths)
1363 /// or expressions (e.g., repeat counts), and also used to define
1364 /// explicit discriminant values for enum variants.
1365 ///
1366 /// You can check if this anon const is a default in a const param
1367 /// `const N: usize = { ... }` with `tcx.hir().opt_const_param_default_param_hir_id(..)`
1368 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1369 pub struct AnonConst {
1370     pub hir_id: HirId,
1371     pub body: BodyId,
1372 }
1373
1374 /// An expression.
1375 #[derive(Debug)]
1376 pub struct Expr<'hir> {
1377     pub hir_id: HirId,
1378     pub kind: ExprKind<'hir>,
1379     pub span: Span,
1380 }
1381
1382 impl Expr<'_> {
1383     pub fn precedence(&self) -> ExprPrecedence {
1384         match self.kind {
1385             ExprKind::Box(_) => ExprPrecedence::Box,
1386             ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1387             ExprKind::Array(_) => ExprPrecedence::Array,
1388             ExprKind::Call(..) => ExprPrecedence::Call,
1389             ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1390             ExprKind::Tup(_) => ExprPrecedence::Tup,
1391             ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1392             ExprKind::Unary(..) => ExprPrecedence::Unary,
1393             ExprKind::Lit(_) => ExprPrecedence::Lit,
1394             ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1395             ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1396             ExprKind::If(..) => ExprPrecedence::If,
1397             ExprKind::Let(..) => ExprPrecedence::Let,
1398             ExprKind::Loop(..) => ExprPrecedence::Loop,
1399             ExprKind::Match(..) => ExprPrecedence::Match,
1400             ExprKind::Closure(..) => ExprPrecedence::Closure,
1401             ExprKind::Block(..) => ExprPrecedence::Block,
1402             ExprKind::Assign(..) => ExprPrecedence::Assign,
1403             ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1404             ExprKind::Field(..) => ExprPrecedence::Field,
1405             ExprKind::Index(..) => ExprPrecedence::Index,
1406             ExprKind::Path(..) => ExprPrecedence::Path,
1407             ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1408             ExprKind::Break(..) => ExprPrecedence::Break,
1409             ExprKind::Continue(..) => ExprPrecedence::Continue,
1410             ExprKind::Ret(..) => ExprPrecedence::Ret,
1411             ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1412             ExprKind::LlvmInlineAsm(..) => ExprPrecedence::InlineAsm,
1413             ExprKind::Struct(..) => ExprPrecedence::Struct,
1414             ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1415             ExprKind::Yield(..) => ExprPrecedence::Yield,
1416             ExprKind::Err => ExprPrecedence::Err,
1417         }
1418     }
1419
1420     // Whether this looks like a place expr, without checking for deref
1421     // adjustments.
1422     // This will return `true` in some potentially surprising cases such as
1423     // `CONSTANT.field`.
1424     pub fn is_syntactic_place_expr(&self) -> bool {
1425         self.is_place_expr(|_| true)
1426     }
1427
1428     /// Whether this is a place expression.
1429     ///
1430     /// `allow_projections_from` should return `true` if indexing a field or index expression based
1431     /// on the given expression should be considered a place expression.
1432     pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1433         match self.kind {
1434             ExprKind::Path(QPath::Resolved(_, ref path)) => {
1435                 matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static, _) | Res::Err)
1436             }
1437
1438             // Type ascription inherits its place expression kind from its
1439             // operand. See:
1440             // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1441             ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1442
1443             ExprKind::Unary(UnOp::Deref, _) => true,
1444
1445             ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1446                 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1447             }
1448
1449             // Lang item paths cannot currently be local variables or statics.
1450             ExprKind::Path(QPath::LangItem(..)) => false,
1451
1452             // Partially qualified paths in expressions can only legally
1453             // refer to associated items which are always rvalues.
1454             ExprKind::Path(QPath::TypeRelative(..))
1455             | ExprKind::Call(..)
1456             | ExprKind::MethodCall(..)
1457             | ExprKind::Struct(..)
1458             | ExprKind::Tup(..)
1459             | ExprKind::If(..)
1460             | ExprKind::Match(..)
1461             | ExprKind::Closure(..)
1462             | ExprKind::Block(..)
1463             | ExprKind::Repeat(..)
1464             | ExprKind::Array(..)
1465             | ExprKind::Break(..)
1466             | ExprKind::Continue(..)
1467             | ExprKind::Ret(..)
1468             | ExprKind::Let(..)
1469             | ExprKind::Loop(..)
1470             | ExprKind::Assign(..)
1471             | ExprKind::InlineAsm(..)
1472             | ExprKind::LlvmInlineAsm(..)
1473             | ExprKind::AssignOp(..)
1474             | ExprKind::Lit(_)
1475             | ExprKind::ConstBlock(..)
1476             | ExprKind::Unary(..)
1477             | ExprKind::Box(..)
1478             | ExprKind::AddrOf(..)
1479             | ExprKind::Binary(..)
1480             | ExprKind::Yield(..)
1481             | ExprKind::Cast(..)
1482             | ExprKind::DropTemps(..)
1483             | ExprKind::Err => false,
1484         }
1485     }
1486
1487     /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1488     /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1489     /// silent, only signaling the ownership system. By doing this, suggestions that check the
1490     /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1491     /// beyond remembering to call this function before doing analysis on it.
1492     pub fn peel_drop_temps(&self) -> &Self {
1493         let mut expr = self;
1494         while let ExprKind::DropTemps(inner) = &expr.kind {
1495             expr = inner;
1496         }
1497         expr
1498     }
1499
1500     pub fn peel_blocks(&self) -> &Self {
1501         let mut expr = self;
1502         while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind {
1503             expr = inner;
1504         }
1505         expr
1506     }
1507
1508     pub fn can_have_side_effects(&self) -> bool {
1509         match self.peel_drop_temps().kind {
1510             ExprKind::Path(_) | ExprKind::Lit(_) => false,
1511             ExprKind::Type(base, _)
1512             | ExprKind::Unary(_, base)
1513             | ExprKind::Field(base, _)
1514             | ExprKind::Index(base, _)
1515             | ExprKind::AddrOf(.., base)
1516             | ExprKind::Cast(base, _) => {
1517                 // This isn't exactly true for `Index` and all `Unnary`, but we are using this
1518                 // method exclusively for diagnostics and there's a *cultural* pressure against
1519                 // them being used only for its side-effects.
1520                 base.can_have_side_effects()
1521             }
1522             ExprKind::Struct(_, fields, init) => fields
1523                 .iter()
1524                 .map(|field| field.expr)
1525                 .chain(init.into_iter())
1526                 .all(|e| e.can_have_side_effects()),
1527
1528             ExprKind::Array(args)
1529             | ExprKind::Tup(args)
1530             | ExprKind::Call(
1531                 Expr {
1532                     kind:
1533                         ExprKind::Path(QPath::Resolved(
1534                             None,
1535                             Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. },
1536                         )),
1537                     ..
1538                 },
1539                 args,
1540             ) => args.iter().all(|arg| arg.can_have_side_effects()),
1541             ExprKind::If(..)
1542             | ExprKind::Match(..)
1543             | ExprKind::MethodCall(..)
1544             | ExprKind::Call(..)
1545             | ExprKind::Closure(..)
1546             | ExprKind::Block(..)
1547             | ExprKind::Repeat(..)
1548             | ExprKind::Break(..)
1549             | ExprKind::Continue(..)
1550             | ExprKind::Ret(..)
1551             | ExprKind::Let(..)
1552             | ExprKind::Loop(..)
1553             | ExprKind::Assign(..)
1554             | ExprKind::InlineAsm(..)
1555             | ExprKind::LlvmInlineAsm(..)
1556             | ExprKind::AssignOp(..)
1557             | ExprKind::ConstBlock(..)
1558             | ExprKind::Box(..)
1559             | ExprKind::Binary(..)
1560             | ExprKind::Yield(..)
1561             | ExprKind::DropTemps(..)
1562             | ExprKind::Err => true,
1563         }
1564     }
1565 }
1566
1567 /// Checks if the specified expression is a built-in range literal.
1568 /// (See: `LoweringContext::lower_expr()`).
1569 pub fn is_range_literal(expr: &Expr<'_>) -> bool {
1570     match expr.kind {
1571         // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1572         ExprKind::Struct(ref qpath, _, _) => matches!(
1573             **qpath,
1574             QPath::LangItem(
1575                 LangItem::Range
1576                     | LangItem::RangeTo
1577                     | LangItem::RangeFrom
1578                     | LangItem::RangeFull
1579                     | LangItem::RangeToInclusive,
1580                 _,
1581             )
1582         ),
1583
1584         // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1585         ExprKind::Call(ref func, _) => {
1586             matches!(func.kind, ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, _)))
1587         }
1588
1589         _ => false,
1590     }
1591 }
1592
1593 #[derive(Debug, HashStable_Generic)]
1594 pub enum ExprKind<'hir> {
1595     /// A `box x` expression.
1596     Box(&'hir Expr<'hir>),
1597     /// Allow anonymous constants from an inline `const` block
1598     ConstBlock(AnonConst),
1599     /// An array (e.g., `[a, b, c, d]`).
1600     Array(&'hir [Expr<'hir>]),
1601     /// A function call.
1602     ///
1603     /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1604     /// and the second field is the list of arguments.
1605     /// This also represents calling the constructor of
1606     /// tuple-like ADTs such as tuple structs and enum variants.
1607     Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1608     /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1609     ///
1610     /// The `PathSegment`/`Span` represent the method name and its generic arguments
1611     /// (within the angle brackets).
1612     /// The first element of the vector of `Expr`s is the expression that evaluates
1613     /// to the object on which the method is being called on (the receiver),
1614     /// and the remaining elements are the rest of the arguments.
1615     /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1616     /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1617     /// The final `Span` represents the span of the function and arguments
1618     /// (e.g. `foo::<Bar, Baz>(a, b, c, d)` in `x.foo::<Bar, Baz>(a, b, c, d)`
1619     ///
1620     /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1621     /// the `hir_id` of the `MethodCall` node itself.
1622     ///
1623     /// [`type_dependent_def_id`]: ../ty/struct.TypeckResults.html#method.type_dependent_def_id
1624     MethodCall(&'hir PathSegment<'hir>, Span, &'hir [Expr<'hir>], Span),
1625     /// A tuple (e.g., `(a, b, c, d)`).
1626     Tup(&'hir [Expr<'hir>]),
1627     /// A binary operation (e.g., `a + b`, `a * b`).
1628     Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1629     /// A unary operation (e.g., `!x`, `*x`).
1630     Unary(UnOp, &'hir Expr<'hir>),
1631     /// A literal (e.g., `1`, `"foo"`).
1632     Lit(Lit),
1633     /// A cast (e.g., `foo as f64`).
1634     Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1635     /// A type reference (e.g., `Foo`).
1636     Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1637     /// Wraps the expression in a terminating scope.
1638     /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1639     ///
1640     /// This construct only exists to tweak the drop order in HIR lowering.
1641     /// An example of that is the desugaring of `for` loops.
1642     DropTemps(&'hir Expr<'hir>),
1643     /// A `let $pat = $expr` expression.
1644     ///
1645     /// These are not `Local` and only occur as expressions.
1646     /// The `let Some(x) = foo()` in `if let Some(x) = foo()` is an example of `Let(..)`.
1647     Let(&'hir Pat<'hir>, &'hir Expr<'hir>, Span),
1648     /// An `if` block, with an optional else block.
1649     ///
1650     /// I.e., `if <expr> { <expr> } else { <expr> }`.
1651     If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
1652     /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1653     ///
1654     /// I.e., `'label: loop { <block> }`.
1655     ///
1656     /// The `Span` is the loop header (`for x in y`/`while let pat = expr`).
1657     Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span),
1658     /// A `match` block, with a source that indicates whether or not it is
1659     /// the result of a desugaring, and if so, which kind.
1660     Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1661     /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1662     ///
1663     /// The `Span` is the argument block `|...|`.
1664     ///
1665     /// This may also be a generator literal or an `async block` as indicated by the
1666     /// `Option<Movability>`.
1667     Closure(CaptureBy, &'hir FnDecl<'hir>, BodyId, Span, Option<Movability>),
1668     /// A block (e.g., `'label: { ... }`).
1669     Block(&'hir Block<'hir>, Option<Label>),
1670
1671     /// An assignment (e.g., `a = foo()`).
1672     Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1673     /// An assignment with an operator.
1674     ///
1675     /// E.g., `a += 1`.
1676     AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1677     /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1678     Field(&'hir Expr<'hir>, Ident),
1679     /// An indexing operation (`foo[2]`).
1680     Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1681
1682     /// Path to a definition, possibly containing lifetime or type parameters.
1683     Path(QPath<'hir>),
1684
1685     /// A referencing operation (i.e., `&a` or `&mut a`).
1686     AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1687     /// A `break`, with an optional label to break.
1688     Break(Destination, Option<&'hir Expr<'hir>>),
1689     /// A `continue`, with an optional label.
1690     Continue(Destination),
1691     /// A `return`, with an optional value to be returned.
1692     Ret(Option<&'hir Expr<'hir>>),
1693
1694     /// Inline assembly (from `asm!`), with its outputs and inputs.
1695     InlineAsm(&'hir InlineAsm<'hir>),
1696     /// Inline assembly (from `llvm_asm!`), with its outputs and inputs.
1697     LlvmInlineAsm(&'hir LlvmInlineAsm<'hir>),
1698
1699     /// A struct or struct-like variant literal expression.
1700     ///
1701     /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1702     /// where `base` is the `Option<Expr>`.
1703     Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], Option<&'hir Expr<'hir>>),
1704
1705     /// An array literal constructed from one repeated element.
1706     ///
1707     /// E.g., `[1; 5]`. The first expression is the element
1708     /// to be repeated; the second is the number of times to repeat it.
1709     Repeat(&'hir Expr<'hir>, AnonConst),
1710
1711     /// A suspension point for generators (i.e., `yield <expr>`).
1712     Yield(&'hir Expr<'hir>, YieldSource),
1713
1714     /// A placeholder for an expression that wasn't syntactically well formed in some way.
1715     Err,
1716 }
1717
1718 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1719 ///
1720 /// To resolve the path to a `DefId`, call [`qpath_res`].
1721 ///
1722 /// [`qpath_res`]: ../rustc_middle/ty/struct.TypeckResults.html#method.qpath_res
1723 #[derive(Debug, HashStable_Generic)]
1724 pub enum QPath<'hir> {
1725     /// Path to a definition, optionally "fully-qualified" with a `Self`
1726     /// type, if the path points to an associated item in a trait.
1727     ///
1728     /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1729     /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1730     /// even though they both have the same two-segment `Clone::clone` `Path`.
1731     Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
1732
1733     /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1734     /// Will be resolved by type-checking to an associated item.
1735     ///
1736     /// UFCS source paths can desugar into this, with `Vec::new` turning into
1737     /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1738     /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1739     TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
1740
1741     /// Reference to a `#[lang = "foo"]` item.
1742     LangItem(LangItem, Span),
1743 }
1744
1745 impl<'hir> QPath<'hir> {
1746     /// Returns the span of this `QPath`.
1747     pub fn span(&self) -> Span {
1748         match *self {
1749             QPath::Resolved(_, path) => path.span,
1750             QPath::TypeRelative(qself, ps) => qself.span.to(ps.ident.span),
1751             QPath::LangItem(_, span) => span,
1752         }
1753     }
1754
1755     /// Returns the span of the qself of this `QPath`. For example, `()` in
1756     /// `<() as Trait>::method`.
1757     pub fn qself_span(&self) -> Span {
1758         match *self {
1759             QPath::Resolved(_, path) => path.span,
1760             QPath::TypeRelative(qself, _) => qself.span,
1761             QPath::LangItem(_, span) => span,
1762         }
1763     }
1764
1765     /// Returns the span of the last segment of this `QPath`. For example, `method` in
1766     /// `<() as Trait>::method`.
1767     pub fn last_segment_span(&self) -> Span {
1768         match *self {
1769             QPath::Resolved(_, path) => path.segments.last().unwrap().ident.span,
1770             QPath::TypeRelative(_, segment) => segment.ident.span,
1771             QPath::LangItem(_, span) => span,
1772         }
1773     }
1774 }
1775
1776 /// Hints at the original code for a let statement.
1777 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1778 pub enum LocalSource {
1779     /// A `match _ { .. }`.
1780     Normal,
1781     /// A desugared `for _ in _ { .. }` loop.
1782     ForLoopDesugar,
1783     /// When lowering async functions, we create locals within the `async move` so that
1784     /// all parameters are dropped after the future is polled.
1785     ///
1786     /// ```ignore (pseudo-Rust)
1787     /// async fn foo(<pattern> @ x: Type) {
1788     ///     async move {
1789     ///         let <pattern> = x;
1790     ///     }
1791     /// }
1792     /// ```
1793     AsyncFn,
1794     /// A desugared `<expr>.await`.
1795     AwaitDesugar,
1796     /// A desugared `expr = expr`, where the LHS is a tuple, struct or array.
1797     /// The span is that of the `=` sign.
1798     AssignDesugar(Span),
1799 }
1800
1801 /// Hints at the original code for a `match _ { .. }`.
1802 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
1803 #[derive(HashStable_Generic)]
1804 pub enum MatchSource {
1805     /// A `match _ { .. }`.
1806     Normal,
1807     /// A desugared `for _ in _ { .. }` loop.
1808     ForLoopDesugar,
1809     /// A desugared `?` operator.
1810     TryDesugar,
1811     /// A desugared `<expr>.await`.
1812     AwaitDesugar,
1813 }
1814
1815 impl MatchSource {
1816     #[inline]
1817     pub const fn name(self) -> &'static str {
1818         use MatchSource::*;
1819         match self {
1820             Normal => "match",
1821             ForLoopDesugar => "for",
1822             TryDesugar => "?",
1823             AwaitDesugar => ".await",
1824         }
1825     }
1826 }
1827
1828 /// The loop type that yielded an `ExprKind::Loop`.
1829 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1830 pub enum LoopSource {
1831     /// A `loop { .. }` loop.
1832     Loop,
1833     /// A `while _ { .. }` loop.
1834     While,
1835     /// A `for _ in _ { .. }` loop.
1836     ForLoop,
1837 }
1838
1839 impl LoopSource {
1840     pub fn name(self) -> &'static str {
1841         match self {
1842             LoopSource::Loop => "loop",
1843             LoopSource::While => "while",
1844             LoopSource::ForLoop => "for",
1845         }
1846     }
1847 }
1848
1849 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1850 pub enum LoopIdError {
1851     OutsideLoopScope,
1852     UnlabeledCfInWhileCondition,
1853     UnresolvedLabel,
1854 }
1855
1856 impl fmt::Display for LoopIdError {
1857     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1858         f.write_str(match self {
1859             LoopIdError::OutsideLoopScope => "not inside loop scope",
1860             LoopIdError::UnlabeledCfInWhileCondition => {
1861                 "unlabeled control flow (break or continue) in while condition"
1862             }
1863             LoopIdError::UnresolvedLabel => "label not found",
1864         })
1865     }
1866 }
1867
1868 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1869 pub struct Destination {
1870     // This is `Some(_)` iff there is an explicit user-specified `label
1871     pub label: Option<Label>,
1872
1873     // These errors are caught and then reported during the diagnostics pass in
1874     // librustc_passes/loops.rs
1875     pub target_id: Result<HirId, LoopIdError>,
1876 }
1877
1878 /// The yield kind that caused an `ExprKind::Yield`.
1879 #[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
1880 pub enum YieldSource {
1881     /// An `<expr>.await`.
1882     Await { expr: Option<HirId> },
1883     /// A plain `yield`.
1884     Yield,
1885 }
1886
1887 impl YieldSource {
1888     pub fn is_await(&self) -> bool {
1889         match self {
1890             YieldSource::Await { .. } => true,
1891             YieldSource::Yield => false,
1892         }
1893     }
1894 }
1895
1896 impl fmt::Display for YieldSource {
1897     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1898         f.write_str(match self {
1899             YieldSource::Await { .. } => "`await`",
1900             YieldSource::Yield => "`yield`",
1901         })
1902     }
1903 }
1904
1905 impl From<GeneratorKind> for YieldSource {
1906     fn from(kind: GeneratorKind) -> Self {
1907         match kind {
1908             // Guess based on the kind of the current generator.
1909             GeneratorKind::Gen => Self::Yield,
1910             GeneratorKind::Async(_) => Self::Await { expr: None },
1911         }
1912     }
1913 }
1914
1915 // N.B., if you change this, you'll probably want to change the corresponding
1916 // type structure in middle/ty.rs as well.
1917 #[derive(Debug, HashStable_Generic)]
1918 pub struct MutTy<'hir> {
1919     pub ty: &'hir Ty<'hir>,
1920     pub mutbl: Mutability,
1921 }
1922
1923 /// Represents a function's signature in a trait declaration,
1924 /// trait implementation, or a free function.
1925 #[derive(Debug, HashStable_Generic)]
1926 pub struct FnSig<'hir> {
1927     pub header: FnHeader,
1928     pub decl: &'hir FnDecl<'hir>,
1929     pub span: Span,
1930 }
1931
1932 // The bodies for items are stored "out of line", in a separate
1933 // hashmap in the `Crate`. Here we just record the hir-id of the item
1934 // so it can fetched later.
1935 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
1936 pub struct TraitItemId {
1937     pub def_id: LocalDefId,
1938 }
1939
1940 impl TraitItemId {
1941     #[inline]
1942     pub fn hir_id(&self) -> HirId {
1943         // Items are always HIR owners.
1944         HirId::make_owner(self.def_id)
1945     }
1946 }
1947
1948 /// Represents an item declaration within a trait declaration,
1949 /// possibly including a default implementation. A trait item is
1950 /// either required (meaning it doesn't have an implementation, just a
1951 /// signature) or provided (meaning it has a default implementation).
1952 #[derive(Debug)]
1953 pub struct TraitItem<'hir> {
1954     pub ident: Ident,
1955     pub def_id: LocalDefId,
1956     pub generics: Generics<'hir>,
1957     pub kind: TraitItemKind<'hir>,
1958     pub span: Span,
1959 }
1960
1961 impl TraitItem<'_> {
1962     #[inline]
1963     pub fn hir_id(&self) -> HirId {
1964         // Items are always HIR owners.
1965         HirId::make_owner(self.def_id)
1966     }
1967
1968     pub fn trait_item_id(&self) -> TraitItemId {
1969         TraitItemId { def_id: self.def_id }
1970     }
1971 }
1972
1973 /// Represents a trait method's body (or just argument names).
1974 #[derive(Encodable, Debug, HashStable_Generic)]
1975 pub enum TraitFn<'hir> {
1976     /// No default body in the trait, just a signature.
1977     Required(&'hir [Ident]),
1978
1979     /// Both signature and body are provided in the trait.
1980     Provided(BodyId),
1981 }
1982
1983 /// Represents a trait method or associated constant or type
1984 #[derive(Debug, HashStable_Generic)]
1985 pub enum TraitItemKind<'hir> {
1986     /// An associated constant with an optional value (otherwise `impl`s must contain a value).
1987     Const(&'hir Ty<'hir>, Option<BodyId>),
1988     /// An associated function with an optional body.
1989     Fn(FnSig<'hir>, TraitFn<'hir>),
1990     /// An associated type with (possibly empty) bounds and optional concrete
1991     /// type.
1992     Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
1993 }
1994
1995 // The bodies for items are stored "out of line", in a separate
1996 // hashmap in the `Crate`. Here we just record the hir-id of the item
1997 // so it can fetched later.
1998 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
1999 pub struct ImplItemId {
2000     pub def_id: LocalDefId,
2001 }
2002
2003 impl ImplItemId {
2004     #[inline]
2005     pub fn hir_id(&self) -> HirId {
2006         // Items are always HIR owners.
2007         HirId::make_owner(self.def_id)
2008     }
2009 }
2010
2011 /// Represents anything within an `impl` block.
2012 #[derive(Debug)]
2013 pub struct ImplItem<'hir> {
2014     pub ident: Ident,
2015     pub def_id: LocalDefId,
2016     pub vis: Visibility<'hir>,
2017     pub defaultness: Defaultness,
2018     pub generics: Generics<'hir>,
2019     pub kind: ImplItemKind<'hir>,
2020     pub span: Span,
2021 }
2022
2023 impl ImplItem<'_> {
2024     #[inline]
2025     pub fn hir_id(&self) -> HirId {
2026         // Items are always HIR owners.
2027         HirId::make_owner(self.def_id)
2028     }
2029
2030     pub fn impl_item_id(&self) -> ImplItemId {
2031         ImplItemId { def_id: self.def_id }
2032     }
2033 }
2034
2035 /// Represents various kinds of content within an `impl`.
2036 #[derive(Debug, HashStable_Generic)]
2037 pub enum ImplItemKind<'hir> {
2038     /// An associated constant of the given type, set to the constant result
2039     /// of the expression.
2040     Const(&'hir Ty<'hir>, BodyId),
2041     /// An associated function implementation with the given signature and body.
2042     Fn(FnSig<'hir>, BodyId),
2043     /// An associated type.
2044     TyAlias(&'hir Ty<'hir>),
2045 }
2046
2047 // The name of the associated type for `Fn` return types.
2048 pub const FN_OUTPUT_NAME: Symbol = sym::Output;
2049
2050 /// Bind a type to an associated type (i.e., `A = Foo`).
2051 ///
2052 /// Bindings like `A: Debug` are represented as a special type `A =
2053 /// $::Debug` that is understood by the astconv code.
2054 ///
2055 /// FIXME(alexreg): why have a separate type for the binding case,
2056 /// wouldn't it be better to make the `ty` field an enum like the
2057 /// following?
2058 ///
2059 /// ```
2060 /// enum TypeBindingKind {
2061 ///    Equals(...),
2062 ///    Binding(...),
2063 /// }
2064 /// ```
2065 #[derive(Debug, HashStable_Generic)]
2066 pub struct TypeBinding<'hir> {
2067     pub hir_id: HirId,
2068     #[stable_hasher(project(name))]
2069     pub ident: Ident,
2070     pub gen_args: &'hir GenericArgs<'hir>,
2071     pub kind: TypeBindingKind<'hir>,
2072     pub span: Span,
2073 }
2074
2075 // Represents the two kinds of type bindings.
2076 #[derive(Debug, HashStable_Generic)]
2077 pub enum TypeBindingKind<'hir> {
2078     /// E.g., `Foo<Bar: Send>`.
2079     Constraint { bounds: &'hir [GenericBound<'hir>] },
2080     /// E.g., `Foo<Bar = ()>`.
2081     Equality { ty: &'hir Ty<'hir> },
2082 }
2083
2084 impl TypeBinding<'_> {
2085     pub fn ty(&self) -> &Ty<'_> {
2086         match self.kind {
2087             TypeBindingKind::Equality { ref ty } => ty,
2088             _ => panic!("expected equality type binding for parenthesized generic args"),
2089         }
2090     }
2091 }
2092
2093 #[derive(Debug)]
2094 pub struct Ty<'hir> {
2095     pub hir_id: HirId,
2096     pub kind: TyKind<'hir>,
2097     pub span: Span,
2098 }
2099
2100 /// Not represented directly in the AST; referred to by name through a `ty_path`.
2101 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
2102 #[derive(HashStable_Generic)]
2103 pub enum PrimTy {
2104     Int(IntTy),
2105     Uint(UintTy),
2106     Float(FloatTy),
2107     Str,
2108     Bool,
2109     Char,
2110 }
2111
2112 impl PrimTy {
2113     /// All of the primitive types
2114     pub const ALL: [Self; 17] = [
2115         // any changes here should also be reflected in `PrimTy::from_name`
2116         Self::Int(IntTy::I8),
2117         Self::Int(IntTy::I16),
2118         Self::Int(IntTy::I32),
2119         Self::Int(IntTy::I64),
2120         Self::Int(IntTy::I128),
2121         Self::Int(IntTy::Isize),
2122         Self::Uint(UintTy::U8),
2123         Self::Uint(UintTy::U16),
2124         Self::Uint(UintTy::U32),
2125         Self::Uint(UintTy::U64),
2126         Self::Uint(UintTy::U128),
2127         Self::Uint(UintTy::Usize),
2128         Self::Float(FloatTy::F32),
2129         Self::Float(FloatTy::F64),
2130         Self::Bool,
2131         Self::Char,
2132         Self::Str,
2133     ];
2134
2135     /// Like [`PrimTy::name`], but returns a &str instead of a symbol.
2136     ///
2137     /// Used by clippy.
2138     pub fn name_str(self) -> &'static str {
2139         match self {
2140             PrimTy::Int(i) => i.name_str(),
2141             PrimTy::Uint(u) => u.name_str(),
2142             PrimTy::Float(f) => f.name_str(),
2143             PrimTy::Str => "str",
2144             PrimTy::Bool => "bool",
2145             PrimTy::Char => "char",
2146         }
2147     }
2148
2149     pub fn name(self) -> Symbol {
2150         match self {
2151             PrimTy::Int(i) => i.name(),
2152             PrimTy::Uint(u) => u.name(),
2153             PrimTy::Float(f) => f.name(),
2154             PrimTy::Str => sym::str,
2155             PrimTy::Bool => sym::bool,
2156             PrimTy::Char => sym::char,
2157         }
2158     }
2159
2160     /// Returns the matching `PrimTy` for a `Symbol` such as "str" or "i32".
2161     /// Returns `None` if no matching type is found.
2162     pub fn from_name(name: Symbol) -> Option<Self> {
2163         let ty = match name {
2164             // any changes here should also be reflected in `PrimTy::ALL`
2165             sym::i8 => Self::Int(IntTy::I8),
2166             sym::i16 => Self::Int(IntTy::I16),
2167             sym::i32 => Self::Int(IntTy::I32),
2168             sym::i64 => Self::Int(IntTy::I64),
2169             sym::i128 => Self::Int(IntTy::I128),
2170             sym::isize => Self::Int(IntTy::Isize),
2171             sym::u8 => Self::Uint(UintTy::U8),
2172             sym::u16 => Self::Uint(UintTy::U16),
2173             sym::u32 => Self::Uint(UintTy::U32),
2174             sym::u64 => Self::Uint(UintTy::U64),
2175             sym::u128 => Self::Uint(UintTy::U128),
2176             sym::usize => Self::Uint(UintTy::Usize),
2177             sym::f32 => Self::Float(FloatTy::F32),
2178             sym::f64 => Self::Float(FloatTy::F64),
2179             sym::bool => Self::Bool,
2180             sym::char => Self::Char,
2181             sym::str => Self::Str,
2182             _ => return None,
2183         };
2184         Some(ty)
2185     }
2186 }
2187
2188 #[derive(Debug, HashStable_Generic)]
2189 pub struct BareFnTy<'hir> {
2190     pub unsafety: Unsafety,
2191     pub abi: Abi,
2192     pub generic_params: &'hir [GenericParam<'hir>],
2193     pub decl: &'hir FnDecl<'hir>,
2194     pub param_names: &'hir [Ident],
2195 }
2196
2197 #[derive(Debug, HashStable_Generic)]
2198 pub struct OpaqueTy<'hir> {
2199     pub generics: Generics<'hir>,
2200     pub bounds: GenericBounds<'hir>,
2201     pub impl_trait_fn: Option<DefId>,
2202     pub origin: OpaqueTyOrigin,
2203 }
2204
2205 /// From whence the opaque type came.
2206 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2207 pub enum OpaqueTyOrigin {
2208     /// `-> impl Trait`
2209     FnReturn,
2210     /// `async fn`
2211     AsyncFn,
2212     /// type aliases: `type Foo = impl Trait;`
2213     TyAlias,
2214 }
2215
2216 /// The various kinds of types recognized by the compiler.
2217 #[derive(Debug, HashStable_Generic)]
2218 pub enum TyKind<'hir> {
2219     /// A variable length slice (i.e., `[T]`).
2220     Slice(&'hir Ty<'hir>),
2221     /// A fixed length array (i.e., `[T; n]`).
2222     Array(&'hir Ty<'hir>, AnonConst),
2223     /// A raw pointer (i.e., `*const T` or `*mut T`).
2224     Ptr(MutTy<'hir>),
2225     /// A reference (i.e., `&'a T` or `&'a mut T`).
2226     Rptr(Lifetime, MutTy<'hir>),
2227     /// A bare function (e.g., `fn(usize) -> bool`).
2228     BareFn(&'hir BareFnTy<'hir>),
2229     /// The never type (`!`).
2230     Never,
2231     /// A tuple (`(A, B, C, D, ...)`).
2232     Tup(&'hir [Ty<'hir>]),
2233     /// A path to a type definition (`module::module::...::Type`), or an
2234     /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2235     ///
2236     /// Type parameters may be stored in each `PathSegment`.
2237     Path(QPath<'hir>),
2238     /// An opaque type definition itself. This is currently only used for the
2239     /// `opaque type Foo: Trait` item that `impl Trait` in desugars to.
2240     ///
2241     /// The generic argument list contains the lifetimes (and in the future
2242     /// possibly parameters) that are actually bound on the `impl Trait`.
2243     OpaqueDef(ItemId, &'hir [GenericArg<'hir>]),
2244     /// A trait object type `Bound1 + Bound2 + Bound3`
2245     /// where `Bound` is a trait or a lifetime.
2246     TraitObject(&'hir [PolyTraitRef<'hir>], Lifetime, TraitObjectSyntax),
2247     /// Unused for now.
2248     Typeof(AnonConst),
2249     /// `TyKind::Infer` means the type should be inferred instead of it having been
2250     /// specified. This can appear anywhere in a type.
2251     Infer,
2252     /// Placeholder for a type that has failed to be defined.
2253     Err,
2254 }
2255
2256 #[derive(Debug, HashStable_Generic)]
2257 pub enum InlineAsmOperand<'hir> {
2258     In {
2259         reg: InlineAsmRegOrRegClass,
2260         expr: Expr<'hir>,
2261     },
2262     Out {
2263         reg: InlineAsmRegOrRegClass,
2264         late: bool,
2265         expr: Option<Expr<'hir>>,
2266     },
2267     InOut {
2268         reg: InlineAsmRegOrRegClass,
2269         late: bool,
2270         expr: Expr<'hir>,
2271     },
2272     SplitInOut {
2273         reg: InlineAsmRegOrRegClass,
2274         late: bool,
2275         in_expr: Expr<'hir>,
2276         out_expr: Option<Expr<'hir>>,
2277     },
2278     Const {
2279         anon_const: AnonConst,
2280     },
2281     Sym {
2282         expr: Expr<'hir>,
2283     },
2284 }
2285
2286 impl<'hir> InlineAsmOperand<'hir> {
2287     pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
2288         match *self {
2289             Self::In { reg, .. }
2290             | Self::Out { reg, .. }
2291             | Self::InOut { reg, .. }
2292             | Self::SplitInOut { reg, .. } => Some(reg),
2293             Self::Const { .. } | Self::Sym { .. } => None,
2294         }
2295     }
2296
2297     pub fn is_clobber(&self) -> bool {
2298         matches!(
2299             self,
2300             InlineAsmOperand::Out { reg: InlineAsmRegOrRegClass::Reg(_), late: _, expr: None }
2301         )
2302     }
2303 }
2304
2305 #[derive(Debug, HashStable_Generic)]
2306 pub struct InlineAsm<'hir> {
2307     pub template: &'hir [InlineAsmTemplatePiece],
2308     pub template_strs: &'hir [(Symbol, Option<Symbol>, Span)],
2309     pub operands: &'hir [(InlineAsmOperand<'hir>, Span)],
2310     pub options: InlineAsmOptions,
2311     pub line_spans: &'hir [Span],
2312 }
2313
2314 #[derive(Copy, Clone, Encodable, Decodable, Debug, Hash, HashStable_Generic, PartialEq)]
2315 pub struct LlvmInlineAsmOutput {
2316     pub constraint: Symbol,
2317     pub is_rw: bool,
2318     pub is_indirect: bool,
2319     pub span: Span,
2320 }
2321
2322 // NOTE(eddyb) This is used within MIR as well, so unlike the rest of the HIR,
2323 // it needs to be `Clone` and `Decodable` and use plain `Vec<T>` instead of
2324 // arena-allocated slice.
2325 #[derive(Clone, Encodable, Decodable, Debug, Hash, HashStable_Generic, PartialEq)]
2326 pub struct LlvmInlineAsmInner {
2327     pub asm: Symbol,
2328     pub asm_str_style: StrStyle,
2329     pub outputs: Vec<LlvmInlineAsmOutput>,
2330     pub inputs: Vec<Symbol>,
2331     pub clobbers: Vec<Symbol>,
2332     pub volatile: bool,
2333     pub alignstack: bool,
2334     pub dialect: LlvmAsmDialect,
2335 }
2336
2337 #[derive(Debug, HashStable_Generic)]
2338 pub struct LlvmInlineAsm<'hir> {
2339     pub inner: LlvmInlineAsmInner,
2340     pub outputs_exprs: &'hir [Expr<'hir>],
2341     pub inputs_exprs: &'hir [Expr<'hir>],
2342 }
2343
2344 /// Represents a parameter in a function header.
2345 #[derive(Debug, HashStable_Generic)]
2346 pub struct Param<'hir> {
2347     pub hir_id: HirId,
2348     pub pat: &'hir Pat<'hir>,
2349     pub ty_span: Span,
2350     pub span: Span,
2351 }
2352
2353 /// Represents the header (not the body) of a function declaration.
2354 #[derive(Debug, HashStable_Generic)]
2355 pub struct FnDecl<'hir> {
2356     /// The types of the function's parameters.
2357     ///
2358     /// Additional argument data is stored in the function's [body](Body::params).
2359     pub inputs: &'hir [Ty<'hir>],
2360     pub output: FnRetTy<'hir>,
2361     pub c_variadic: bool,
2362     /// Does the function have an implicit self?
2363     pub implicit_self: ImplicitSelfKind,
2364 }
2365
2366 /// Represents what type of implicit self a function has, if any.
2367 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2368 pub enum ImplicitSelfKind {
2369     /// Represents a `fn x(self);`.
2370     Imm,
2371     /// Represents a `fn x(mut self);`.
2372     Mut,
2373     /// Represents a `fn x(&self);`.
2374     ImmRef,
2375     /// Represents a `fn x(&mut self);`.
2376     MutRef,
2377     /// Represents when a function does not have a self argument or
2378     /// when a function has a `self: X` argument.
2379     None,
2380 }
2381
2382 impl ImplicitSelfKind {
2383     /// Does this represent an implicit self?
2384     pub fn has_implicit_self(&self) -> bool {
2385         !matches!(*self, ImplicitSelfKind::None)
2386     }
2387 }
2388
2389 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable, Debug)]
2390 #[derive(HashStable_Generic)]
2391 pub enum IsAsync {
2392     Async,
2393     NotAsync,
2394 }
2395
2396 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable, HashStable_Generic)]
2397 pub enum Defaultness {
2398     Default { has_value: bool },
2399     Final,
2400 }
2401
2402 impl Defaultness {
2403     pub fn has_value(&self) -> bool {
2404         match *self {
2405             Defaultness::Default { has_value } => has_value,
2406             Defaultness::Final => true,
2407         }
2408     }
2409
2410     pub fn is_final(&self) -> bool {
2411         *self == Defaultness::Final
2412     }
2413
2414     pub fn is_default(&self) -> bool {
2415         matches!(*self, Defaultness::Default { .. })
2416     }
2417 }
2418
2419 #[derive(Debug, HashStable_Generic)]
2420 pub enum FnRetTy<'hir> {
2421     /// Return type is not specified.
2422     ///
2423     /// Functions default to `()` and
2424     /// closures default to inference. Span points to where return
2425     /// type would be inserted.
2426     DefaultReturn(Span),
2427     /// Everything else.
2428     Return(&'hir Ty<'hir>),
2429 }
2430
2431 impl FnRetTy<'_> {
2432     #[inline]
2433     pub fn span(&self) -> Span {
2434         match *self {
2435             Self::DefaultReturn(span) => span,
2436             Self::Return(ref ty) => ty.span,
2437         }
2438     }
2439 }
2440
2441 #[derive(Encodable, Debug)]
2442 pub struct Mod<'hir> {
2443     /// A span from the first token past `{` to the last token until `}`.
2444     /// For `mod foo;`, the inner span ranges from the first token
2445     /// to the last token in the external file.
2446     pub inner: Span,
2447     pub item_ids: &'hir [ItemId],
2448 }
2449
2450 #[derive(Debug, HashStable_Generic)]
2451 pub struct EnumDef<'hir> {
2452     pub variants: &'hir [Variant<'hir>],
2453 }
2454
2455 #[derive(Debug, HashStable_Generic)]
2456 pub struct Variant<'hir> {
2457     /// Name of the variant.
2458     #[stable_hasher(project(name))]
2459     pub ident: Ident,
2460     /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2461     pub id: HirId,
2462     /// Fields and constructor id of the variant.
2463     pub data: VariantData<'hir>,
2464     /// Explicit discriminant (e.g., `Foo = 1`).
2465     pub disr_expr: Option<AnonConst>,
2466     /// Span
2467     pub span: Span,
2468 }
2469
2470 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2471 pub enum UseKind {
2472     /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2473     /// Also produced for each element of a list `use`, e.g.
2474     /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2475     Single,
2476
2477     /// Glob import, e.g., `use foo::*`.
2478     Glob,
2479
2480     /// Degenerate list import, e.g., `use foo::{a, b}` produces
2481     /// an additional `use foo::{}` for performing checks such as
2482     /// unstable feature gating. May be removed in the future.
2483     ListStem,
2484 }
2485
2486 /// References to traits in impls.
2487 ///
2488 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2489 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2490 /// trait being referred to but just a unique `HirId` that serves as a key
2491 /// within the resolution map.
2492 #[derive(Clone, Debug, HashStable_Generic)]
2493 pub struct TraitRef<'hir> {
2494     pub path: &'hir Path<'hir>,
2495     // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2496     #[stable_hasher(ignore)]
2497     pub hir_ref_id: HirId,
2498 }
2499
2500 impl TraitRef<'_> {
2501     /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2502     pub fn trait_def_id(&self) -> Option<DefId> {
2503         match self.path.res {
2504             Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
2505             Res::Err => None,
2506             _ => unreachable!(),
2507         }
2508     }
2509 }
2510
2511 #[derive(Clone, Debug, HashStable_Generic)]
2512 pub struct PolyTraitRef<'hir> {
2513     /// The `'a` in `for<'a> Foo<&'a T>`.
2514     pub bound_generic_params: &'hir [GenericParam<'hir>],
2515
2516     /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
2517     pub trait_ref: TraitRef<'hir>,
2518
2519     pub span: Span,
2520 }
2521
2522 pub type Visibility<'hir> = Spanned<VisibilityKind<'hir>>;
2523
2524 #[derive(Copy, Clone, Debug)]
2525 pub enum VisibilityKind<'hir> {
2526     Public,
2527     Crate(CrateSugar),
2528     Restricted { path: &'hir Path<'hir>, hir_id: HirId },
2529     Inherited,
2530 }
2531
2532 impl VisibilityKind<'_> {
2533     pub fn is_pub(&self) -> bool {
2534         matches!(*self, VisibilityKind::Public)
2535     }
2536
2537     pub fn is_pub_restricted(&self) -> bool {
2538         match *self {
2539             VisibilityKind::Public | VisibilityKind::Inherited => false,
2540             VisibilityKind::Crate(..) | VisibilityKind::Restricted { .. } => true,
2541         }
2542     }
2543 }
2544
2545 #[derive(Debug, HashStable_Generic)]
2546 pub struct FieldDef<'hir> {
2547     pub span: Span,
2548     #[stable_hasher(project(name))]
2549     pub ident: Ident,
2550     pub vis: Visibility<'hir>,
2551     pub hir_id: HirId,
2552     pub ty: &'hir Ty<'hir>,
2553 }
2554
2555 impl FieldDef<'_> {
2556     // Still necessary in couple of places
2557     pub fn is_positional(&self) -> bool {
2558         let first = self.ident.as_str().as_bytes()[0];
2559         (b'0'..=b'9').contains(&first)
2560     }
2561 }
2562
2563 /// Fields and constructor IDs of enum variants and structs.
2564 #[derive(Debug, HashStable_Generic)]
2565 pub enum VariantData<'hir> {
2566     /// A struct variant.
2567     ///
2568     /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2569     Struct(&'hir [FieldDef<'hir>], /* recovered */ bool),
2570     /// A tuple variant.
2571     ///
2572     /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2573     Tuple(&'hir [FieldDef<'hir>], HirId),
2574     /// A unit variant.
2575     ///
2576     /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2577     Unit(HirId),
2578 }
2579
2580 impl VariantData<'hir> {
2581     /// Return the fields of this variant.
2582     pub fn fields(&self) -> &'hir [FieldDef<'hir>] {
2583         match *self {
2584             VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2585             _ => &[],
2586         }
2587     }
2588
2589     /// Return the `HirId` of this variant's constructor, if it has one.
2590     pub fn ctor_hir_id(&self) -> Option<HirId> {
2591         match *self {
2592             VariantData::Struct(_, _) => None,
2593             VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2594         }
2595     }
2596 }
2597
2598 // The bodies for items are stored "out of line", in a separate
2599 // hashmap in the `Crate`. Here we just record the hir-id of the item
2600 // so it can fetched later.
2601 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug, Hash)]
2602 pub struct ItemId {
2603     pub def_id: LocalDefId,
2604 }
2605
2606 impl ItemId {
2607     #[inline]
2608     pub fn hir_id(&self) -> HirId {
2609         // Items are always HIR owners.
2610         HirId::make_owner(self.def_id)
2611     }
2612 }
2613
2614 /// An item
2615 ///
2616 /// The name might be a dummy name in case of anonymous items
2617 #[derive(Debug)]
2618 pub struct Item<'hir> {
2619     pub ident: Ident,
2620     pub def_id: LocalDefId,
2621     pub kind: ItemKind<'hir>,
2622     pub vis: Visibility<'hir>,
2623     pub span: Span,
2624 }
2625
2626 impl Item<'_> {
2627     #[inline]
2628     pub fn hir_id(&self) -> HirId {
2629         // Items are always HIR owners.
2630         HirId::make_owner(self.def_id)
2631     }
2632
2633     pub fn item_id(&self) -> ItemId {
2634         ItemId { def_id: self.def_id }
2635     }
2636 }
2637
2638 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2639 #[derive(Encodable, Decodable, HashStable_Generic)]
2640 pub enum Unsafety {
2641     Unsafe,
2642     Normal,
2643 }
2644
2645 impl Unsafety {
2646     pub fn prefix_str(&self) -> &'static str {
2647         match self {
2648             Self::Unsafe => "unsafe ",
2649             Self::Normal => "",
2650         }
2651     }
2652 }
2653
2654 impl fmt::Display for Unsafety {
2655     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2656         f.write_str(match *self {
2657             Self::Unsafe => "unsafe",
2658             Self::Normal => "normal",
2659         })
2660     }
2661 }
2662
2663 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2664 #[derive(Encodable, Decodable, HashStable_Generic)]
2665 pub enum Constness {
2666     Const,
2667     NotConst,
2668 }
2669
2670 impl fmt::Display for Constness {
2671     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2672         f.write_str(match *self {
2673             Self::Const => "const",
2674             Self::NotConst => "non-const",
2675         })
2676     }
2677 }
2678
2679 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2680 pub struct FnHeader {
2681     pub unsafety: Unsafety,
2682     pub constness: Constness,
2683     pub asyncness: IsAsync,
2684     pub abi: Abi,
2685 }
2686
2687 impl FnHeader {
2688     pub fn is_const(&self) -> bool {
2689         matches!(&self.constness, Constness::Const)
2690     }
2691 }
2692
2693 #[derive(Debug, HashStable_Generic)]
2694 pub enum ItemKind<'hir> {
2695     /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2696     ///
2697     /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2698     ExternCrate(Option<Symbol>),
2699
2700     /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2701     ///
2702     /// or just
2703     ///
2704     /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2705     Use(&'hir Path<'hir>, UseKind),
2706
2707     /// A `static` item.
2708     Static(&'hir Ty<'hir>, Mutability, BodyId),
2709     /// A `const` item.
2710     Const(&'hir Ty<'hir>, BodyId),
2711     /// A function declaration.
2712     Fn(FnSig<'hir>, Generics<'hir>, BodyId),
2713     /// A MBE macro definition (`macro_rules!` or `macro`).
2714     Macro(ast::MacroDef),
2715     /// A module.
2716     Mod(Mod<'hir>),
2717     /// An external module, e.g. `extern { .. }`.
2718     ForeignMod { abi: Abi, items: &'hir [ForeignItemRef] },
2719     /// Module-level inline assembly (from `global_asm!`).
2720     GlobalAsm(&'hir InlineAsm<'hir>),
2721     /// A type alias, e.g., `type Foo = Bar<u8>`.
2722     TyAlias(&'hir Ty<'hir>, Generics<'hir>),
2723     /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2724     OpaqueTy(OpaqueTy<'hir>),
2725     /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2726     Enum(EnumDef<'hir>, Generics<'hir>),
2727     /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2728     Struct(VariantData<'hir>, Generics<'hir>),
2729     /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2730     Union(VariantData<'hir>, Generics<'hir>),
2731     /// A trait definition.
2732     Trait(IsAuto, Unsafety, Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
2733     /// A trait alias.
2734     TraitAlias(Generics<'hir>, GenericBounds<'hir>),
2735
2736     /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2737     Impl(Impl<'hir>),
2738 }
2739
2740 #[derive(Debug, HashStable_Generic)]
2741 pub struct Impl<'hir> {
2742     pub unsafety: Unsafety,
2743     pub polarity: ImplPolarity,
2744     pub defaultness: Defaultness,
2745     // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata
2746     // decoding as `Span`s cannot be decoded when a `Session` is not available.
2747     pub defaultness_span: Option<Span>,
2748     pub constness: Constness,
2749     pub generics: Generics<'hir>,
2750
2751     /// The trait being implemented, if any.
2752     pub of_trait: Option<TraitRef<'hir>>,
2753
2754     pub self_ty: &'hir Ty<'hir>,
2755     pub items: &'hir [ImplItemRef],
2756 }
2757
2758 impl ItemKind<'_> {
2759     pub fn generics(&self) -> Option<&Generics<'_>> {
2760         Some(match *self {
2761             ItemKind::Fn(_, ref generics, _)
2762             | ItemKind::TyAlias(_, ref generics)
2763             | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
2764             | ItemKind::Enum(_, ref generics)
2765             | ItemKind::Struct(_, ref generics)
2766             | ItemKind::Union(_, ref generics)
2767             | ItemKind::Trait(_, _, ref generics, _, _)
2768             | ItemKind::Impl(Impl { ref generics, .. }) => generics,
2769             _ => return None,
2770         })
2771     }
2772
2773     pub fn descr(&self) -> &'static str {
2774         match self {
2775             ItemKind::ExternCrate(..) => "extern crate",
2776             ItemKind::Use(..) => "`use` import",
2777             ItemKind::Static(..) => "static item",
2778             ItemKind::Const(..) => "constant item",
2779             ItemKind::Fn(..) => "function",
2780             ItemKind::Macro(..) => "macro",
2781             ItemKind::Mod(..) => "module",
2782             ItemKind::ForeignMod { .. } => "extern block",
2783             ItemKind::GlobalAsm(..) => "global asm item",
2784             ItemKind::TyAlias(..) => "type alias",
2785             ItemKind::OpaqueTy(..) => "opaque type",
2786             ItemKind::Enum(..) => "enum",
2787             ItemKind::Struct(..) => "struct",
2788             ItemKind::Union(..) => "union",
2789             ItemKind::Trait(..) => "trait",
2790             ItemKind::TraitAlias(..) => "trait alias",
2791             ItemKind::Impl(..) => "implementation",
2792         }
2793     }
2794 }
2795
2796 /// A reference from an trait to one of its associated items. This
2797 /// contains the item's id, naturally, but also the item's name and
2798 /// some other high-level details (like whether it is an associated
2799 /// type or method, and whether it is public). This allows other
2800 /// passes to find the impl they want without loading the ID (which
2801 /// means fewer edges in the incremental compilation graph).
2802 #[derive(Encodable, Debug, HashStable_Generic)]
2803 pub struct TraitItemRef {
2804     pub id: TraitItemId,
2805     #[stable_hasher(project(name))]
2806     pub ident: Ident,
2807     pub kind: AssocItemKind,
2808     pub span: Span,
2809     pub defaultness: Defaultness,
2810 }
2811
2812 /// A reference from an impl to one of its associated items. This
2813 /// contains the item's ID, naturally, but also the item's name and
2814 /// some other high-level details (like whether it is an associated
2815 /// type or method, and whether it is public). This allows other
2816 /// passes to find the impl they want without loading the ID (which
2817 /// means fewer edges in the incremental compilation graph).
2818 #[derive(Debug, HashStable_Generic)]
2819 pub struct ImplItemRef {
2820     pub id: ImplItemId,
2821     #[stable_hasher(project(name))]
2822     pub ident: Ident,
2823     pub kind: AssocItemKind,
2824     pub span: Span,
2825     pub defaultness: Defaultness,
2826 }
2827
2828 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2829 pub enum AssocItemKind {
2830     Const,
2831     Fn { has_self: bool },
2832     Type,
2833 }
2834
2835 // The bodies for items are stored "out of line", in a separate
2836 // hashmap in the `Crate`. Here we just record the hir-id of the item
2837 // so it can fetched later.
2838 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
2839 pub struct ForeignItemId {
2840     pub def_id: LocalDefId,
2841 }
2842
2843 impl ForeignItemId {
2844     #[inline]
2845     pub fn hir_id(&self) -> HirId {
2846         // Items are always HIR owners.
2847         HirId::make_owner(self.def_id)
2848     }
2849 }
2850
2851 /// A reference from a foreign block to one of its items. This
2852 /// contains the item's ID, naturally, but also the item's name and
2853 /// some other high-level details (like whether it is an associated
2854 /// type or method, and whether it is public). This allows other
2855 /// passes to find the impl they want without loading the ID (which
2856 /// means fewer edges in the incremental compilation graph).
2857 #[derive(Debug, HashStable_Generic)]
2858 pub struct ForeignItemRef {
2859     pub id: ForeignItemId,
2860     #[stable_hasher(project(name))]
2861     pub ident: Ident,
2862     pub span: Span,
2863 }
2864
2865 #[derive(Debug)]
2866 pub struct ForeignItem<'hir> {
2867     pub ident: Ident,
2868     pub kind: ForeignItemKind<'hir>,
2869     pub def_id: LocalDefId,
2870     pub span: Span,
2871     pub vis: Visibility<'hir>,
2872 }
2873
2874 impl ForeignItem<'_> {
2875     #[inline]
2876     pub fn hir_id(&self) -> HirId {
2877         // Items are always HIR owners.
2878         HirId::make_owner(self.def_id)
2879     }
2880
2881     pub fn foreign_item_id(&self) -> ForeignItemId {
2882         ForeignItemId { def_id: self.def_id }
2883     }
2884 }
2885
2886 /// An item within an `extern` block.
2887 #[derive(Debug, HashStable_Generic)]
2888 pub enum ForeignItemKind<'hir> {
2889     /// A foreign function.
2890     Fn(&'hir FnDecl<'hir>, &'hir [Ident], Generics<'hir>),
2891     /// A foreign static item (`static ext: u8`).
2892     Static(&'hir Ty<'hir>, Mutability),
2893     /// A foreign type.
2894     Type,
2895 }
2896
2897 /// A variable captured by a closure.
2898 #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)]
2899 pub struct Upvar {
2900     // First span where it is accessed (there can be multiple).
2901     pub span: Span,
2902 }
2903
2904 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2905 // has length > 0 if the trait is found through an chain of imports, starting with the
2906 // import/use statement in the scope where the trait is used.
2907 #[derive(Encodable, Decodable, Clone, Debug)]
2908 pub struct TraitCandidate {
2909     pub def_id: DefId,
2910     pub import_ids: SmallVec<[LocalDefId; 1]>,
2911 }
2912
2913 #[derive(Copy, Clone, Debug, HashStable_Generic)]
2914 pub enum OwnerNode<'hir> {
2915     Item(&'hir Item<'hir>),
2916     ForeignItem(&'hir ForeignItem<'hir>),
2917     TraitItem(&'hir TraitItem<'hir>),
2918     ImplItem(&'hir ImplItem<'hir>),
2919     Crate(&'hir Mod<'hir>),
2920 }
2921
2922 impl<'hir> OwnerNode<'hir> {
2923     pub fn ident(&self) -> Option<Ident> {
2924         match self {
2925             OwnerNode::Item(Item { ident, .. })
2926             | OwnerNode::ForeignItem(ForeignItem { ident, .. })
2927             | OwnerNode::ImplItem(ImplItem { ident, .. })
2928             | OwnerNode::TraitItem(TraitItem { ident, .. }) => Some(*ident),
2929             OwnerNode::Crate(..) => None,
2930         }
2931     }
2932
2933     pub fn span(&self) -> Span {
2934         match self {
2935             OwnerNode::Item(Item { span, .. })
2936             | OwnerNode::ForeignItem(ForeignItem { span, .. })
2937             | OwnerNode::ImplItem(ImplItem { span, .. })
2938             | OwnerNode::TraitItem(TraitItem { span, .. })
2939             | OwnerNode::Crate(Mod { inner: span, .. }) => *span,
2940         }
2941     }
2942
2943     pub fn fn_decl(&self) -> Option<&FnDecl<'hir>> {
2944         match self {
2945             OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
2946             | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
2947             | OwnerNode::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
2948             OwnerNode::ForeignItem(ForeignItem {
2949                 kind: ForeignItemKind::Fn(fn_decl, _, _),
2950                 ..
2951             }) => Some(fn_decl),
2952             _ => None,
2953         }
2954     }
2955
2956     pub fn body_id(&self) -> Option<BodyId> {
2957         match self {
2958             OwnerNode::TraitItem(TraitItem {
2959                 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
2960                 ..
2961             })
2962             | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
2963             | OwnerNode::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
2964             _ => None,
2965         }
2966     }
2967
2968     pub fn generics(&self) -> Option<&'hir Generics<'hir>> {
2969         match self {
2970             OwnerNode::TraitItem(TraitItem { generics, .. })
2971             | OwnerNode::ImplItem(ImplItem { generics, .. }) => Some(generics),
2972             OwnerNode::Item(item) => item.kind.generics(),
2973             _ => None,
2974         }
2975     }
2976
2977     pub fn def_id(self) -> LocalDefId {
2978         match self {
2979             OwnerNode::Item(Item { def_id, .. })
2980             | OwnerNode::TraitItem(TraitItem { def_id, .. })
2981             | OwnerNode::ImplItem(ImplItem { def_id, .. })
2982             | OwnerNode::ForeignItem(ForeignItem { def_id, .. }) => *def_id,
2983             OwnerNode::Crate(..) => crate::CRATE_HIR_ID.owner,
2984         }
2985     }
2986
2987     pub fn expect_item(self) -> &'hir Item<'hir> {
2988         match self {
2989             OwnerNode::Item(n) => n,
2990             _ => panic!(),
2991         }
2992     }
2993
2994     pub fn expect_foreign_item(self) -> &'hir ForeignItem<'hir> {
2995         match self {
2996             OwnerNode::ForeignItem(n) => n,
2997             _ => panic!(),
2998         }
2999     }
3000
3001     pub fn expect_impl_item(self) -> &'hir ImplItem<'hir> {
3002         match self {
3003             OwnerNode::ImplItem(n) => n,
3004             _ => panic!(),
3005         }
3006     }
3007
3008     pub fn expect_trait_item(self) -> &'hir TraitItem<'hir> {
3009         match self {
3010             OwnerNode::TraitItem(n) => n,
3011             _ => panic!(),
3012         }
3013     }
3014 }
3015
3016 impl<'hir> Into<OwnerNode<'hir>> for &'hir Item<'hir> {
3017     fn into(self) -> OwnerNode<'hir> {
3018         OwnerNode::Item(self)
3019     }
3020 }
3021
3022 impl<'hir> Into<OwnerNode<'hir>> for &'hir ForeignItem<'hir> {
3023     fn into(self) -> OwnerNode<'hir> {
3024         OwnerNode::ForeignItem(self)
3025     }
3026 }
3027
3028 impl<'hir> Into<OwnerNode<'hir>> for &'hir ImplItem<'hir> {
3029     fn into(self) -> OwnerNode<'hir> {
3030         OwnerNode::ImplItem(self)
3031     }
3032 }
3033
3034 impl<'hir> Into<OwnerNode<'hir>> for &'hir TraitItem<'hir> {
3035     fn into(self) -> OwnerNode<'hir> {
3036         OwnerNode::TraitItem(self)
3037     }
3038 }
3039
3040 impl<'hir> Into<Node<'hir>> for OwnerNode<'hir> {
3041     fn into(self) -> Node<'hir> {
3042         match self {
3043             OwnerNode::Item(n) => Node::Item(n),
3044             OwnerNode::ForeignItem(n) => Node::ForeignItem(n),
3045             OwnerNode::ImplItem(n) => Node::ImplItem(n),
3046             OwnerNode::TraitItem(n) => Node::TraitItem(n),
3047             OwnerNode::Crate(n) => Node::Crate(n),
3048         }
3049     }
3050 }
3051
3052 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3053 pub enum Node<'hir> {
3054     Param(&'hir Param<'hir>),
3055     Item(&'hir Item<'hir>),
3056     ForeignItem(&'hir ForeignItem<'hir>),
3057     TraitItem(&'hir TraitItem<'hir>),
3058     ImplItem(&'hir ImplItem<'hir>),
3059     Variant(&'hir Variant<'hir>),
3060     Field(&'hir FieldDef<'hir>),
3061     AnonConst(&'hir AnonConst),
3062     Expr(&'hir Expr<'hir>),
3063     Stmt(&'hir Stmt<'hir>),
3064     PathSegment(&'hir PathSegment<'hir>),
3065     Ty(&'hir Ty<'hir>),
3066     TraitRef(&'hir TraitRef<'hir>),
3067     Binding(&'hir Pat<'hir>),
3068     Pat(&'hir Pat<'hir>),
3069     Arm(&'hir Arm<'hir>),
3070     Block(&'hir Block<'hir>),
3071     Local(&'hir Local<'hir>),
3072
3073     /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
3074     /// with synthesized constructors.
3075     Ctor(&'hir VariantData<'hir>),
3076
3077     Lifetime(&'hir Lifetime),
3078     GenericParam(&'hir GenericParam<'hir>),
3079     Visibility(&'hir Visibility<'hir>),
3080
3081     Crate(&'hir Mod<'hir>),
3082
3083     Infer(&'hir InferArg),
3084 }
3085
3086 impl<'hir> Node<'hir> {
3087     /// Get the identifier of this `Node`, if applicable.
3088     ///
3089     /// # Edge cases
3090     ///
3091     /// Calling `.ident()` on a [`Node::Ctor`] will return `None`
3092     /// because `Ctor`s do not have identifiers themselves.
3093     /// Instead, call `.ident()` on the parent struct/variant, like so:
3094     ///
3095     /// ```ignore (illustrative)
3096     /// ctor
3097     ///     .ctor_hir_id()
3098     ///     .and_then(|ctor_id| tcx.hir().find(tcx.hir().get_parent_node(ctor_id)))
3099     ///     .and_then(|parent| parent.ident())
3100     /// ```
3101     pub fn ident(&self) -> Option<Ident> {
3102         match self {
3103             Node::TraitItem(TraitItem { ident, .. })
3104             | Node::ImplItem(ImplItem { ident, .. })
3105             | Node::ForeignItem(ForeignItem { ident, .. })
3106             | Node::Field(FieldDef { ident, .. })
3107             | Node::Variant(Variant { ident, .. })
3108             | Node::Item(Item { ident, .. })
3109             | Node::PathSegment(PathSegment { ident, .. }) => Some(*ident),
3110             Node::Lifetime(lt) => Some(lt.name.ident()),
3111             Node::GenericParam(p) => Some(p.name.ident()),
3112             Node::Param(..)
3113             | Node::AnonConst(..)
3114             | Node::Expr(..)
3115             | Node::Stmt(..)
3116             | Node::Block(..)
3117             | Node::Ctor(..)
3118             | Node::Pat(..)
3119             | Node::Binding(..)
3120             | Node::Arm(..)
3121             | Node::Local(..)
3122             | Node::Visibility(..)
3123             | Node::Crate(..)
3124             | Node::Ty(..)
3125             | Node::TraitRef(..)
3126             | Node::Infer(..) => None,
3127         }
3128     }
3129
3130     pub fn fn_decl(&self) -> Option<&FnDecl<'hir>> {
3131         match self {
3132             Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3133             | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3134             | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3135             Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
3136                 Some(fn_decl)
3137             }
3138             _ => None,
3139         }
3140     }
3141
3142     pub fn body_id(&self) -> Option<BodyId> {
3143         match self {
3144             Node::TraitItem(TraitItem {
3145                 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3146                 ..
3147             })
3148             | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3149             | Node::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3150             _ => None,
3151         }
3152     }
3153
3154     pub fn generics(&self) -> Option<&'hir Generics<'hir>> {
3155         match self {
3156             Node::TraitItem(TraitItem { generics, .. })
3157             | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
3158             Node::Item(item) => item.kind.generics(),
3159             _ => None,
3160         }
3161     }
3162
3163     pub fn hir_id(&self) -> Option<HirId> {
3164         match self {
3165             Node::Item(Item { def_id, .. })
3166             | Node::TraitItem(TraitItem { def_id, .. })
3167             | Node::ImplItem(ImplItem { def_id, .. })
3168             | Node::ForeignItem(ForeignItem { def_id, .. }) => Some(HirId::make_owner(*def_id)),
3169             Node::Field(FieldDef { hir_id, .. })
3170             | Node::AnonConst(AnonConst { hir_id, .. })
3171             | Node::Expr(Expr { hir_id, .. })
3172             | Node::Stmt(Stmt { hir_id, .. })
3173             | Node::Ty(Ty { hir_id, .. })
3174             | Node::Binding(Pat { hir_id, .. })
3175             | Node::Pat(Pat { hir_id, .. })
3176             | Node::Arm(Arm { hir_id, .. })
3177             | Node::Block(Block { hir_id, .. })
3178             | Node::Local(Local { hir_id, .. })
3179             | Node::Lifetime(Lifetime { hir_id, .. })
3180             | Node::Param(Param { hir_id, .. })
3181             | Node::Infer(InferArg { hir_id, .. })
3182             | Node::GenericParam(GenericParam { hir_id, .. }) => Some(*hir_id),
3183             Node::TraitRef(TraitRef { hir_ref_id, .. }) => Some(*hir_ref_id),
3184             Node::PathSegment(PathSegment { hir_id, .. }) => *hir_id,
3185             Node::Variant(Variant { id, .. }) => Some(*id),
3186             Node::Ctor(variant) => variant.ctor_hir_id(),
3187             Node::Crate(_) | Node::Visibility(_) => None,
3188         }
3189     }
3190
3191     /// Returns `Constness::Const` when this node is a const fn/impl/item.
3192     pub fn constness_for_typeck(&self) -> Constness {
3193         match self {
3194             Node::Item(Item {
3195                 kind: ItemKind::Fn(FnSig { header: FnHeader { constness, .. }, .. }, ..),
3196                 ..
3197             })
3198             | Node::TraitItem(TraitItem {
3199                 kind: TraitItemKind::Fn(FnSig { header: FnHeader { constness, .. }, .. }, ..),
3200                 ..
3201             })
3202             | Node::ImplItem(ImplItem {
3203                 kind: ImplItemKind::Fn(FnSig { header: FnHeader { constness, .. }, .. }, ..),
3204                 ..
3205             })
3206             | Node::Item(Item { kind: ItemKind::Impl(Impl { constness, .. }), .. }) => *constness,
3207
3208             Node::Item(Item { kind: ItemKind::Const(..), .. })
3209             | Node::TraitItem(TraitItem { kind: TraitItemKind::Const(..), .. })
3210             | Node::ImplItem(ImplItem { kind: ImplItemKind::Const(..), .. }) => Constness::Const,
3211
3212             _ => Constness::NotConst,
3213         }
3214     }
3215
3216     pub fn as_owner(self) -> Option<OwnerNode<'hir>> {
3217         match self {
3218             Node::Item(i) => Some(OwnerNode::Item(i)),
3219             Node::ForeignItem(i) => Some(OwnerNode::ForeignItem(i)),
3220             Node::TraitItem(i) => Some(OwnerNode::TraitItem(i)),
3221             Node::ImplItem(i) => Some(OwnerNode::ImplItem(i)),
3222             Node::Crate(i) => Some(OwnerNode::Crate(i)),
3223             _ => None,
3224         }
3225     }
3226 }
3227
3228 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3229 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
3230 mod size_asserts {
3231     rustc_data_structures::static_assert_size!(super::Block<'static>, 48);
3232     rustc_data_structures::static_assert_size!(super::Expr<'static>, 64);
3233     rustc_data_structures::static_assert_size!(super::Pat<'static>, 88);
3234     rustc_data_structures::static_assert_size!(super::QPath<'static>, 24);
3235     rustc_data_structures::static_assert_size!(super::Ty<'static>, 72);
3236
3237     rustc_data_structures::static_assert_size!(super::Item<'static>, 184);
3238     rustc_data_structures::static_assert_size!(super::TraitItem<'static>, 128);
3239     rustc_data_structures::static_assert_size!(super::ImplItem<'static>, 152);
3240     rustc_data_structures::static_assert_size!(super::ForeignItem<'static>, 136);
3241 }