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