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