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