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