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