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