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