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