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