Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_text/tests/annealer_corpus/rustc_hir.rs

181 KiB, 1 run

created by r1870400018:11812, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1// ignore-tidy-filelength
2use std::borrow::Cow;
3use std::fmt;
4use std::ops::Not;
5
6use rustc_abi::ExternAbi;
7use rustc_ast::attr::AttributeExt;
8use rustc_ast::token::DocFragmentKind;
9use rustc_ast::util::parser::ExprPrecedence;
10use rustc_ast::{
11 self as ast, FloatTy, InlineAsmOptions, InlineAsmTemplatePiece, IntTy, Label, LitIntType,
12 LitKind, TraitObjectSyntax, UintTy, UnsafeBinderCastKind, join_path_idents,
13};
14pub use rustc_ast::{
15 AssignOp, AssignOpKind, AttrId, AttrStyle, BinOp, BinOpKind, BindingMode, BorrowKind,
16 BoundConstness, BoundPolarity, ByRef, CaptureBy, DelimArgs, ImplPolarity, IsAuto,
17 MetaItemInner, MetaItemLit, Movability, Mutability, Pinnedness, UnOp,
18};
19use rustc_data_structures::fingerprint::Fingerprint;
20use rustc_data_structures::sorted_map::SortedMap;
21use rustc_data_structures::steal::Steal;
22use rustc_data_structures::tagged_ptr::TaggedRef;
23use rustc_error_messages::{DiagArgValue, IntoDiagArg};
24use rustc_index::IndexVec;
25use rustc_macros::{Decodable, Encodable, StableHash};
26use rustc_span::def_id::LocalDefId;
27use rustc_span::{
28 BytePos, DUMMY_SP, DesugaringKind, ErrorGuaranteed, Ident, Span, Spanned, Symbol, kw, sym,
29};
30use rustc_target::asm::InlineAsmRegOrRegClass;
31use smallvec::SmallVec;
32use thin_vec::ThinVec;
33use tracing::debug;
34
35use crate::attrs::AttributeKind;
36use crate::def::{CtorKind, DefKind, MacroKinds, PerNS, Res};
37use crate::def_id::{DefId, LocalDefIdMap};
38pub(crate) use crate::hir_id::{HirId, ItemLocalId, ItemLocalMap, OwnerId};
39use crate::intravisit::{FnKind, VisitorExt};
40use crate::lints::DelayedLints;
41
42#[derive(Debug, Copy, Clone, PartialEq, Eq, StableHash)]
43pub enum AngleBrackets {
44 /// E.g. `Path`.
45 Missing,
46 /// E.g. `Path<>`.
47 Empty,
48 /// E.g. `Path<T>`.
49 Full,
50}
51
52#[derive(Debug, Copy, Clone, PartialEq, Eq, StableHash)]
53pub enum LifetimeSource {
54 /// E.g. `&Type`, `&'_ Type`, `&'a Type`, `&mut Type`, `&'_ mut Type`, `&'a mut Type`
55 Reference,
56
57 /// E.g. `ContainsLifetime`, `ContainsLifetime<>`, `ContainsLifetime<'_>`,
58 /// `ContainsLifetime<'a>`
59 Path { angle_brackets: AngleBrackets },
60
61 /// E.g. `impl Trait + '_`, `impl Trait + 'a`
62 OutlivesBound,
63
64 /// E.g. `impl Trait + use<'_>`, `impl Trait + use<'a>`
65 PreciseCapturing,
66
67 /// Other usages which have not yet been categorized. Feel free to
68 /// add new sources that you find useful.
69 ///
70 /// Some non-exhaustive examples:
71 /// - `where T: 'a`
72 /// - `fn(_: dyn Trait + 'a)`
73 Other,
74}
75
76#[derive(Debug, Copy, Clone, PartialEq, Eq, StableHash)]
77pub enum LifetimeSyntax {
78 /// E.g. `&Type`, `ContainsLifetime`
79 Implicit,
80
81 /// E.g. `&'_ Type`, `ContainsLifetime<'_>`, `impl Trait + '_`, `impl Trait + use<'_>`
82 ExplicitAnonymous,
83
84 /// E.g. `&'a Type`, `ContainsLifetime<'a>`, `impl Trait + 'a`, `impl Trait + use<'a>`
85 ExplicitBound,
86}
87
88impl From<Ident> for LifetimeSyntax {
89 fn from(ident: Ident) -> Self {
90 let name = ident.name;
91
92 if name == sym::empty {
93 unreachable!("A lifetime name should never be empty");
94 } else if name == kw::UnderscoreLifetime {
95 LifetimeSyntax::ExplicitAnonymous
96 } else {
97 debug_assert!(name.as_str().starts_with('\''));
98 LifetimeSyntax::ExplicitBound
99 }
100 }
101}
102
103/// A lifetime. The valid field combinations are non-obvious and not all
104/// combinations are possible. The following example shows some of
105/// them. See also the comments on `LifetimeKind` and `LifetimeSource`.
106///
107/// ```
108/// #[repr(C)]
109/// struct S<'a>(&'a u32); // res=Param, name='a, source=Reference, syntax=ExplicitBound
110/// unsafe extern "C" {
111/// fn f1(s: S); // res=Param, name='_, source=Path, syntax=Implicit
112/// fn f2(s: S<'_>); // res=Param, name='_, source=Path, syntax=ExplicitAnonymous
113/// fn f3<'a>(s: S<'a>); // res=Param, name='a, source=Path, syntax=ExplicitBound
114/// }
115///
116/// struct St<'a> { x: &'a u32 } // res=Param, name='a, source=Reference, syntax=ExplicitBound
117/// fn f() {
118/// _ = St { x: &0 }; // res=Infer, name='_, source=Path, syntax=Implicit
119/// _ = St::<'_> { x: &0 }; // res=Infer, name='_, source=Path, syntax=ExplicitAnonymous
120/// }
121///
122/// struct Name<'a>(&'a str); // res=Param, name='a, source=Reference, syntax=ExplicitBound
123/// const A: Name = Name("a"); // res=Static, name='_, source=Path, syntax=Implicit
124/// const B: &str = ""; // res=Static, name='_, source=Reference, syntax=Implicit
125/// static C: &'_ str = ""; // res=Static, name='_, source=Reference, syntax=ExplicitAnonymous
126/// static D: &'static str = ""; // res=Static, name='static, source=Reference, syntax=ExplicitBound
127///
128/// trait Tr {}
129/// fn tr(_: Box<dyn Tr>) {} // res=ImplicitObjectLifetimeDefault, name='_, source=Other, syntax=Implicit
130///
131/// fn capture_outlives<'a>() ->
132/// impl FnOnce() + 'a // res=Param, ident='a, source=OutlivesBound, syntax=ExplicitBound
133/// {
134/// || {}
135/// }
136///
137/// fn capture_precise<'a>() ->
138/// impl FnOnce() + use<'a> // res=Param, ident='a, source=PreciseCapturing, syntax=ExplicitBound
139/// {
140/// || {}
141/// }
142///
143/// // (commented out because these cases trigger errors)
144/// // struct S1<'a>(&'a str); // res=Param, name='a, source=Reference, syntax=ExplicitBound
145/// // struct S2(S1); // res=Error, name='_, source=Path, syntax=Implicit
146/// // struct S3(S1<'_>); // res=Error, name='_, source=Path, syntax=ExplicitAnonymous
147/// // struct S4(S1<'a>); // res=Error, name='a, source=Path, syntax=ExplicitBound
148/// ```
149///
150/// Some combinations that cannot occur are `LifetimeSyntax::Implicit` with
151/// `LifetimeSource::OutlivesBound` or `LifetimeSource::PreciseCapturing`
152/// — there's no way to "elide" these lifetimes.
153#[derive(Debug, Copy, Clone, StableHash)]
154// Raise the alignment to at least 4 bytes.
155// This is relied on in other parts of the compiler (for pointer tagging):
156// <https://github.com/rust-lang/rust/blob/ce5fdd7d42aba9a2925692e11af2bd39cf37798a/compiler/rustc_data_structures/src/tagged_ptr.rs#L163>
157// Removing this `repr(4)` will cause the compiler to not build on platforms
158// like `m68k` Linux, where the alignment of u32 and usize is only 2.
159// Since `repr(align)` may only raise alignment, this has no effect on
160// platforms where the alignment is already sufficient.
161#[repr(align(4))]
162pub struct Lifetime {
163 #[stable_hash(ignore)]
164 pub hir_id: HirId,
165
166 /// Either a named lifetime definition (e.g. `'a`, `'static`) or an
167 /// anonymous lifetime (`'_`, either explicitly written, or inserted for
168 /// things like `&type`).
169 pub ident: Ident,
170
171 /// Semantics of this lifetime.
172 pub kind: LifetimeKind,
173
174 /// The context in which the lifetime occurred. See `Lifetime::suggestion`
175 /// for example use.
176 pub source: LifetimeSource,
177
178 /// The syntax that the user used to declare this lifetime. See
179 /// `Lifetime::suggestion` for example use.
180 pub syntax: LifetimeSyntax,
181}
182
183#[derive(Debug, Copy, Clone, StableHash)]
184pub enum ParamName {
185 /// Some user-given name like `T` or `'x`.
186 Plain(Ident),
187
188 /// Indicates an illegal name was given and an error has been
189 /// reported (so we should squelch other derived errors).
190 ///
191 /// Occurs when, e.g., `'_` is used in the wrong place, or a
192 /// lifetime name is duplicated.
193 Error(Ident),
194
195 /// Synthetic name generated when user elided a lifetime in an impl header.
196 ///
197 /// E.g., the lifetimes in cases like these:
198 /// ```ignore (fragment)
199 /// impl Foo for &u32
200 /// impl Foo<'_> for u32
201 /// ```
202 /// in that case, we rewrite to
203 /// ```ignore (fragment)
204 /// impl<'f> Foo for &'f u32
205 /// impl<'f> Foo<'f> for u32
206 /// ```
207 /// where `'f` is something like `Fresh(0)`. The indices are
208 /// unique per impl, but not necessarily continuous.
209 Fresh,
210}
211
212impl ParamName {
213 pub fn ident(&self) -> Ident {
214 match *self {
215 ParamName::Plain(ident) | ParamName::Error(ident) => ident,
216 ParamName::Fresh => Ident::with_dummy_span(kw::UnderscoreLifetime),
217 }
218 }
219}
220
221#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, StableHash)]
222pub enum LifetimeKind {
223 /// User-given names or fresh (synthetic) names.
224 Param(LocalDefId),
225
226 /// Implicit lifetime in a context like `dyn Foo`. This is
227 /// distinguished from implicit lifetimes elsewhere because the
228 /// lifetime that they default to must appear elsewhere within the
229 /// enclosing type. This means that, in an `impl Trait` context, we
230 /// don't have to create a parameter for them. That is, `impl
231 /// Trait<Item = &u32>` expands to an opaque type like `type
232 /// Foo<'a> = impl Trait<Item = &'a u32>`, but `impl Trait<item =
233 /// dyn Bar>` expands to `type Foo = impl Trait<Item = dyn Bar +
234 /// 'static>`. The latter uses `ImplicitObjectLifetimeDefault` so
235 /// that surrounding code knows not to create a lifetime
236 /// parameter.
237 ImplicitObjectLifetimeDefault,
238
239 /// Indicates an error during lowering (usually `'_` in wrong place)
240 /// that was already reported.
241 Error(ErrorGuaranteed),
242
243 /// User wrote an anonymous lifetime, either `'_` or nothing (which gets
244 /// converted to `'_`). The semantics of this lifetime should be inferred
245 /// by typechecking code.
246 Infer,
247
248 /// User wrote `'static` or nothing (which gets converted to `'_`).
249 Static,
250}
251
252impl LifetimeKind {
253 fn is_elided(&self) -> bool {
254 match self {
255 LifetimeKind::ImplicitObjectLifetimeDefault | LifetimeKind::Infer => true,
256
257 // It might seem surprising that `Fresh` counts as not *elided*
258 // -- but this is because, as far as the code in the compiler is
259 // concerned -- `Fresh` variants act equivalently to "some fresh name".
260 // They correspond to early-bound regions on an impl, in other words.
261 LifetimeKind::Error(..) | LifetimeKind::Param(..) | LifetimeKind::Static => false,
262 }
263 }
264}
265
266impl fmt::Display for Lifetime {
267 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
268 self.ident.name.fmt(f)
269 }
270}
271
272impl Lifetime {
273 pub fn new(
274 hir_id: HirId,
275 ident: Ident,
276 kind: LifetimeKind,
277 source: LifetimeSource,
278 syntax: LifetimeSyntax,
279 ) -> Lifetime {
280 let lifetime = Lifetime { hir_id, ident, kind, source, syntax };
281
282 // Sanity check: elided lifetimes form a strict subset of anonymous lifetimes.
283 #[cfg(debug_assertions)]
284 match (lifetime.is_elided(), lifetime.is_anonymous()) {
285 (false, false) => {} // e.g. `'a`
286 (false, true) => {} // e.g. explicit `'_`
287 (true, true) => {} // e.g. `&x`
288 (true, false) => panic!("bad Lifetime"),
289 }
290
291 lifetime
292 }
293
294 pub fn is_elided(&self) -> bool {
295 self.kind.is_elided()
296 }
297
298 pub fn is_anonymous(&self) -> bool {
299 self.ident.name == kw::UnderscoreLifetime
300 }
301
302 pub fn is_implicit(&self) -> bool {
303 matches!(self.syntax, LifetimeSyntax::Implicit)
304 }
305
306 pub fn is_static(&self) -> bool {
307 self.kind == LifetimeKind::Static
308 }
309
310 pub fn suggestion(&self, new_lifetime: &str) -> (Span, String) {
311 use LifetimeSource::*;
312 use LifetimeSyntax::*;
313
314 debug_assert!(new_lifetime.starts_with('\''));
315
316 match (self.syntax, self.source) {
317 // The user wrote `'a` or `'_`.
318 (ExplicitBound | ExplicitAnonymous, _) => (self.ident.span, format!("{new_lifetime}")),
319
320 // The user wrote `Path<T>`, and omitted the `'_,`.
321 (Implicit, Path { angle_brackets: AngleBrackets::Full }) => {
322 (self.ident.span, format!("{new_lifetime}, "))
323 }
324
325 // The user wrote `Path<>`, and omitted the `'_`..
326 (Implicit, Path { angle_brackets: AngleBrackets::Empty }) => {
327 (self.ident.span, format!("{new_lifetime}"))
328 }
329
330 // The user wrote `Path` and omitted the `<'_>`.
331 (Implicit, Path { angle_brackets: AngleBrackets::Missing }) => {
332 (self.ident.span.shrink_to_hi(), format!("<{new_lifetime}>"))
333 }
334
335 // The user wrote `&type` or `&mut type`.
336 (Implicit, Reference) => (self.ident.span, format!("{new_lifetime} ")),
337
338 (Implicit, source) => {
339 unreachable!("can't suggest for a implicit lifetime of {source:?}")
340 }
341 }
342 }
343}
344
345/// A `Path` is essentially Rust's notion of a name; for instance,
346/// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
347/// along with a bunch of supporting information.
348#[derive(Debug, Clone, Copy, StableHash)]
349pub struct Path<'hir, R = Res> {
350 pub span: Span,
351 /// The resolution for the path.
352 pub res: R,
353 /// The segments in the path: the things separated by `::`.
354 pub segments: &'hir [PathSegment<'hir>],
355}
356
357/// Up to three resolutions for type, value and macro namespaces.
358pub type UsePath<'hir> = Path<'hir, PerNS<Option<Res>>>;
359
360impl Path<'_> {
361 pub fn is_global(&self) -> bool {
362 self.segments.first().is_some_and(|segment| segment.ident.name == kw::PathRoot)
363 }
364}
365
366/// A segment of a path: an identifier, an optional lifetime, and a set of
367/// types.
368#[derive(Debug, Clone, Copy, StableHash)]
369pub struct PathSegment<'hir> {
370 /// The identifier portion of this path segment.
371 pub ident: Ident,
372 #[stable_hash(ignore)]
373 pub hir_id: HirId,
374 pub res: Res,
375
376 /// Type/lifetime parameters attached to this path. They come in
377 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
378 /// this is more than just simple syntactic sugar; the use of
379 /// parens affects the region binding rules, so we preserve the
380 /// distinction.
381 pub args: Option<&'hir GenericArgs<'hir>>,
382
383 /// Whether to infer remaining type parameters, if any.
384 /// This only applies to expression and pattern paths, and
385 /// out of those only the segments with no type parameters
386 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
387 pub infer_args: bool,
388}
389
390impl<'hir> PathSegment<'hir> {
391 /// Converts an identifier to the corresponding segment.
392 pub fn new(ident: Ident, hir_id: HirId, res: Res) -> PathSegment<'hir> {
393 PathSegment { ident, hir_id, res, infer_args: true, args: None }
394 }
395
396 pub fn invalid() -> Self {
397 Self::new(Ident::dummy(), HirId::INVALID, Res::Err)
398 }
399
400 pub fn args(&self) -> &GenericArgs<'hir> {
401 if let Some(ref args) = self.args { args } else { GenericArgs::NONE }
402 }
403}
404
405#[derive(Clone, Copy, Debug, StableHash)]
406pub enum ConstItemRhs<'hir> {
407 Body(BodyId),
408 TypeConst(&'hir ConstArg<'hir>),
409}
410
411impl<'hir> ConstItemRhs<'hir> {
412 pub fn hir_id(&self) -> HirId {
413 match self {
414 ConstItemRhs::Body(body_id) => body_id.hir_id,
415 ConstItemRhs::TypeConst(ct_arg) => ct_arg.hir_id,
416 }
417 }
418
419 pub fn span<'tcx>(&self, tcx: impl crate::intravisit::HirTyCtxt<'tcx>) -> Span {
420 match self {
421 ConstItemRhs::Body(body_id) => tcx.hir_body(*body_id).value.span,
422 ConstItemRhs::TypeConst(ct_arg) => ct_arg.span,
423 }
424 }
425}
426
427/// A constant that enters the type system, used for arguments to const generics (e.g. array lengths).
428///
429/// These are distinct from [`AnonConst`] as anon consts in the type system are not allowed
430/// to use any generic parameters, therefore we must represent `N` differently. Additionally
431/// future designs for supporting generic parameters in const arguments will likely not use
432/// an anon const based design.
433///
434/// So, `ConstArg` (specifically, [`ConstArgKind`]) distinguishes between const args
435/// that are [just paths](ConstArgKind::Path) (currently just bare const params)
436/// versus const args that are literals or have arbitrary computations (e.g., `{ 1 + 3 }`).
437///
438/// For an explanation of the `Unambig` generic parameter see the dev-guide:
439/// <https://rustc-dev-guide.rust-lang.org/ambig-unambig-ty-and-consts.html>
440#[derive(Clone, Copy, Debug, StableHash)]
441#[repr(C)]
442pub struct ConstArg<'hir, Unambig = ()> {
443 #[stable_hash(ignore)]
444 pub hir_id: HirId,
445 pub kind: ConstArgKind<'hir, Unambig>,
446 pub span: Span,
447}
448
449impl<'hir> ConstArg<'hir, AmbigArg> {
450 /// Converts a `ConstArg` in an ambiguous position to one in an unambiguous position.
451 ///
452 /// Functions accepting unambiguous consts may expect the [`ConstArgKind::Infer`] variant
453 /// to be used. Care should be taken to separately handle infer consts when calling this
454 /// function as it cannot be handled by downstream code making use of the returned const.
455 ///
456 /// In practice this may mean overriding the [`Visitor::visit_infer`][visit_infer] method on hir visitors, or
457 /// specifically matching on [`GenericArg::Infer`] when handling generic arguments.
458 ///
459 /// [visit_infer]: [rustc_hir::intravisit::Visitor::visit_infer]
460 pub fn as_unambig_ct(&self) -> &ConstArg<'hir> {
461 // SAFETY: `ConstArg` is `repr(C)` and `ConstArgKind` is marked `repr(u8)` so that the
462 // layout is the same across different ZST type arguments.
463 let ptr = self as *const ConstArg<'hir, AmbigArg> as *const ConstArg<'hir, ()>;
464 unsafe { &*ptr }
465 }
466}
467
468impl<'hir> ConstArg<'hir> {
469 /// Converts a `ConstArg` in an unambiguous position to one in an ambiguous position. This is
470 /// fallible as the [`ConstArgKind::Infer`] variant is not present in ambiguous positions.
471 ///
472 /// Functions accepting ambiguous consts will not handle the [`ConstArgKind::Infer`] variant, if
473 /// infer consts are relevant to you then care should be taken to handle them separately.
474 pub fn try_as_ambig_ct(&self) -> Option<&ConstArg<'hir, AmbigArg>> {
475 if let ConstArgKind::Infer(()) = self.kind {
476 return None;
477 }
478
479 // SAFETY: `ConstArg` is `repr(C)` and `ConstArgKind` is marked `repr(u8)` so that the layout is
480 // the same across different ZST type arguments. We also asserted that the `self` is
481 // not a `ConstArgKind::Infer` so there is no risk of transmuting a `()` to `AmbigArg`.
482 let ptr = self as *const ConstArg<'hir> as *const ConstArg<'hir, AmbigArg>;
483 Some(unsafe { &*ptr })
484 }
485}
486
487impl<'hir, Unambig> ConstArg<'hir, Unambig> {
488 pub fn anon_const_hir_id(&self) -> Option<HirId> {
489 match self.kind {
490 ConstArgKind::Anon(ac) => Some(ac.hir_id),
491 _ => None,
492 }
493 }
494}
495
496/// See [`ConstArg`].
497#[derive(Clone, Copy, Debug, StableHash)]
498#[repr(u8, C)]
499pub enum ConstArgKind<'hir, Unambig = ()> {
500 Tup(&'hir [&'hir ConstArg<'hir, Unambig>]),
501 /// **Note:** Currently this is only used for bare const params
502 /// (`N` where `fn foo<const N: usize>(...)`),
503 /// not paths to any const (`N` where `const N: usize = ...`).
504 ///
505 /// However, in the future, we'll be using it for all of those.
506 Path(QPath<'hir>),
507 Anon(&'hir AnonConst),
508 /// Represents construction of struct/struct variants
509 Struct(QPath<'hir>, &'hir [&'hir ConstArgExprField<'hir>]),
510 /// Tuple constructor variant
511 TupleCall(QPath<'hir>, &'hir [&'hir ConstArg<'hir>]),
512 /// Array literal argument
513 Array(&'hir ConstArgArrayExpr<'hir>),
514 /// Error const
515 Error(ErrorGuaranteed),
516 /// This variant is not always used to represent inference consts, sometimes
517 /// [`GenericArg::Infer`] is used instead.
518 Infer(Unambig),
519 Literal {
520 lit: LitKind,
521 negated: bool,
522 },
523}
524
525#[derive(Clone, Copy, Debug, StableHash)]
526pub struct ConstArgExprField<'hir> {
527 pub hir_id: HirId,
528 pub span: Span,
529 pub field: Ident,
530 pub expr: &'hir ConstArg<'hir>,
531}
532
533#[derive(Clone, Copy, Debug, StableHash)]
534pub struct ConstArgArrayExpr<'hir> {
535 pub span: Span,
536 pub elems: &'hir [&'hir ConstArg<'hir>],
537}
538
539#[derive(Clone, Copy, Debug, StableHash)]
540pub struct InferArg {
541 #[stable_hash(ignore)]
542 pub hir_id: HirId,
543 pub span: Span,
544}
545
546impl InferArg {
547 pub fn to_ty(&self) -> Ty<'static> {
548 Ty { kind: TyKind::Infer(()), span: self.span, hir_id: self.hir_id }
549 }
550}
551
552#[derive(Debug, Clone, Copy, StableHash)]
553pub enum GenericArg<'hir> {
554 Lifetime(&'hir Lifetime),
555 Type(&'hir Ty<'hir, AmbigArg>),
556 Const(&'hir ConstArg<'hir, AmbigArg>),
557 /// Inference variables in [`GenericArg`] are always represented by
558 /// `GenericArg::Infer` instead of the `Infer` variants on [`TyKind`] and
559 /// [`ConstArgKind`] as it is not clear until hir ty lowering whether a
560 /// `_` argument is a type or const argument.
561 ///
562 /// However, some builtin types' generic arguments are represented by [`TyKind`]
563 /// without a [`GenericArg`], instead directly storing a [`Ty`] or [`ConstArg`]. In
564 /// such cases they *are* represented by the `Infer` variants on [`TyKind`] and
565 /// [`ConstArgKind`] as it is not ambiguous whether the argument is a type or const.
566 Infer(InferArg),
567}
568
569impl GenericArg<'_> {
570 pub fn span(&self) -> Span {
571 match self {
572 GenericArg::Lifetime(l) => l.ident.span,
573 GenericArg::Type(t) => t.span,
574 GenericArg::Const(c) => c.span,
575 GenericArg::Infer(i) => i.span,
576 }
577 }
578
579 pub fn hir_id(&self) -> HirId {
580 match self {
581 GenericArg::Lifetime(l) => l.hir_id,
582 GenericArg::Type(t) => t.hir_id,
583 GenericArg::Const(c) => c.hir_id,
584 GenericArg::Infer(i) => i.hir_id,
585 }
586 }
587
588 pub fn descr(&self) -> &'static str {
589 match self {
590 GenericArg::Lifetime(_) => "lifetime",
591 GenericArg::Type(_) => "type",
592 GenericArg::Const(_) => "constant",
593 GenericArg::Infer(_) => "placeholder",
594 }
595 }
596
597 pub fn to_ord(&self) -> ast::ParamKindOrd {
598 match self {
599 GenericArg::Lifetime(_) => ast::ParamKindOrd::Lifetime,
600 GenericArg::Type(_) | GenericArg::Const(_) | GenericArg::Infer(_) => {
601 ast::ParamKindOrd::TypeOrConst
602 }
603 }
604 }
605
606 pub fn is_ty_or_const(&self) -> bool {
607 match self {
608 GenericArg::Lifetime(_) => false,
609 GenericArg::Type(_) | GenericArg::Const(_) | GenericArg::Infer(_) => true,
610 }
611 }
612}
613
614/// The generic arguments and associated item constraints of a path segment.
615#[derive(Debug, Clone, Copy, StableHash)]
616pub struct GenericArgs<'hir> {
617 /// The generic arguments for this path segment.
618 pub args: &'hir [GenericArg<'hir>],
619 /// The associated item constraints for this path segment.
620 pub constraints: &'hir [AssocItemConstraint<'hir>],
621 /// Whether the arguments were written in parenthesized form (e.g., `Fn(T) -> U`).
622 ///
623 /// This is required mostly for pretty-printing and diagnostics,
624 /// but also for changing lifetime elision rules to be "function-like".
625 pub parenthesized: GenericArgsParentheses,
626 /// The span encompassing the arguments, constraints and the surrounding brackets (`<>` or `()`).
627 ///
628 /// For example:
629 ///
630 /// ```ignore (illustrative)
631 /// Foo<A, B, AssocTy = D> Fn(T, U, V) -> W
632 /// ^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^
633 /// ```
634 ///
635 /// Note that this may be:
636 /// - empty, if there are no generic brackets (but there may be hidden lifetimes)
637 /// - dummy, if this was generated during desugaring
638 pub span_ext: Span,
639}
640
641impl<'hir> GenericArgs<'hir> {
642 pub const NONE: &'hir GenericArgs<'hir> = &GenericArgs {
643 args: &[],
644 constraints: &[],
645 parenthesized: GenericArgsParentheses::No,
646 span_ext: DUMMY_SP,
647 };
648
649 /// Obtain the list of input types and the output type if the generic arguments are parenthesized.
650 ///
651 /// Returns the `Ty0, Ty1, ...` and the `RetTy` in `Trait(Ty0, Ty1, ...) -> RetTy`.
652 /// Panics if the parenthesized arguments have an incorrect form (this shouldn't happen).
653 pub fn paren_sugar_inputs_output(&self) -> Option<(&[Ty<'hir>], &Ty<'hir>)> {
654 if self.parenthesized != GenericArgsParentheses::ParenSugar {
655 return None;
656 }
657
658 let inputs = self
659 .args
660 .iter()
661 .find_map(|arg| {
662 let GenericArg::Type(ty) = arg else { return None };
663 let TyKind::Tup(tys) = &ty.kind else { return None };
664 Some(tys)
665 })
666 .unwrap();
667
668 Some((inputs, self.paren_sugar_output_inner()))
669 }
670
671 /// Obtain the output type if the generic arguments are parenthesized.
672 ///
673 /// Returns the `RetTy` in `Trait(Ty0, Ty1, ...) -> RetTy`.
674 /// Panics if the parenthesized arguments have an incorrect form (this shouldn't happen).
675 pub fn paren_sugar_output(&self) -> Option<&Ty<'hir>> {
676 (self.parenthesized == GenericArgsParentheses::ParenSugar)
677 .then(|| self.paren_sugar_output_inner())
678 }
679
680 fn paren_sugar_output_inner(&self) -> &Ty<'hir> {
681 let [constraint] = self.constraints.try_into().unwrap();
682 debug_assert_eq!(constraint.ident.name, sym::Output);
683 constraint.ty().unwrap()
684 }
685
686 pub fn has_err(&self) -> Option<ErrorGuaranteed> {
687 self.args
688 .iter()
689 .find_map(|arg| {
690 let GenericArg::Type(ty) = arg else { return None };
691 let TyKind::Err(guar) = ty.kind else { return None };
692 Some(guar)
693 })
694 .or_else(|| {
695 self.constraints.iter().find_map(|constraint| {
696 let TyKind::Err(guar) = constraint.ty()?.kind else { return None };
697 Some(guar)
698 })
699 })
700 }
701
702 #[inline]
703 pub fn num_lifetime_params(&self) -> usize {
704 self.args.iter().filter(|arg| matches!(arg, GenericArg::Lifetime(_))).count()
705 }
706
707 #[inline]
708 pub fn has_lifetime_params(&self) -> bool {
709 self.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)))
710 }
711
712 #[inline]
713 /// This function returns the number of type and const generic params.
714 /// It should only be used for diagnostics.
715 pub fn num_generic_params(&self) -> usize {
716 self.args.iter().filter(|arg| !matches!(arg, GenericArg::Lifetime(_))).count()
717 }
718
719 /// The span encompassing the arguments and constraints[^1] inside the surrounding brackets.
720 ///
721 /// Returns `None` if the span is empty (i.e., no brackets) or dummy.
722 ///
723 /// [^1]: Unless of the form `-> Ty` (see [`GenericArgsParentheses`]).
724 pub fn span(&self) -> Option<Span> {
725 let span_ext = self.span_ext()?;
726 Some(span_ext.with_lo(span_ext.lo() + BytePos(1)).with_hi(span_ext.hi() - BytePos(1)))
727 }
728
729 /// Returns span encompassing arguments and their surrounding `<>` or `()`
730 pub fn span_ext(&self) -> Option<Span> {
731 Some(self.span_ext).filter(|span| !span.is_empty())
732 }
733
734 pub fn is_empty(&self) -> bool {
735 self.args.is_empty()
736 }
737}
738
739#[derive(Copy, Clone, PartialEq, Eq, Debug, StableHash)]
740pub enum GenericArgsParentheses {
741 No,
742 /// Bounds for `feature(return_type_notation)`, like `T: Trait<method(..): Send>`,
743 /// where the args are explicitly elided with `..`
744 ReturnTypeNotation,
745 /// parenthesized function-family traits, like `T: Fn(u32) -> i32`
746 ParenSugar,
747}
748
749/// The modifiers on a trait bound.
750#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, StableHash)]
751pub struct TraitBoundModifiers {
752 pub constness: BoundConstness,
753 pub polarity: BoundPolarity,
754}
755
756impl TraitBoundModifiers {
757 pub const NONE: Self =
758 TraitBoundModifiers { constness: BoundConstness::Never, polarity: BoundPolarity::Positive };
759}
760
761#[derive(Clone, Copy, Debug, StableHash)]
762pub enum GenericBound<'hir> {
763 Trait(PolyTraitRef<'hir>),
764 Outlives(&'hir Lifetime),
765 Use(&'hir [PreciseCapturingArg<'hir>], Span),
766}
767
768impl GenericBound<'_> {
769 pub fn trait_ref(&self) -> Option<&TraitRef<'_>> {
770 match self {
771 GenericBound::Trait(data) => Some(&data.trait_ref),
772 _ => None,
773 }
774 }
775
776 pub fn span(&self) -> Span {
777 match self {
778 GenericBound::Trait(t, ..) => t.span,
779 GenericBound::Outlives(l) => l.ident.span,
780 GenericBound::Use(_, span) => *span,
781 }
782 }
783}
784
785pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
786
787#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, StableHash, Debug)]
788pub enum MissingLifetimeKind {
789 /// An explicit `'_`.
790 Underscore,
791 /// An elided lifetime `&' ty`.
792 Ampersand,
793 /// An elided lifetime in brackets with written brackets.
794 Comma,
795 /// An elided lifetime with elided brackets.
796 Brackets,
797}
798
799#[derive(Copy, Clone, Debug, StableHash)]
800pub enum LifetimeParamKind {
801 // Indicates that the lifetime definition was explicitly declared (e.g., in
802 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
803 Explicit,
804
805 // Indication that the lifetime was elided (e.g., in both cases in
806 // `fn foo(x: &u8) -> &'_ u8 { x }`).
807 Elided(MissingLifetimeKind),
808
809 // Indication that the lifetime name was somehow in error.
810 Error,
811}
812
813#[derive(Debug, Clone, Copy, StableHash)]
814pub enum GenericParamKind<'hir> {
815 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
816 Lifetime {
817 kind: LifetimeParamKind,
818 },
819 Type {
820 default: Option<&'hir Ty<'hir>>,
821 synthetic: bool,
822 },
823 Const {
824 ty: &'hir Ty<'hir>,
825 /// Optional default value for the const generic param
826 default: Option<&'hir ConstArg<'hir>>,
827 },
828}
829
830#[derive(Debug, Clone, Copy, StableHash)]
831pub struct GenericParam<'hir> {
832 #[stable_hash(ignore)]
833 pub hir_id: HirId,
834 pub def_id: LocalDefId,
835 pub name: ParamName,
836 pub span: Span,
837 pub pure_wrt_drop: bool,
838 pub kind: GenericParamKind<'hir>,
839 pub colon_span: Option<Span>,
840 pub source: GenericParamSource,
841}
842
843impl<'hir> GenericParam<'hir> {
844 /// Synthetic type-parameters are inserted after normal ones.
845 /// In order for normal parameters to be able to refer to synthetic ones,
846 /// scans them first.
847 pub fn is_impl_trait(&self) -> bool {
848 matches!(self.kind, GenericParamKind::Type { synthetic: true, .. })
849 }
850
851 /// This can happen for `async fn`, e.g. `async fn f<'_>(&'_ self)`.
852 ///
853 /// See `lifetime_to_generic_param` in `rustc_ast_lowering` for more information.
854 pub fn is_elided_lifetime(&self) -> bool {
855 matches!(self.kind, GenericParamKind::Lifetime { kind: LifetimeParamKind::Elided(_) })
856 }
857
858 pub fn is_lifetime(&self) -> bool {
859 matches!(self.kind, GenericParamKind::Lifetime { .. })
860 }
861}
862
863/// Records where the generic parameter originated from.
864///
865/// This can either be from an item's generics, in which case it's typically
866/// early-bound (but can be a late-bound lifetime in functions, for example),
867/// or from a `for<...>` binder, in which case it's late-bound (and notably,
868/// does not show up in the parent item's generics).
869#[derive(Debug, Clone, Copy, StableHash)]
870pub enum GenericParamSource {
871 // Early or late-bound parameters defined on an item
872 Generics,
873 // Late-bound parameters defined via a `for<...>`
874 Binder,
875}
876
877#[derive(Default)]
878pub struct GenericParamCount {
879 pub lifetimes: usize,
880 pub types: usize,
881 pub consts: usize,
882 pub infer: usize,
883}
884
885/// Represents lifetimes and type parameters attached to a declaration
886/// of a function, enum, trait, etc.
887#[derive(Debug, Clone, Copy, StableHash)]
888pub struct Generics<'hir> {
889 pub params: &'hir [GenericParam<'hir>],
890 pub predicates: &'hir [WherePredicate<'hir>],
891 pub has_where_clause_predicates: bool,
892 pub where_clause_span: Span,
893 pub span: Span,
894}
895
896impl<'hir> Generics<'hir> {
897 pub const fn empty() -> &'hir Generics<'hir> {
898 const NOPE: Generics<'_> = Generics {
899 params: &[],
900 predicates: &[],
901 has_where_clause_predicates: false,
902 where_clause_span: DUMMY_SP,
903 span: DUMMY_SP,
904 };
905 &NOPE
906 }
907
908 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'hir>> {
909 self.params.iter().find(|&param| name == param.name.ident().name)
910 }
911
912 /// If there are generic parameters, return where to introduce a new one.
913 pub fn span_for_lifetime_suggestion(&self) -> Option<Span> {
914 if let Some(first) = self.params.first()
915 && self.span.contains(first.span)
916 {
917 // `fn foo<A>(t: impl Trait)`
918 // ^ suggest `'a, ` here
919 Some(first.span.shrink_to_lo())
920 } else {
921 None
922 }
923 }
924
925 /// If there are generic parameters, return where to introduce a new one.
926 pub fn span_for_param_suggestion(&self) -> Option<Span> {
927 self.params.iter().any(|p| self.span.contains(p.span)).then(|| {
928 // `fn foo<A>(t: impl Trait)`
929 // ^ suggest `, T: Trait` here
930 self.span.with_lo(self.span.hi() - BytePos(1)).shrink_to_lo()
931 })
932 }
933
934 /// `Span` where further predicates would be suggested, accounting for trailing commas, like
935 /// in `fn foo<T>(t: T) where T: Foo,` so we don't suggest two trailing commas.
936 pub fn tail_span_for_predicate_suggestion(&self) -> Span {
937 let end = self.where_clause_span.shrink_to_hi();
938 if self.has_where_clause_predicates {
939 self.predicates
940 .iter()
941 .rfind(|&p| p.kind.in_where_clause())
942 .map_or(end, |p| p.span)
943 .shrink_to_hi()
944 .to(end)
945 } else {
946 end
947 }
948 }
949
950 pub fn add_where_or_trailing_comma(&self) -> &'static str {
951 if self.has_where_clause_predicates {
952 ","
953 } else if self.where_clause_span.is_empty() {
954 " where"
955 } else {
956 // No where clause predicates, but we have `where` token
957 ""
958 }
959 }
960
961 pub fn bounds_for_param(
962 &self,
963 param_def_id: LocalDefId,
964 ) -> impl Iterator<Item = &WhereBoundPredicate<'hir>> {
965 self.predicates.iter().filter_map(move |pred| match pred.kind {
966 WherePredicateKind::BoundPredicate(bp)
967 if bp.is_param_bound(param_def_id.to_def_id()) =>
968 {
969 Some(bp)
970 }
971 _ => None,
972 })
973 }
974
975 pub fn outlives_for_param(
976 &self,
977 param_def_id: LocalDefId,
978 ) -> impl Iterator<Item = &WhereRegionPredicate<'_>> {
979 self.predicates.iter().filter_map(move |pred| match pred.kind {
980 WherePredicateKind::RegionPredicate(rp) if rp.is_param_bound(param_def_id) => Some(rp),
981 _ => None,
982 })
983 }
984
985 /// Returns a suggestable empty span right after the "final" bound of the generic parameter.
986 ///
987 /// If that bound needs to be wrapped in parentheses to avoid ambiguity with
988 /// subsequent bounds, it also returns an empty span for an open parenthesis
989 /// as the second component.
990 ///
991 /// E.g., adding `+ 'static` after `Fn() -> dyn Future<Output = ()>` or
992 /// `Fn() -> &'static dyn Debug` requires parentheses:
993 /// `Fn() -> (dyn Future<Output = ()>) + 'static` and
994 /// `Fn() -> &'static (dyn Debug) + 'static`, respectively.
995 pub fn bounds_span_for_suggestions(
996 &self,
997 param_def_id: LocalDefId,
998 ) -> Option<(Span, Option<Span>)> {
999 self.bounds_for_param(param_def_id).flat_map(|bp| bp.bounds.iter().rev()).find_map(
1000 |bound| {
1001 let span_for_parentheses = if let Some(trait_ref) = bound.trait_ref()
1002 && let [.., segment] = trait_ref.path.segments
1003 && let Some(ret_ty) = segment.args().paren_sugar_output()
1004 && let ret_ty = ret_ty.peel_refs()
1005 && let TyKind::TraitObject(_, tagged_ptr) = ret_ty.kind
1006 && let TraitObjectSyntax::Dyn = tagged_ptr.tag()
1007 && ret_ty.span.can_be_used_for_suggestions()
1008 {
1009 Some(ret_ty.span)
1010 } else {
1011 None
1012 };
1013
1014 span_for_parentheses.map_or_else(
1015 || {
1016 // We include bounds that come from a `#[derive(_)]` but point at the user's
1017 // code, as we use this method to get a span appropriate for suggestions.
1018 let bs = bound.span();
1019 // We use `from_expansion` instead of `can_be_used_for_suggestions` because
1020 // the trait bound from imperfect derives do point at the type parameter,
1021 // but expanded to a where clause, so we want to ignore those. This is only
1022 // true for derive intrinsics.
1023 bs.from_expansion().not().then(|| (bs.shrink_to_hi(), None))
1024 },
1025 |span| Some((span.shrink_to_hi(), Some(span.shrink_to_lo()))),
1026 )
1027 },
1028 )
1029 }
1030
1031 pub fn span_for_predicate_removal(&self, pos: usize) -> Span {
1032 let predicate = &self.predicates[pos];
1033 let span = predicate.span;
1034
1035 if !predicate.kind.in_where_clause() {
1036 // <T: ?Sized, U>
1037 // ^^^^^^^^
1038 return span;
1039 }
1040
1041 // We need to find out which comma to remove.
1042 if pos < self.predicates.len() - 1 {
1043 let next_pred = &self.predicates[pos + 1];
1044 if next_pred.kind.in_where_clause() {
1045 // where T: ?Sized, Foo: Bar,
1046 // ^^^^^^^^^^^
1047 return span.until(next_pred.span);
1048 }
1049 }
1050
1051 if pos > 0 {
1052 let prev_pred = &self.predicates[pos - 1];
1053 if prev_pred.kind.in_where_clause() {
1054 // where Foo: Bar, T: ?Sized,
1055 // ^^^^^^^^^^^
1056 return prev_pred.span.shrink_to_hi().to(span);
1057 }
1058 }
1059
1060 // This is the only predicate in the where clause.
1061 // where T: ?Sized
1062 // ^^^^^^^^^^^^^^^
1063 self.where_clause_span
1064 }
1065
1066 pub fn span_for_bound_removal(&self, predicate_pos: usize, bound_pos: usize) -> Span {
1067 let predicate = &self.predicates[predicate_pos];
1068 let bounds = predicate.kind.bounds();
1069
1070 if bounds.len() == 1 {
1071 return self.span_for_predicate_removal(predicate_pos);
1072 }
1073
1074 let bound_span = bounds[bound_pos].span();
1075 if bound_pos < bounds.len() - 1 {
1076 // If there's another bound after the current bound
1077 // include the following '+' e.g.:
1078 //
1079 // `T: Foo + CurrentBound + Bar`
1080 // ^^^^^^^^^^^^^^^
1081 bound_span.to(bounds[bound_pos + 1].span().shrink_to_lo())
1082 } else {
1083 // If the current bound is the last bound
1084 // include the preceding '+' E.g.:
1085 //
1086 // `T: Foo + Bar + CurrentBound`
1087 // ^^^^^^^^^^^^^^^
1088 bound_span.with_lo(bounds[bound_pos - 1].span().hi())
1089 }
1090 }
1091}
1092
1093/// A single predicate in a where-clause.
1094#[derive(Debug, Clone, Copy, StableHash)]
1095pub struct WherePredicate<'hir> {
1096 #[stable_hash(ignore)]
1097 pub hir_id: HirId,
1098 pub span: Span,
1099 pub kind: &'hir WherePredicateKind<'hir>,
1100}
1101
1102/// The kind of a single predicate in a where-clause.
1103#[derive(Debug, Clone, Copy, StableHash)]
1104pub enum WherePredicateKind<'hir> {
1105 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
1106 BoundPredicate(WhereBoundPredicate<'hir>),
1107 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
1108 RegionPredicate(WhereRegionPredicate<'hir>),
1109 /// An equality predicate (unsupported).
1110 EqPredicate(WhereEqPredicate<'hir>),
1111}
1112
1113impl<'hir> WherePredicateKind<'hir> {
1114 pub fn in_where_clause(&self) -> bool {
1115 match self {
1116 WherePredicateKind::BoundPredicate(p) => p.origin == PredicateOrigin::WhereClause,
1117 WherePredicateKind::RegionPredicate(p) => p.in_where_clause,
1118 WherePredicateKind::EqPredicate(_) => false,
1119 }
1120 }
1121
1122 pub fn bounds(&self) -> GenericBounds<'hir> {
1123 match self {
1124 WherePredicateKind::BoundPredicate(p) => p.bounds,
1125 WherePredicateKind::RegionPredicate(p) => p.bounds,
1126 WherePredicateKind::EqPredicate(_) => &[],
1127 }
1128 }
1129}
1130
1131#[derive(Copy, Clone, Debug, StableHash, PartialEq, Eq)]
1132pub enum PredicateOrigin {
1133 WhereClause,
1134 GenericParam,
1135 ImplTrait,
1136}
1137
1138/// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
1139#[derive(Debug, Clone, Copy, StableHash)]
1140pub struct WhereBoundPredicate<'hir> {
1141 /// Origin of the predicate.
1142 pub origin: PredicateOrigin,
1143 /// Any generics from a `for` binding.
1144 pub bound_generic_params: &'hir [GenericParam<'hir>],
1145 /// The type being bounded.
1146 pub bounded_ty: &'hir Ty<'hir>,
1147 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
1148 pub bounds: GenericBounds<'hir>,
1149}
1150
1151impl<'hir> WhereBoundPredicate<'hir> {
1152 /// Returns `true` if `param_def_id` matches the `bounded_ty` of this predicate.
1153 pub fn is_param_bound(&self, param_def_id: DefId) -> bool {
1154 self.bounded_ty.as_generic_param().is_some_and(|(def_id, _)| def_id == param_def_id)
1155 }
1156}
1157
1158/// A lifetime predicate (e.g., `'a: 'b + 'c`).
1159#[derive(Debug, Clone, Copy, StableHash)]
1160pub struct WhereRegionPredicate<'hir> {
1161 pub in_where_clause: bool,
1162 pub lifetime: &'hir Lifetime,
1163 pub bounds: GenericBounds<'hir>,
1164}
1165
1166impl<'hir> WhereRegionPredicate<'hir> {
1167 /// Returns `true` if `param_def_id` matches the `lifetime` of this predicate.
1168 fn is_param_bound(&self, param_def_id: LocalDefId) -> bool {
1169 self.lifetime.kind == LifetimeKind::Param(param_def_id)
1170 }
1171}
1172
1173/// An equality predicate (e.g., `T = int`); currently unsupported.
1174#[derive(Debug, Clone, Copy, StableHash)]
1175pub struct WhereEqPredicate<'hir> {
1176 pub lhs_ty: &'hir Ty<'hir>,
1177 pub rhs_ty: &'hir Ty<'hir>,
1178}
1179
1180/// HIR node coupled with its parent's id in the same HIR owner.
1181///
1182/// The parent is trash when the node is a HIR owner.
1183#[derive(Clone, Copy, Debug)]
1184pub struct ParentedNode<'tcx> {
1185 pub parent: ItemLocalId,
1186 pub node: Node<'tcx>,
1187}
1188
1189/// Arguments passed to an attribute macro.
1190#[derive(Clone, Debug, StableHash, Encodable, Decodable)]
1191pub enum AttrArgs {
1192 /// No arguments: `#[attr]`.
1193 Empty,
1194 /// Delimited arguments: `#[attr()/[]/{}]`.
1195 Delimited(DelimArgs),
1196 /// Arguments of a key-value attribute: `#[attr = "value"]`.
1197 Eq {
1198 /// Span of the `=` token.
1199 eq_span: Span,
1200 /// The "value".
1201 expr: MetaItemLit,
1202 },
1203}
1204
1205#[derive(Clone, Debug, StableHash, Encodable, Decodable)]
1206pub struct AttrPath {
1207 pub segments: Box<[Symbol]>,
1208 pub span: Span,
1209}
1210
1211impl IntoDiagArg for AttrPath {
1212 fn into_diag_arg(self, path: &mut Option<std::path::PathBuf>) -> DiagArgValue {
1213 self.to_string().into_diag_arg(path)
1214 }
1215}
1216
1217impl AttrPath {
1218 pub fn from_ast(path: &ast::Path, lower_span: impl Copy + Fn(Span) -> Span) -> Self {
1219 AttrPath {
1220 segments: path
1221 .segments
1222 .iter()
1223 .map(|i| i.ident.name)
1224 .collect::<Vec<_>>()
1225 .into_boxed_slice(),
1226 span: lower_span(path.span),
1227 }
1228 }
1229}
1230
1231impl fmt::Display for AttrPath {
1232 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1233 write!(
1234 f,
1235 "{}",
1236 join_path_idents(self.segments.iter().map(|i| Ident { name: *i, span: DUMMY_SP }))
1237 )
1238 }
1239}
1240
1241#[derive(Clone, Debug, StableHash, Encodable, Decodable)]
1242pub struct AttrItem {
1243 // Not lowered to hir::Path because we have no NodeId to resolve to.
1244 pub path: AttrPath,
1245 pub args: AttrArgs,
1246 pub id: HashIgnoredAttrId,
1247 /// Denotes if the attribute decorates the following construct (outer)
1248 /// or the construct this attribute is contained within (inner).
1249 pub style: AttrStyle,
1250 /// Span of the entire attribute
1251 pub span: Span,
1252}
1253
1254/// The derived implementation of [`StableHash`] on [`Attribute`]s shouldn't hash
1255/// [`AttrId`]s. By wrapping them in this, we make sure we never do.
1256#[derive(Copy, Debug, Encodable, Decodable, Clone)]
1257pub struct HashIgnoredAttrId {
1258 pub attr_id: AttrId,
1259}
1260
1261/// Many functions on this type have their documentation in the [`AttributeExt`] trait,
1262/// since they defer their implementation directly to that trait.
1263#[derive(Clone, Debug, Encodable, Decodable, StableHash)]
1264pub enum Attribute {
1265 /// A parsed built-in attribute.
1266 ///
1267 /// Each attribute has a span connected to it. However, you must be somewhat careful using it.
1268 /// That's because sometimes we merge multiple attributes together, like when an item has
1269 /// multiple `repr` attributes. In this case the span might not be very useful.
1270 Parsed(AttributeKind),
1271
1272 /// An attribute that could not be parsed, out of a token-like representation.
1273 /// This is the case for custom tool attributes.
1274 Unparsed(Box<AttrItem>),
1275}
1276
1277impl Attribute {
1278 pub fn get_normal_item(&self) -> &AttrItem {
1279 match &self {
1280 Attribute::Unparsed(normal) => &normal,
1281 _ => panic!("unexpected parsed attribute"),
1282 }
1283 }
1284
1285 pub fn unwrap_normal_item(self) -> AttrItem {
1286 match self {
1287 Attribute::Unparsed(normal) => *normal,
1288 _ => panic!("unexpected parsed attribute"),
1289 }
1290 }
1291
1292 pub fn value_lit(&self) -> Option<&MetaItemLit> {
1293 match &self {
1294 Attribute::Unparsed(n) => match n.as_ref() {
1295 AttrItem { args: AttrArgs::Eq { eq_span: _, expr }, .. } => Some(expr),
1296 _ => None,
1297 },
1298 _ => None,
1299 }
1300 }
1301
1302 pub fn is_parsed_attr(&self) -> bool {
1303 match self {
1304 Attribute::Parsed(_) => true,
1305 Attribute::Unparsed(_) => false,
1306 }
1307 }
1308
1309 pub fn is_prefix_attr_for_suggestions(&self) -> bool {
1310 match self {
1311 Attribute::Unparsed(attr) => attr.span.desugaring_kind().is_none(),
1312 // Other parsed attributes that can appear on expressions originate from source and
1313 // should make suggestions treat the expression like a prefixed form.
1314 Attribute::Parsed(_) => true,
1315 }
1316 }
1317}
1318
1319impl AttributeExt for Attribute {
1320 #[inline]
1321 fn id(&self) -> AttrId {
1322 match &self {
1323 Attribute::Unparsed(u) => u.id.attr_id,
1324 _ => panic!(),
1325 }
1326 }
1327
1328 #[inline]
1329 fn meta_item_list(&self) -> Option<ThinVec<ast::MetaItemInner>> {
1330 match &self {
1331 Attribute::Unparsed(n) => match n.as_ref() {
1332 AttrItem { args: AttrArgs::Delimited(d), .. } => {
1333 ast::MetaItemKind::list_from_tokens(d.tokens.clone())
1334 }
1335 _ => None,
1336 },
1337 _ => None,
1338 }
1339 }
1340
1341 #[inline]
1342 fn value_str(&self) -> Option<Symbol> {
1343 self.value_lit().and_then(|x| x.value_as_str())
1344 }
1345
1346 #[inline]
1347 fn value_span(&self) -> Option<Span> {
1348 self.value_lit().map(|i| i.span)
1349 }
1350
1351 /// For a single-segment attribute, returns its name; otherwise, returns `None`.
1352 #[inline]
1353 fn name(&self) -> Option<Symbol> {
1354 match &self {
1355 Attribute::Unparsed(n) => {
1356 if let [ident] = n.path.segments.as_ref() {
1357 Some(*ident)
1358 } else {
1359 None
1360 }
1361 }
1362 _ => None,
1363 }
1364 }
1365
1366 #[inline]
1367 fn path_matches(&self, name: &[Symbol]) -> bool {
1368 match &self {
1369 Attribute::Unparsed(n) => n.path.segments.iter().eq(name),
1370 _ => false,
1371 }
1372 }
1373
1374 #[inline]
1375 fn is_doc_comment(&self) -> Option<Span> {
1376 if let Attribute::Parsed(AttributeKind::DocComment { span, .. }) = self {
1377 Some(*span)
1378 } else {
1379 None
1380 }
1381 }
1382
1383 #[inline]
1384 fn span(&self) -> Span {
1385 match &self {
1386 Attribute::Unparsed(u) => u.span,
1387 // FIXME: should not be needed anymore when all attrs are parsed
1388 Attribute::Parsed(AttributeKind::DocComment { span, .. }) => *span,
1389 Attribute::Parsed(AttributeKind::Deprecated { span, .. }) => *span,
1390 Attribute::Parsed(AttributeKind::CfgTrace(cfgs)) => cfgs[0].1,
1391 a => panic!("can't get the span of an arbitrary parsed attribute: {a:?}"),
1392 }
1393 }
1394
1395 #[inline]
1396 fn is_word(&self) -> bool {
1397 match &self {
1398 Attribute::Unparsed(n) => {
1399 matches!(n.args, AttrArgs::Empty)
1400 }
1401 _ => false,
1402 }
1403 }
1404
1405 #[inline]
1406 fn symbol_path(&self) -> Option<SmallVec<[Symbol; 1]>> {
1407 match &self {
1408 Attribute::Unparsed(n) => Some(n.path.segments.iter().copied().collect()),
1409 _ => None,
1410 }
1411 }
1412
1413 fn path_span(&self) -> Option<Span> {
1414 match &self {
1415 Attribute::Unparsed(attr) => Some(attr.path.span),
1416 Attribute::Parsed(_) => None,
1417 }
1418 }
1419
1420 #[inline]
1421 fn doc_str(&self) -> Option<Symbol> {
1422 match &self {
1423 Attribute::Parsed(AttributeKind::DocComment { comment, .. }) => Some(*comment),
1424 _ => None,
1425 }
1426 }
1427
1428 fn is_automatically_derived_attr(&self) -> bool {
1429 matches!(self, Attribute::Parsed(AttributeKind::AutomaticallyDerived))
1430 }
1431
1432 #[inline]
1433 fn doc_str_and_fragment_kind(&self) -> Option<(Symbol, DocFragmentKind)> {
1434 match &self {
1435 Attribute::Parsed(AttributeKind::DocComment { kind, comment, .. }) => {
1436 Some((*comment, *kind))
1437 }
1438 _ => None,
1439 }
1440 }
1441
1442 fn doc_resolution_scope(&self) -> Option<AttrStyle> {
1443 match self {
1444 Attribute::Parsed(AttributeKind::DocComment { style, .. }) => Some(*style),
1445 Attribute::Unparsed(attr) if self.has_name(sym::doc) && self.value_str().is_some() => {
1446 Some(attr.style)
1447 }
1448 _ => None,
1449 }
1450 }
1451
1452 fn is_proc_macro_attr(&self) -> bool {
1453 matches!(
1454 self,
1455 Attribute::Parsed(
1456 AttributeKind::ProcMacro
1457 | AttributeKind::ProcMacroAttribute
1458 | AttributeKind::ProcMacroDerive { .. }
1459 )
1460 )
1461 }
1462
1463 fn is_doc_hidden(&self) -> bool {
1464 matches!(self, Attribute::Parsed(AttributeKind::Doc(d)) if d.hidden.is_some())
1465 }
1466
1467 fn is_doc_keyword_or_attribute(&self) -> bool {
1468 matches!(self, Attribute::Parsed(AttributeKind::Doc(d)) if d.attribute.is_some() || d.keyword.is_some())
1469 }
1470
1471 fn is_rustc_doc_primitive(&self) -> bool {
1472 matches!(self, Attribute::Parsed(AttributeKind::RustcDocPrimitive(..)))
1473 }
1474}
1475
1476// FIXME(fn_delegation): use function delegation instead of manually forwarding
1477impl Attribute {
1478 #[inline]
1479 pub fn id(&self) -> AttrId {
1480 AttributeExt::id(self)
1481 }
1482
1483 #[inline]
1484 pub fn name(&self) -> Option<Symbol> {
1485 AttributeExt::name(self)
1486 }
1487
1488 #[inline]
1489 pub fn meta_item_list(&self) -> Option<ThinVec<MetaItemInner>> {
1490 AttributeExt::meta_item_list(self)
1491 }
1492
1493 #[inline]
1494 pub fn value_str(&self) -> Option<Symbol> {
1495 AttributeExt::value_str(self)
1496 }
1497
1498 #[inline]
1499 pub fn value_span(&self) -> Option<Span> {
1500 AttributeExt::value_span(self)
1501 }
1502
1503 #[inline]
1504 pub fn path_matches(&self, name: &[Symbol]) -> bool {
1505 AttributeExt::path_matches(self, name)
1506 }
1507
1508 #[inline]
1509 pub fn is_doc_comment(&self) -> Option<Span> {
1510 AttributeExt::is_doc_comment(self)
1511 }
1512
1513 #[inline]
1514 pub fn has_name(&self, name: Symbol) -> bool {
1515 AttributeExt::has_name(self, name)
1516 }
1517
1518 #[inline]
1519 pub fn has_any_name(&self, names: &[Symbol]) -> bool {
1520 AttributeExt::has_any_name(self, names)
1521 }
1522
1523 #[inline]
1524 pub fn span(&self) -> Span {
1525 AttributeExt::span(self)
1526 }
1527
1528 #[inline]
1529 pub fn is_word(&self) -> bool {
1530 AttributeExt::is_word(self)
1531 }
1532
1533 #[inline]
1534 pub fn path(&self) -> SmallVec<[Symbol; 1]> {
1535 AttributeExt::path(self)
1536 }
1537
1538 #[inline]
1539 pub fn doc_str(&self) -> Option<Symbol> {
1540 AttributeExt::doc_str(self)
1541 }
1542
1543 #[inline]
1544 pub fn is_proc_macro_attr(&self) -> bool {
1545 AttributeExt::is_proc_macro_attr(self)
1546 }
1547
1548 #[inline]
1549 pub fn doc_str_and_fragment_kind(&self) -> Option<(Symbol, DocFragmentKind)> {
1550 AttributeExt::doc_str_and_fragment_kind(self)
1551 }
1552}
1553
1554/// Attributes owned by a HIR owner.
1555#[derive(Debug)]
1556pub struct AttributeMap<'tcx> {
1557 pub map: SortedMap<ItemLocalId, &'tcx [Attribute]>,
1558 /// Preprocessed `#[define_opaque]` attribute.
1559 pub define_opaque: Option<&'tcx [(Span, LocalDefId)]>,
1560 // Only present when the crate hash is needed.
1561 pub opt_hash: Option<Fingerprint>,
1562}
1563
1564impl<'tcx> AttributeMap<'tcx> {
1565 pub const EMPTY: &'static AttributeMap<'static> = &AttributeMap {
1566 map: SortedMap::new(),
1567 opt_hash: Some(Fingerprint::ZERO),
1568 define_opaque: None,
1569 };
1570
1571 #[inline]
1572 pub fn get(&self, id: ItemLocalId) -> &'tcx [Attribute] {
1573 self.map.get(&id).copied().unwrap_or(&[])
1574 }
1575}
1576
1577/// Map of all HIR nodes inside the current owner.
1578/// These nodes are mapped by `ItemLocalId` alongside the index of their parent node.
1579/// The HIR tree, including bodies, is pre-hashed.
1580pub struct OwnerNodes<'tcx> {
1581 /// Pre-computed hash of the full HIR. Used in the crate hash. Only present
1582 /// when incr. comp. is enabled.
1583 pub opt_hash_including_bodies: Option<Fingerprint>,
1584 /// Full HIR for the current owner.
1585 // The zeroth node's parent should never be accessed: the owner's parent is computed by the
1586 // hir_owner_parent query. It is set to `ItemLocalId::INVALID` to force an ICE if accidentally
1587 // used.
1588 pub nodes: IndexVec<ItemLocalId, ParentedNode<'tcx>>,
1589 /// Content of local bodies.
1590 pub bodies: SortedMap<ItemLocalId, &'tcx Body<'tcx>>,
1591}
1592
1593impl<'tcx> OwnerNodes<'tcx> {
1594 pub fn node(&self) -> OwnerNode<'tcx> {
1595 // Indexing must ensure it is an OwnerNode.
1596 self.nodes[ItemLocalId::ZERO].node.as_owner().unwrap()
1597 }
1598
1599 /// Return an instance of `OwnerNodes` suitable for definitions that have no corresponding AST.
1600 pub fn synthetic() -> OwnerNodes<'tcx> {
1601 OwnerNodes {
1602 // There is no reason to bother computing a hash for a synthetic body.
1603 // Just use a constant value.
1604 opt_hash_including_bodies: Some(Fingerprint::ZERO),
1605 nodes: IndexVec::from_elem_n(
1606 ParentedNode { parent: ItemLocalId::INVALID, node: OwnerNode::Synthetic.into() },
1607 1,
1608 ),
1609 bodies: SortedMap::new(),
1610 }
1611 }
1612}
1613
1614impl fmt::Debug for OwnerNodes<'_> {
1615 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1616 f.debug_struct("OwnerNodes")
1617 // Do not print all the pointers to all the nodes, as it would be unreadable.
1618 .field("node", &self.nodes[ItemLocalId::ZERO])
1619 .field(
1620 "parents",
1621 &fmt::from_fn(|f| {
1622 f.debug_list()
1623 .entries(self.nodes.iter_enumerated().map(|(id, parented_node)| {
1624 fmt::from_fn(move |f| write!(f, "({id:?}, {:?})", parented_node.parent))
1625 }))
1626 .finish()
1627 }),
1628 )
1629 .field("bodies", &self.bodies)
1630 .field("opt_hash_including_bodies", &self.opt_hash_including_bodies)
1631 .finish()
1632 }
1633}
1634
1635/// Full information resulting from lowering an AST node.
1636#[derive(Debug, StableHash)]
1637pub struct OwnerInfo<'hir> {
1638 /// Contents of the HIR.
1639 pub nodes: OwnerNodes<'hir>,
1640 /// Map from each nested owner to its parent's local id.
1641 pub parenting: LocalDefIdMap<ItemLocalId>,
1642 /// Collected attributes of the HIR nodes.
1643 pub attrs: AttributeMap<'hir>,
1644 /// Map indicating what traits are in scope for places where this
1645 /// is relevant; generated by resolve.
1646 pub trait_map: ItemLocalMap<&'hir [TraitCandidate<'hir>]>,
1647
1648 /// Lints delayed during ast lowering to be emitted
1649 /// after hir has completely built
1650 ///
1651 /// WARNING: The delayed lints are not hashed as a part of the `OwnerInfo`, and therefore
1652 /// should only be accessed in `eval_always` queries.
1653 #[stable_hash(ignore)]
1654 pub delayed_lints: Steal<DelayedLints>,
1655}
1656
1657impl<'tcx> OwnerInfo<'tcx> {
1658 #[inline]
1659 pub fn node(&self) -> OwnerNode<'tcx> {
1660 self.nodes.node()
1661 }
1662}
1663
1664#[derive(Copy, Clone, Debug, StableHash)]
1665pub enum MaybeOwner<'tcx> {
1666 Owner(&'tcx OwnerInfo<'tcx>),
1667 NonOwner(HirId),
1668 /// Used as a placeholder for unused LocalDefId.
1669 Phantom,
1670}
1671
1672impl<'tcx> MaybeOwner<'tcx> {
1673 pub fn as_owner(self) -> Option<&'tcx OwnerInfo<'tcx>> {
1674 match self {
1675 MaybeOwner::Owner(i) => Some(i),
1676 MaybeOwner::NonOwner(_) | MaybeOwner::Phantom => None,
1677 }
1678 }
1679
1680 pub fn unwrap(self) -> &'tcx OwnerInfo<'tcx> {
1681 self.as_owner().unwrap_or_else(|| panic!("Not a HIR owner"))
1682 }
1683}
1684
1685#[derive(Debug, Clone, Copy, StableHash)]
1686pub struct Closure<'hir> {
1687 pub def_id: LocalDefId,
1688 pub binder: ClosureBinder,
1689 pub constness: Constness,
1690 pub capture_clause: CaptureBy,
1691 pub bound_generic_params: &'hir [GenericParam<'hir>],
1692 pub fn_decl: &'hir FnDecl<'hir>,
1693 pub body: BodyId,
1694 /// The span of the declaration block: 'move |...| -> ...'
1695 pub fn_decl_span: Span,
1696 /// The span of the argument block `|...|`
1697 pub fn_arg_span: Option<Span>,
1698 pub kind: ClosureKind,
1699 pub explicit_captures: &'hir [ExplicitCapture],
1700}
1701
1702/// A HIR local that must be captured by value even if ordinary closure capture
1703/// analysis would infer a weaker capture kind from its uses in the body.
1704#[derive(Debug, Clone, Copy, StableHash)]
1705pub struct ExplicitCapture {
1706 pub var_hir_id: HirId,
1707}
1708
1709#[derive(Clone, PartialEq, Eq, Debug, Copy, Hash, StableHash, Encodable, Decodable)]
1710pub enum ClosureKind {
1711 /// This is a plain closure expression.
1712 Closure,
1713 /// This is a coroutine expression -- i.e. a closure expression in which
1714 /// we've found a `yield`. These can arise either from "plain" coroutine
1715 /// usage (e.g. `let x = || { yield (); }`) or from a desugared expression
1716 /// (e.g. `async` and `gen` blocks).
1717 Coroutine(CoroutineKind),
1718 /// This is a coroutine-closure, which is a special sugared closure that
1719 /// returns one of the sugared coroutine (`async`/`gen`/`async gen`). It
1720 /// additionally allows capturing the coroutine's upvars by ref, and therefore
1721 /// needs to be specially treated during analysis and borrowck.
1722 CoroutineClosure(CoroutineDesugaring),
1723}
1724
1725/// A block of statements `{ .. }`, which may have a label (in this case the
1726/// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
1727/// the `rules` being anything but `DefaultBlock`.
1728#[derive(Debug, Clone, Copy, StableHash)]
1729pub struct Block<'hir> {
1730 /// Statements in a block.
1731 pub stmts: &'hir [Stmt<'hir>],
1732 /// An expression at the end of the block
1733 /// without a semicolon, if any.
1734 pub expr: Option<&'hir Expr<'hir>>,
1735 #[stable_hash(ignore)]
1736 pub hir_id: HirId,
1737 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
1738 pub rules: BlockCheckMode,
1739 /// The span includes the curly braces `{` and `}` around the block.
1740 pub span: Span,
1741 /// If true, then there may exist `break 'a` values that aim to
1742 /// break out of this block early.
1743 /// Used by `'label: {}` blocks and by `try {}` blocks.
1744 pub targeted_by_break: bool,
1745}
1746
1747impl<'hir> Block<'hir> {
1748 pub fn innermost_block(&self) -> &Block<'hir> {
1749 let mut block = self;
1750 while let Some(Expr { kind: ExprKind::Block(inner_block, _), .. }) = block.expr {
1751 block = inner_block;
1752 }
1753 block
1754 }
1755}
1756
1757#[derive(Debug, Clone, Copy, StableHash)]
1758pub struct TyFieldPath {
1759 pub variant: Option<Ident>,
1760 pub field: Ident,
1761}
1762
1763#[derive(Debug, Clone, Copy, StableHash)]
1764pub struct TyPat<'hir> {
1765 #[stable_hash(ignore)]
1766 pub hir_id: HirId,
1767 pub kind: TyPatKind<'hir>,
1768 pub span: Span,
1769}
1770
1771#[derive(Debug, Clone, Copy, StableHash)]
1772pub struct Pat<'hir> {
1773 #[stable_hash(ignore)]
1774 pub hir_id: HirId,
1775 pub kind: PatKind<'hir>,
1776 pub span: Span,
1777 /// Whether to use default binding modes.
1778 /// At present, this is false only for destructuring assignment.
1779 pub default_binding_modes: bool,
1780}
1781
1782impl<'hir> Pat<'hir> {
1783 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) -> bool {
1784 if !it(self) {
1785 return false;
1786 }
1787
1788 use PatKind::*;
1789 match self.kind {
1790 Missing => unreachable!(),
1791 Wild | Never | Expr(_) | Range(..) | Binding(.., None) | Err(_) => true,
1792 Box(s) | Deref(s) | Ref(s, _, _) | Binding(.., Some(s)) | Guard(s, _) => {
1793 s.walk_short_(it)
1794 }
1795 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
1796 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
1797 Slice(before, slice, after) => {
1798 before.iter().chain(slice).chain(after.iter()).all(|p| p.walk_short_(it))
1799 }
1800 }
1801 }
1802
1803 /// Walk the pattern in left-to-right order,
1804 /// short circuiting (with `.all(..)`) if `false` is returned.
1805 ///
1806 /// Note that when visiting e.g. `Tuple(ps)`,
1807 /// if visiting `ps[0]` returns `false`,
1808 /// then `ps[1]` will not be visited.
1809 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) -> bool {
1810 self.walk_short_(&mut it)
1811 }
1812
1813 fn walk_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) {
1814 if !it(self) {
1815 return;
1816 }
1817
1818 use PatKind::*;
1819 match self.kind {
1820 Missing | Wild | Never | Expr(_) | Range(..) | Binding(.., None) | Err(_) => {}
1821 Box(s) | Deref(s) | Ref(s, _, _) | Binding(.., Some(s)) | Guard(s, _) => s.walk_(it),
1822 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
1823 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
1824 Slice(before, slice, after) => {
1825 before.iter().chain(slice).chain(after.iter()).for_each(|p| p.walk_(it))
1826 }
1827 }
1828 }
1829
1830 /// Walk the pattern in left-to-right order.
1831 ///
1832 /// If `it(pat)` returns `false`, the children are not visited.
1833 pub fn walk(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) {
1834 self.walk_(&mut it)
1835 }
1836
1837 /// Walk the pattern in left-to-right order.
1838 ///
1839 /// If you always want to recurse, prefer this method over `walk`.
1840 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
1841 self.walk(|p| {
1842 it(p);
1843 true
1844 })
1845 }
1846
1847 /// Whether this a never pattern.
1848 pub fn is_never_pattern(&self) -> bool {
1849 let mut is_never_pattern = false;
1850 self.walk(|pat| match &pat.kind {
1851 PatKind::Never => {
1852 is_never_pattern = true;
1853 false
1854 }
1855 PatKind::Or(s) => {
1856 is_never_pattern = s.iter().all(|p| p.is_never_pattern());
1857 false
1858 }
1859 _ => true,
1860 });
1861 is_never_pattern
1862 }
1863
1864 /// Whether this pattern constitutes a read of value of the scrutinee that
1865 /// it is matching against. This is used to determine whether we should
1866 /// perform `NeverToAny` coercions.
1867 ///
1868 /// See [`expr_guaranteed_to_constitute_read_for_never`][m] for the nuances of
1869 /// what happens when this returns true.
1870 ///
1871 /// [m]: ../../rustc_middle/ty/struct.TyCtxt.html#method.expr_guaranteed_to_constitute_read_for_never
1872 pub fn is_guaranteed_to_constitute_read_for_never(&self) -> bool {
1873 match self.kind {
1874 // Does not constitute a read.
1875 PatKind::Wild => false,
1876
1877 // The guard cannot affect if we make a read or not (it runs after the inner pattern
1878 // has matched), therefore it's irrelevant.
1879 PatKind::Guard(pat, _) => pat.is_guaranteed_to_constitute_read_for_never(),
1880
1881 // This is unnecessarily restrictive when the pattern that doesn't
1882 // constitute a read is unreachable.
1883 //
1884 // For example `match *never_ptr { value => {}, _ => {} }` or
1885 // `match *never_ptr { _ if false => {}, value => {} }`.
1886 //
1887 // It is however fine to be restrictive here; only returning `true`
1888 // can lead to unsoundness.
1889 PatKind::Or(subpats) => {
1890 subpats.iter().all(|pat| pat.is_guaranteed_to_constitute_read_for_never())
1891 }
1892
1893 // Does constitute a read, since it is equivalent to a discriminant read.
1894 PatKind::Never => true,
1895
1896 // All of these constitute a read, or match on something that isn't `!`,
1897 // which would require a `NeverToAny` coercion.
1898 PatKind::Missing
1899 | PatKind::Binding(_, _, _, _)
1900 | PatKind::Struct(_, _, _)
1901 | PatKind::TupleStruct(_, _, _)
1902 | PatKind::Tuple(_, _)
1903 | PatKind::Box(_)
1904 | PatKind::Ref(_, _, _)
1905 | PatKind::Deref(_)
1906 | PatKind::Expr(_)
1907 | PatKind::Range(_, _, _)
1908 | PatKind::Slice(_, _, _)
1909 | PatKind::Err(_) => true,
1910 }
1911 }
1912}
1913
1914/// A single field in a struct pattern.
1915///
1916/// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
1917/// are treated the same as` x: x, y: ref y, z: ref mut z`,
1918/// except `is_shorthand` is true.
1919#[derive(Debug, Clone, Copy, StableHash)]
1920pub struct PatField<'hir> {
1921 #[stable_hash(ignore)]
1922 pub hir_id: HirId,
1923 /// The identifier for the field.
1924 pub ident: Ident,
1925 /// The pattern the field is destructured to.
1926 pub pat: &'hir Pat<'hir>,
1927 pub is_shorthand: bool,
1928 pub span: Span,
1929}
1930
1931#[derive(Copy, Clone, PartialEq, Debug, StableHash, Hash, Eq, Encodable, Decodable)]
1932pub enum RangeEnd {
1933 Included,
1934 Excluded,
1935}
1936
1937impl fmt::Display for RangeEnd {
1938 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1939 f.write_str(match self {
1940 RangeEnd::Included => "..=",
1941 RangeEnd::Excluded => "..",
1942 })
1943 }
1944}
1945
1946// Equivalent to `Option<usize>`. That type takes up 16 bytes on 64-bit, but
1947// this type only takes up 4 bytes, at the cost of being restricted to a
1948// maximum value of `u32::MAX - 1`. In practice, this is more than enough.
1949#[derive(Clone, Copy, PartialEq, Eq, Hash, StableHash)]
1950pub struct DotDotPos(u32);
1951
1952impl DotDotPos {
1953 /// Panics if n >= u32::MAX.
1954 pub fn new(n: Option<usize>) -> Self {
1955 match n {
1956 Some(n) => {
1957 assert!(n < u32::MAX as usize);
1958 Self(n as u32)
1959 }
1960 None => Self(u32::MAX),
1961 }
1962 }
1963
1964 pub fn as_opt_usize(&self) -> Option<usize> {
1965 if self.0 == u32::MAX { None } else { Some(self.0 as usize) }
1966 }
1967}
1968
1969impl fmt::Debug for DotDotPos {
1970 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1971 self.as_opt_usize().fmt(f)
1972 }
1973}
1974
1975#[derive(Debug, Clone, Copy, StableHash)]
1976pub struct PatExpr<'hir> {
1977 #[stable_hash(ignore)]
1978 pub hir_id: HirId,
1979 pub span: Span,
1980 pub kind: PatExprKind<'hir>,
1981}
1982
1983#[derive(Debug, Clone, Copy, StableHash)]
1984pub enum PatExprKind<'hir> {
1985 Lit {
1986 lit: Lit,
1987 negated: bool,
1988 },
1989 /// A path pattern for a unit struct/variant or a (maybe-associated) constant.
1990 Path(QPath<'hir>),
1991}
1992
1993#[derive(Debug, Clone, Copy, StableHash)]
1994pub enum TyPatKind<'hir> {
1995 /// A range pattern (e.g., `1..=2` or `1..2`).
1996 Range(&'hir ConstArg<'hir>, &'hir ConstArg<'hir>),
1997
1998 /// A pattern that excludes null pointers
1999 NotNull,
2000
2001 /// A list of patterns where only one needs to be satisfied
2002 Or(&'hir [TyPat<'hir>]),
2003
2004 /// A placeholder for a pattern that wasn't well formed in some way.
2005 Err(ErrorGuaranteed),
2006}
2007
2008#[derive(Debug, Clone, Copy, StableHash)]
2009pub enum PatKind<'hir> {
2010 /// A missing pattern, e.g. for an anonymous param in a bare fn like `fn f(u32)`.
2011 Missing,
2012
2013 /// Represents a wildcard pattern (i.e., `_`).
2014 Wild,
2015
2016 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
2017 /// The `HirId` is the canonical ID for the variable being bound,
2018 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
2019 /// which is the pattern ID of the first `x`.
2020 ///
2021 /// The `BindingMode` is what's provided by the user, before match
2022 /// ergonomics are applied. For the binding mode actually in use,
2023 /// see [`TypeckResults::extract_binding_mode`].
2024 ///
2025 /// [`TypeckResults::extract_binding_mode`]: ../../rustc_middle/ty/struct.TypeckResults.html#method.extract_binding_mode
2026 Binding(BindingMode, HirId, Ident, Option<&'hir Pat<'hir>>),
2027
2028 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
2029 /// The `Option` contains the span of a possible `..`.
2030 Struct(QPath<'hir>, &'hir [PatField<'hir>], Option<Span>),
2031
2032 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
2033 /// If the `..` pattern fragment is present, then `DotDotPos` denotes its position.
2034 /// `0 <= position <= subpats.len()`
2035 TupleStruct(QPath<'hir>, &'hir [Pat<'hir>], DotDotPos),
2036
2037 /// An or-pattern `A | B | C`.
2038 /// Invariant: `pats.len() >= 2`.
2039 Or(&'hir [Pat<'hir>]),
2040
2041 /// A never pattern `!`.
2042 Never,
2043
2044 /// A tuple pattern (e.g., `(a, b)`).
2045 /// If the `..` pattern fragment is present, then `DotDotPos` denotes its position.
2046 /// `0 <= position <= subpats.len()`
2047 Tuple(&'hir [Pat<'hir>], DotDotPos),
2048
2049 /// A `box` pattern.
2050 Box(&'hir Pat<'hir>),
2051
2052 /// A `deref` pattern (currently `deref!()` macro-based syntax).
2053 Deref(&'hir Pat<'hir>),
2054
2055 /// A reference pattern (e.g., `&mut (a, b)`).
2056 Ref(&'hir Pat<'hir>, Pinnedness, Mutability),
2057
2058 /// A literal, const block or path.
2059 Expr(&'hir PatExpr<'hir>),
2060
2061 /// A guard pattern (e.g., `x if guard(x)`).
2062 Guard(&'hir Pat<'hir>, &'hir Expr<'hir>),
2063
2064 /// A range pattern (e.g., `1..=2` or `1..2`).
2065 Range(Option<&'hir PatExpr<'hir>>, Option<&'hir PatExpr<'hir>>, RangeEnd),
2066
2067 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
2068 ///
2069 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
2070 /// If `slice` exists, then `after` can be non-empty.
2071 ///
2072 /// The representation for e.g., `[a, b, .., c, d]` is:
2073 /// ```ignore (illustrative)
2074 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
2075 /// ```
2076 Slice(&'hir [Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [Pat<'hir>]),
2077
2078 /// A placeholder for a pattern that wasn't well formed in some way.
2079 Err(ErrorGuaranteed),
2080}
2081
2082/// A statement.
2083#[derive(Debug, Clone, Copy, StableHash)]
2084pub struct Stmt<'hir> {
2085 #[stable_hash(ignore)]
2086 pub hir_id: HirId,
2087 pub kind: StmtKind<'hir>,
2088 pub span: Span,
2089}
2090
2091/// The contents of a statement.
2092#[derive(Debug, Clone, Copy, StableHash)]
2093pub enum StmtKind<'hir> {
2094 /// A local (`let`) binding.
2095 Let(&'hir LetStmt<'hir>),
2096
2097 /// An item binding.
2098 Item(ItemId),
2099
2100 /// An expression without a trailing semi-colon (must have unit type).
2101 Expr(&'hir Expr<'hir>),
2102
2103 /// An expression with a trailing semi-colon (may have any type).
2104 Semi(&'hir Expr<'hir>),
2105}
2106
2107/// Represents a `let` statement (i.e., `let <pat>:<ty> = <init>;`).
2108#[derive(Debug, Clone, Copy, StableHash)]
2109pub struct LetStmt<'hir> {
2110 /// Span of `super` in `super let`.
2111 pub super_: Option<Span>,
2112 pub pat: &'hir Pat<'hir>,
2113 /// Type annotation, if any (otherwise the type will be inferred).
2114 pub ty: Option<&'hir Ty<'hir>>,
2115 /// Initializer expression to set the value, if any.
2116 pub init: Option<&'hir Expr<'hir>>,
2117 /// Else block for a `let...else` binding.
2118 pub els: Option<&'hir Block<'hir>>,
2119 #[stable_hash(ignore)]
2120 pub hir_id: HirId,
2121 pub span: Span,
2122 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
2123 /// desugaring, or `AssignDesugar` if it is the result of a complex
2124 /// assignment desugaring. Otherwise will be `Normal`.
2125 pub source: LocalSource,
2126}
2127
2128/// Represents a single arm of a `match` expression, e.g.
2129/// `<pat> (if <guard>) => <body>`.
2130#[derive(Debug, Clone, Copy, StableHash)]
2131pub struct Arm<'hir> {
2132 #[stable_hash(ignore)]
2133 pub hir_id: HirId,
2134 pub span: Span,
2135 /// If this pattern and the optional guard matches, then `body` is evaluated.
2136 pub pat: &'hir Pat<'hir>,
2137 /// Optional guard clause.
2138 pub guard: Option<&'hir Expr<'hir>>,
2139 /// The expression the arm evaluates to if this arm matches.
2140 pub body: &'hir Expr<'hir>,
2141}
2142
2143/// Represents a `let <pat>[: <ty>] = <expr>` expression (not a [`LetStmt`]), occurring in an `if-let`
2144/// or `let-else`, evaluating to a boolean. Typically the pattern is refutable.
2145///
2146/// In an `if let`, imagine it as `if (let <pat> = <expr>) { ... }`; in a let-else, it is part of
2147/// the desugaring to if-let. Only let-else supports the type annotation at present.
2148#[derive(Debug, Clone, Copy, StableHash)]
2149pub struct LetExpr<'hir> {
2150 pub span: Span,
2151 pub pat: &'hir Pat<'hir>,
2152 pub ty: Option<&'hir Ty<'hir>>,
2153 pub init: &'hir Expr<'hir>,
2154 /// `Recovered::Yes` when this let expressions is not in a syntactically valid location.
2155 /// Used to prevent building MIR in such situations.
2156 pub recovered: ast::Recovered,
2157}
2158
2159#[derive(Debug, Clone, Copy, StableHash)]
2160pub struct ExprField<'hir> {
2161 #[stable_hash(ignore)]
2162 pub hir_id: HirId,
2163 pub ident: Ident,
2164 pub expr: &'hir Expr<'hir>,
2165 pub span: Span,
2166 pub is_shorthand: bool,
2167}
2168
2169#[derive(Copy, Clone, PartialEq, Debug, StableHash)]
2170pub enum BlockCheckMode {
2171 DefaultBlock,
2172 UnsafeBlock(UnsafeSource),
2173}
2174
2175#[derive(Copy, Clone, PartialEq, Debug, StableHash)]
2176pub enum UnsafeSource {
2177 CompilerGenerated,
2178 UserProvided,
2179}
2180
2181#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, StableHash)]
2182pub struct BodyId {
2183 pub hir_id: HirId,
2184}
2185
2186/// The body of a function, closure, or constant value. In the case of
2187/// a function, the body contains not only the function body itself
2188/// (which is an expression), but also the argument patterns, since
2189/// those are something that the caller doesn't really care about.
2190///
2191/// # Examples
2192///
2193/// ```
2194/// fn foo((x, y): (u32, u32)) -> u32 {
2195/// x + y
2196/// }
2197/// ```
2198///
2199/// Here, the `Body` associated with `foo()` would contain:
2200///
2201/// - an `params` array containing the `(x, y)` pattern
2202/// - a `value` containing the `x + y` expression (maybe wrapped in a block)
2203/// - `coroutine_kind` would be `None`
2204///
2205/// All bodies have an **owner**, which can be accessed via the HIR
2206/// map using `body_owner_def_id()`.
2207#[derive(Debug, Clone, Copy, StableHash)]
2208pub struct Body<'hir> {
2209 pub params: &'hir [Param<'hir>],
2210 pub value: &'hir Expr<'hir>,
2211}
2212
2213impl<'hir> Body<'hir> {
2214 pub fn id(&self) -> BodyId {
2215 BodyId { hir_id: self.value.hir_id }
2216 }
2217}
2218
2219/// The type of source expression that caused this coroutine to be created.
2220#[derive(Clone, PartialEq, Eq, Debug, Copy, Hash, StableHash, Encodable, Decodable)]
2221pub enum CoroutineKind {
2222 /// A coroutine that comes from a desugaring.
2223 Desugared(CoroutineDesugaring, CoroutineSource),
2224
2225 /// A coroutine literal created via a `yield` inside a closure.
2226 Coroutine(Movability),
2227}
2228
2229impl CoroutineKind {
2230 pub fn movability(self) -> Movability {
2231 match self {
2232 CoroutineKind::Desugared(CoroutineDesugaring::Async, _)
2233 | CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => Movability::Static,
2234 CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => Movability::Movable,
2235 CoroutineKind::Coroutine(mov) => mov,
2236 }
2237 }
2238
2239 pub fn is_fn_like(self) -> bool {
2240 matches!(self, CoroutineKind::Desugared(_, CoroutineSource::Fn))
2241 }
2242
2243 pub fn to_plural_string(&self) -> String {
2244 match self {
2245 CoroutineKind::Desugared(d, CoroutineSource::Fn) => format!("{d:#}fn bodies"),
2246 CoroutineKind::Desugared(d, CoroutineSource::Block) => format!("{d:#}blocks"),
2247 CoroutineKind::Desugared(d, CoroutineSource::Closure) => format!("{d:#}closure bodies"),
2248 CoroutineKind::Coroutine(_) => "coroutines".to_string(),
2249 }
2250 }
2251}
2252
2253impl fmt::Display for CoroutineKind {
2254 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2255 match self {
2256 CoroutineKind::Desugared(d, k) => {
2257 d.fmt(f)?;
2258 k.fmt(f)
2259 }
2260 CoroutineKind::Coroutine(_) => f.write_str("coroutine"),
2261 }
2262 }
2263}
2264
2265/// In the case of a coroutine created as part of an async/gen construct,
2266/// which kind of async/gen construct caused it to be created?
2267///
2268/// This helps error messages but is also used to drive coercions in
2269/// type-checking (see #60424).
2270#[derive(Clone, PartialEq, Eq, Hash, Debug, Copy, StableHash, Encodable, Decodable)]
2271pub enum CoroutineSource {
2272 /// An explicit `async`/`gen` block written by the user.
2273 Block,
2274
2275 /// An explicit `async`/`gen` closure written by the user.
2276 Closure,
2277
2278 /// The `async`/`gen` block generated as the body of an async/gen function.
2279 Fn,
2280}
2281
2282impl fmt::Display for CoroutineSource {
2283 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2284 match self {
2285 CoroutineSource::Block => "block",
2286 CoroutineSource::Closure => "closure body",
2287 CoroutineSource::Fn => "fn body",
2288 }
2289 .fmt(f)
2290 }
2291}
2292
2293#[derive(Clone, PartialEq, Eq, Debug, Copy, Hash, StableHash, Encodable, Decodable)]
2294pub enum CoroutineDesugaring {
2295 /// An explicit `async` block or the body of an `async` function.
2296 Async,
2297
2298 /// An explicit `gen` block or the body of a `gen` function.
2299 Gen,
2300
2301 /// An explicit `async gen` block or the body of an `async gen` function,
2302 /// which is able to both `yield` and `.await`.
2303 AsyncGen,
2304}
2305
2306impl fmt::Display for CoroutineDesugaring {
2307 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2308 match self {
2309 CoroutineDesugaring::Async => {
2310 if f.alternate() {
2311 f.write_str("`async` ")?;
2312 } else {
2313 f.write_str("async ")?
2314 }
2315 }
2316 CoroutineDesugaring::Gen => {
2317 if f.alternate() {
2318 f.write_str("`gen` ")?;
2319 } else {
2320 f.write_str("gen ")?
2321 }
2322 }
2323 CoroutineDesugaring::AsyncGen => {
2324 if f.alternate() {
2325 f.write_str("`async gen` ")?;
2326 } else {
2327 f.write_str("async gen ")?
2328 }
2329 }
2330 }
2331
2332 Ok(())
2333 }
2334}
2335
2336#[derive(Copy, Clone, Debug)]
2337pub enum BodyOwnerKind {
2338 /// Functions and methods.
2339 Fn,
2340
2341 /// Closures
2342 Closure,
2343
2344 /// Constants and associated constants, also including inline constants.
2345 Const { inline: bool },
2346
2347 /// Initializer of a `static` item.
2348 Static(Mutability),
2349
2350 /// Fake body for a global asm to store its const-like value types.
2351 GlobalAsm,
2352}
2353
2354impl BodyOwnerKind {
2355 pub fn is_fn_or_closure(self) -> bool {
2356 match self {
2357 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
2358 BodyOwnerKind::Const { .. } | BodyOwnerKind::Static(_) | BodyOwnerKind::GlobalAsm => {
2359 false
2360 }
2361 }
2362 }
2363}
2364
2365/// The kind of an item that requires const-checking.
2366#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2367pub enum ConstContext {
2368 /// A `const fn`.
2369 ConstFn,
2370
2371 /// A `static` or `static mut`.
2372 Static(Mutability),
2373
2374 /// A `const`, associated `const`, or other const context.
2375 ///
2376 /// Other contexts include:
2377 /// - Array length expressions
2378 /// - Enum discriminants
2379 /// - Const generics
2380 ///
2381 /// For the most part, other contexts are treated just like a regular `const`, so they are
2382 /// lumped into the same category.
2383 Const { inline: bool },
2384}
2385
2386impl ConstContext {
2387 /// A description of this const context that can appear between backticks in an error message.
2388 ///
2389 /// E.g. `const` or `static mut`.
2390 pub fn keyword_name(self) -> &'static str {
2391 match self {
2392 Self::Const { .. } => "const",
2393 Self::Static(Mutability::Not) => "static",
2394 Self::Static(Mutability::Mut) => "static mut",
2395 Self::ConstFn => "const fn",
2396 }
2397 }
2398}
2399
2400/// A colloquial, trivially pluralizable description of this const context for use in error
2401/// messages.
2402impl fmt::Display for ConstContext {
2403 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2404 match *self {
2405 Self::Const { .. } => write!(f, "constant"),
2406 Self::Static(_) => write!(f, "static"),
2407 Self::ConstFn => write!(f, "constant function"),
2408 }
2409 }
2410}
2411
2412impl IntoDiagArg for ConstContext {
2413 fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
2414 DiagArgValue::Str(Cow::Borrowed(match self {
2415 ConstContext::ConstFn => "constant function",
2416 ConstContext::Static(_) => "static",
2417 ConstContext::Const { .. } => "constant",
2418 }))
2419 }
2420}
2421
2422/// A literal.
2423pub type Lit = Spanned<LitKind>;
2424
2425/// A constant (expression) that's not an item or associated item,
2426/// but needs its own `DefId` for type-checking, const-eval, etc.
2427/// These are usually found nested inside types (e.g., array lengths)
2428/// or expressions (e.g., repeat counts), and also used to define
2429/// explicit discriminant values for enum variants.
2430///
2431/// You can check if this anon const is a default in a const param
2432/// `const N: usize = { ... }` with `tcx.hir_opt_const_param_default_param_def_id(..)`
2433#[derive(Copy, Clone, Debug, StableHash)]
2434pub struct AnonConst {
2435 #[stable_hash(ignore)]
2436 pub hir_id: HirId,
2437 pub def_id: LocalDefId,
2438 pub body: BodyId,
2439 pub span: Span,
2440}
2441
2442/// An inline constant expression `const { something }`.
2443#[derive(Copy, Clone, Debug, StableHash)]
2444pub struct ConstBlock {
2445 #[stable_hash(ignore)]
2446 pub hir_id: HirId,
2447 pub def_id: LocalDefId,
2448 pub body: BodyId,
2449}
2450
2451/// An expression.
2452///
2453/// For more details, see the [rust lang reference].
2454/// Note that the reference does not document nightly-only features.
2455/// There may be also slight differences in the names and representation of AST nodes between
2456/// the compiler and the reference.
2457///
2458/// [rust lang reference]: https://doc.rust-lang.org/reference/expressions.html
2459#[derive(Debug, Clone, Copy, StableHash)]
2460pub struct Expr<'hir> {
2461 #[stable_hash(ignore)]
2462 pub hir_id: HirId,
2463 pub kind: ExprKind<'hir>,
2464 pub span: Span,
2465}
2466
2467impl Expr<'_> {
2468 pub fn precedence(&self, has_attr: &dyn Fn(HirId) -> bool) -> ExprPrecedence {
2469 let prefix_attrs_precedence = || -> ExprPrecedence {
2470 if has_attr(self.hir_id) { ExprPrecedence::Prefix } else { ExprPrecedence::Unambiguous }
2471 };
2472
2473 match &self.kind {
2474 ExprKind::Closure(closure) => {
2475 match closure.fn_decl.output {
2476 FnRetTy::DefaultReturn(_) => ExprPrecedence::Jump,
2477 FnRetTy::Return(_) => prefix_attrs_precedence(),
2478 }
2479 }
2480
2481 ExprKind::Break(..)
2482 | ExprKind::Ret(..)
2483 | ExprKind::Yield(..)
2484 | ExprKind::Become(..) => ExprPrecedence::Jump,
2485
2486 // Binop-like expr kinds, handled by `AssocOp`.
2487 ExprKind::Binary(op, ..) => op.node.precedence(),
2488 ExprKind::Cast(..) => ExprPrecedence::Cast,
2489
2490 ExprKind::Assign(..) |
2491 ExprKind::AssignOp(..) => ExprPrecedence::Assign,
2492
2493 // Unary, prefix
2494 ExprKind::AddrOf(..)
2495 // Here `let pats = expr` has `let pats =` as a "unary" prefix of `expr`.
2496 // However, this is not exactly right. When `let _ = a` is the LHS of a binop we
2497 // need parens sometimes. E.g. we can print `(let _ = a) && b` as `let _ = a && b`
2498 // but we need to print `(let _ = a) < b` as-is with parens.
2499 | ExprKind::Let(..)
2500 | ExprKind::Unary(..) => ExprPrecedence::Prefix,
2501
2502 // Need parens if and only if there are prefix attributes.
2503 ExprKind::Array(_)
2504 | ExprKind::Block(..)
2505 | ExprKind::Call(..)
2506 | ExprKind::ConstBlock(_)
2507 | ExprKind::Continue(..)
2508 | ExprKind::Field(..)
2509 | ExprKind::If(..)
2510 | ExprKind::Index(..)
2511 | ExprKind::InlineAsm(..)
2512 | ExprKind::Lit(_)
2513 | ExprKind::Loop(..)
2514 | ExprKind::Match(..)
2515 | ExprKind::MethodCall(..)
2516 | ExprKind::OffsetOf(..)
2517 | ExprKind::Path(..)
2518 | ExprKind::Repeat(..)
2519 | ExprKind::Struct(..)
2520 | ExprKind::Tup(_)
2521 | ExprKind::Type(..)
2522 | ExprKind::UnsafeBinderCast(..)
2523 | ExprKind::Use(..)
2524 | ExprKind::Err(_) => prefix_attrs_precedence(),
2525
2526 ExprKind::DropTemps(expr, ..) => expr.precedence(has_attr),
2527 }
2528 }
2529
2530 /// Whether this looks like a place expr, without checking for deref
2531 /// adjustments.
2532 /// This will return `true` in some potentially surprising cases such as
2533 /// `CONSTANT.field`.
2534 pub fn is_syntactic_place_expr(&self) -> bool {
2535 self.is_place_expr(|_| true)
2536 }
2537
2538 /// Whether this is a place expression.
2539 ///
2540 /// `allow_projections_from` should return `true` if indexing a field or index expression based
2541 /// on the given expression should be considered a place expression.
2542 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
2543 match self.kind {
2544 ExprKind::Path(QPath::Resolved(_, ref path)) => {
2545 matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static { .. }, _) | Res::Err)
2546 }
2547
2548 // Type ascription inherits its place expression kind from its
2549 // operand. See:
2550 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
2551 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
2552
2553 // Unsafe binder cast preserves place-ness of the sub-expression.
2554 ExprKind::UnsafeBinderCast(_, e, _) => e.is_place_expr(allow_projections_from),
2555
2556 ExprKind::Unary(UnOp::Deref, _) => true,
2557
2558 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _, _) => {
2559 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
2560 }
2561
2562 // Suppress errors for bad expressions.
2563 ExprKind::Err(_guar)
2564 | ExprKind::Let(&LetExpr { recovered: ast::Recovered::Yes(_guar), .. }) => true,
2565
2566 // Partially qualified paths in expressions can only legally
2567 // refer to associated items which are always rvalues.
2568 ExprKind::Path(QPath::TypeRelative(..))
2569 | ExprKind::Call(..)
2570 | ExprKind::MethodCall(..)
2571 | ExprKind::Use(..)
2572 | ExprKind::Struct(..)
2573 | ExprKind::Tup(..)
2574 | ExprKind::If(..)
2575 | ExprKind::Match(..)
2576 | ExprKind::Closure { .. }
2577 | ExprKind::Block(..)
2578 | ExprKind::Repeat(..)
2579 | ExprKind::Array(..)
2580 | ExprKind::Break(..)
2581 | ExprKind::Continue(..)
2582 | ExprKind::Ret(..)
2583 | ExprKind::Become(..)
2584 | ExprKind::Let(..)
2585 | ExprKind::Loop(..)
2586 | ExprKind::Assign(..)
2587 | ExprKind::InlineAsm(..)
2588 | ExprKind::OffsetOf(..)
2589 | ExprKind::AssignOp(..)
2590 | ExprKind::Lit(_)
2591 | ExprKind::ConstBlock(..)
2592 | ExprKind::Unary(..)
2593 | ExprKind::AddrOf(..)
2594 | ExprKind::Binary(..)
2595 | ExprKind::Yield(..)
2596 | ExprKind::Cast(..)
2597 | ExprKind::DropTemps(..) => false,
2598 }
2599 }
2600
2601 /// If this is a desugared range expression,
2602 /// returns the span of the range without desugaring context.
2603 pub fn range_span(&self) -> Option<Span> {
2604 is_range_literal(self).then(|| self.span.parent_callsite().unwrap())
2605 }
2606
2607 /// Check if expression is an integer literal that can be used
2608 /// where `usize` is expected.
2609 pub fn is_size_lit(&self) -> bool {
2610 matches!(
2611 self.kind,
2612 ExprKind::Lit(Lit {
2613 node: LitKind::Int(_, LitIntType::Unsuffixed | LitIntType::Unsigned(UintTy::Usize)),
2614 ..
2615 })
2616 )
2617 }
2618
2619 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
2620 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
2621 /// silent, only signaling the ownership system. By doing this, suggestions that check the
2622 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
2623 /// beyond remembering to call this function before doing analysis on it.
2624 pub fn peel_drop_temps(&self) -> &Self {
2625 let mut expr = self;
2626 while let ExprKind::DropTemps(inner) = &expr.kind {
2627 expr = inner;
2628 }
2629 expr
2630 }
2631
2632 pub fn peel_blocks(&self) -> &Self {
2633 let mut expr = self;
2634 while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind {
2635 expr = inner;
2636 }
2637 expr
2638 }
2639
2640 pub fn peel_borrows(&self) -> &Self {
2641 let mut expr = self;
2642 while let ExprKind::AddrOf(.., inner) = &expr.kind {
2643 expr = inner;
2644 }
2645 expr
2646 }
2647
2648 pub fn can_have_side_effects(&self) -> bool {
2649 match self.peel_drop_temps().kind {
2650 ExprKind::Path(_) | ExprKind::Lit(_) | ExprKind::OffsetOf(..) | ExprKind::Use(..) => {
2651 false
2652 }
2653 ExprKind::Type(base, _)
2654 | ExprKind::Unary(_, base)
2655 | ExprKind::Field(base, _)
2656 | ExprKind::Index(base, _, _)
2657 | ExprKind::AddrOf(.., base)
2658 | ExprKind::Cast(base, _)
2659 | ExprKind::UnsafeBinderCast(_, base, _) => {
2660 // This isn't exactly true for `Index` and all `Unary`, but we are using this
2661 // method exclusively for diagnostics and there's a *cultural* pressure against
2662 // them being used only for its side-effects.
2663 base.can_have_side_effects()
2664 }
2665 ExprKind::Binary(_, lhs, rhs) => {
2666 // This isn't exactly true for all `Binary`, but we are using this
2667 // method exclusively for diagnostics and there's a *cultural* pressure against
2668 // them being used only for its side-effects.
2669 lhs.can_have_side_effects() || rhs.can_have_side_effects()
2670 }
2671 ExprKind::Struct(_, fields, init) => {
2672 let init_side_effects = match init {
2673 StructTailExpr::Base(init) => init.can_have_side_effects(),
2674 StructTailExpr::DefaultFields(_)
2675 | StructTailExpr::None
2676 | StructTailExpr::NoneWithError(_) => false,
2677 };
2678 fields.iter().map(|field| field.expr).any(|e| e.can_have_side_effects())
2679 || init_side_effects
2680 }
2681
2682 ExprKind::Array(args)
2683 | ExprKind::Tup(args)
2684 | ExprKind::Call(
2685 Expr {
2686 kind:
2687 ExprKind::Path(QPath::Resolved(
2688 None,
2689 Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. },
2690 )),
2691 ..
2692 },
2693 args,
2694 ) => args.iter().any(|arg| arg.can_have_side_effects()),
2695 ExprKind::Repeat(arg, _) => arg.can_have_side_effects(),
2696 ExprKind::If(..)
2697 | ExprKind::Match(..)
2698 | ExprKind::MethodCall(..)
2699 | ExprKind::Call(..)
2700 | ExprKind::Closure { .. }
2701 | ExprKind::Block(..)
2702 | ExprKind::Break(..)
2703 | ExprKind::Continue(..)
2704 | ExprKind::Ret(..)
2705 | ExprKind::Become(..)
2706 | ExprKind::Let(..)
2707 | ExprKind::Loop(..)
2708 | ExprKind::Assign(..)
2709 | ExprKind::InlineAsm(..)
2710 | ExprKind::AssignOp(..)
2711 | ExprKind::ConstBlock(..)
2712 | ExprKind::Yield(..)
2713 | ExprKind::DropTemps(..)
2714 | ExprKind::Err(_) => true,
2715 }
2716 }
2717
2718 /// To a first-order approximation, is this a pattern?
2719 pub fn is_approximately_pattern(&self) -> bool {
2720 match &self.kind {
2721 ExprKind::Array(_)
2722 | ExprKind::Call(..)
2723 | ExprKind::Tup(_)
2724 | ExprKind::Lit(_)
2725 | ExprKind::Path(_)
2726 | ExprKind::Struct(..) => true,
2727 _ => false,
2728 }
2729 }
2730
2731 /// Whether this and the `other` expression are the same for purposes of an indexing operation.
2732 ///
2733 /// This is only used for diagnostics to see if we have things like `foo[i]` where `foo` is
2734 /// borrowed multiple times with `i`.
2735 pub fn equivalent_for_indexing(&self, other: &Expr<'_>) -> bool {
2736 match (self.kind, other.kind) {
2737 (ExprKind::Lit(lit1), ExprKind::Lit(lit2)) => lit1.node == lit2.node,
2738 (
2739 ExprKind::Path(QPath::Resolved(None, path1)),
2740 ExprKind::Path(QPath::Resolved(None, path2)),
2741 ) => path1.res == path2.res,
2742 (
2743 ExprKind::Struct(
2744 &QPath::Resolved(None, &Path { res: Res::Def(_, path1_def_id), .. }),
2745 args1,
2746 StructTailExpr::None,
2747 ),
2748 ExprKind::Struct(
2749 &QPath::Resolved(None, &Path { res: Res::Def(_, path2_def_id), .. }),
2750 args2,
2751 StructTailExpr::None,
2752 ),
2753 ) => {
2754 path2_def_id == path1_def_id
2755 && is_range_literal(self)
2756 && is_range_literal(other)
2757 && std::iter::zip(args1, args2)
2758 .all(|(a, b)| a.expr.equivalent_for_indexing(b.expr))
2759 }
2760 _ => false,
2761 }
2762 }
2763
2764 pub fn method_ident(&self) -> Option<Ident> {
2765 match self.kind {
2766 ExprKind::MethodCall(receiver_method, ..) => Some(receiver_method.ident),
2767 ExprKind::Unary(_, expr) | ExprKind::AddrOf(.., expr) => expr.method_ident(),
2768 _ => None,
2769 }
2770 }
2771}
2772
2773/// Checks if the specified expression is a built-in range literal.
2774/// (See: `LoweringContext::lower_expr()`).
2775pub fn is_range_literal(expr: &Expr<'_>) -> bool {
2776 if let ExprKind::Struct(QPath::Resolved(None, path), _, StructTailExpr::None) = expr.kind
2777 && let [.., segment] = path.segments
2778 && let sym::RangeFrom
2779 | sym::RangeFull
2780 | sym::Range
2781 | sym::RangeToInclusive
2782 | sym::RangeTo
2783 | sym::RangeFromCopy
2784 | sym::RangeCopy
2785 | sym::RangeInclusiveCopy
2786 | sym::RangeToInclusiveCopy = segment.ident.name
2787 && expr.span.is_desugaring(DesugaringKind::RangeExpr)
2788 {
2789 true
2790 } else if let ExprKind::Call(func, _) = &expr.kind
2791 && let ExprKind::Path(QPath::Resolved(None, path)) = func.kind
2792 && let [.., segment] = path.segments
2793 && let sym::range_inclusive_new = segment.ident.name
2794 && expr.span.is_desugaring(DesugaringKind::RangeExpr)
2795 {
2796 true
2797 } else {
2798 false
2799 }
2800}
2801
2802/// Checks if the specified expression needs parentheses for prefix
2803/// or postfix suggestions to be valid.
2804/// For example, `a + b` requires parentheses to suggest `&(a + b)`,
2805/// but just `a` does not.
2806/// Similarly, `(a + b).c()` also requires parentheses.
2807/// This should not be used for other types of suggestions.
2808pub fn expr_needs_parens(expr: &Expr<'_>) -> bool {
2809 match expr.kind {
2810 // parenthesize if needed (Issue #46756)
2811 ExprKind::Cast(_, _) | ExprKind::Binary(_, _, _) => true,
2812 // parenthesize borrows of range literals (Issue #54505)
2813 _ if is_range_literal(expr) => true,
2814 _ => false,
2815 }
2816}
2817
2818#[derive(Debug, Clone, Copy, StableHash)]
2819pub enum ExprKind<'hir> {
2820 /// Allow anonymous constants from an inline `const` block
2821 ConstBlock(ConstBlock),
2822 /// An array (e.g., `[a, b, c, d]`).
2823 Array(&'hir [Expr<'hir>]),
2824 /// A function call.
2825 ///
2826 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
2827 /// and the second field is the list of arguments.
2828 /// This also represents calling the constructor of
2829 /// tuple-like ADTs such as tuple structs and enum variants.
2830 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
2831 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
2832 ///
2833 /// The `PathSegment` represents the method name and its generic arguments
2834 /// (within the angle brackets).
2835 /// The `&Expr` is the expression that evaluates
2836 /// to the object on which the method is being called on (the receiver),
2837 /// and the `&[Expr]` is the rest of the arguments.
2838 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
2839 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, x, [a, b, c, d], span)`.
2840 /// The final `Span` represents the span of the function and arguments
2841 /// (e.g. `foo::<Bar, Baz>(a, b, c, d)` in `x.foo::<Bar, Baz>(a, b, c, d)`
2842 ///
2843 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
2844 /// the `hir_id` of the `MethodCall` node itself.
2845 ///
2846 /// [`type_dependent_def_id`]: ../../rustc_middle/ty/struct.TypeckResults.html#method.type_dependent_def_id
2847 MethodCall(&'hir PathSegment<'hir>, &'hir Expr<'hir>, &'hir [Expr<'hir>], Span),
2848 /// An use expression (e.g., `var.use`).
2849 Use(&'hir Expr<'hir>, Span),
2850 /// A tuple (e.g., `(a, b, c, d)`).
2851 Tup(&'hir [Expr<'hir>]),
2852 /// A binary operation (e.g., `a + b`, `a * b`).
2853 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
2854 /// A unary operation (e.g., `!x`, `*x`).
2855 Unary(UnOp, &'hir Expr<'hir>),
2856 /// A literal (e.g., `1`, `"foo"`).
2857 Lit(Lit),
2858 /// A cast (e.g., `foo as f64`).
2859 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
2860 /// A type ascription (e.g., `x: Foo`). See RFC 3307.
2861 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
2862 /// Wraps the expression in a terminating scope.
2863 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
2864 ///
2865 /// This construct only exists to tweak the drop order in AST lowering.
2866 /// An example of that is the desugaring of `for` loops.
2867 DropTemps(&'hir Expr<'hir>),
2868 /// A `let $pat = $expr` expression.
2869 ///
2870 /// These are not [`LetStmt`] and only occur as expressions.
2871 /// The `let Some(x) = foo()` in `if let Some(x) = foo()` is an example of `Let(..)`.
2872 Let(&'hir LetExpr<'hir>),
2873 /// An `if` block, with an optional else block.
2874 ///
2875 /// I.e., `if <expr> { <expr> } else { <expr> }`.
2876 ///
2877 /// The "then" expr is always `ExprKind::Block`. If present, the "else" expr is always
2878 /// `ExprKind::Block` (for `else`) or `ExprKind::If` (for `else if`).
2879 /// Note that using an `Expr` instead of a `Block` for the "then" part is intentional,
2880 /// as it simplifies the type coercion machinery.
2881 If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
2882 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
2883 ///
2884 /// I.e., `'label: loop { <block> }`.
2885 ///
2886 /// The `Span` is the loop header (`for x in y`/`while let pat = expr`).
2887 Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span),
2888 /// A `match` block, with a source that indicates whether or not it is
2889 /// the result of a desugaring, and if so, which kind.
2890 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
2891 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
2892 ///
2893 /// The `Span` is the argument block `|...|`.
2894 ///
2895 /// This may also be a coroutine literal or an `async block` as indicated by the
2896 /// `Option<Movability>`.
2897 Closure(&'hir Closure<'hir>),
2898 /// A block (e.g., `'label: { ... }`).
2899 Block(&'hir Block<'hir>, Option<Label>),
2900
2901 /// An assignment (e.g., `a = foo()`).
2902 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
2903 /// An assignment with an operator.
2904 ///
2905 /// E.g., `a += 1`.
2906 AssignOp(AssignOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
2907 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
2908 Field(&'hir Expr<'hir>, Ident),
2909 /// An indexing operation (`foo[2]`).
2910 /// Similar to [`ExprKind::MethodCall`], the final `Span` represents the span of the brackets
2911 /// and index.
2912 Index(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
2913
2914 /// Path to a definition, possibly containing lifetime or type parameters.
2915 Path(QPath<'hir>),
2916
2917 /// A referencing operation (i.e., `&a` or `&mut a`).
2918 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
2919 /// A `break`, with an optional label to break.
2920 Break(Destination, Option<&'hir Expr<'hir>>),
2921 /// A `continue`, with an optional label.
2922 Continue(Destination),
2923 /// A `return`, with an optional value to be returned.
2924 Ret(Option<&'hir Expr<'hir>>),
2925 /// A `become`, with the value to be returned.
2926 Become(&'hir Expr<'hir>),
2927
2928 /// Inline assembly (from `asm!`), with its outputs and inputs.
2929 InlineAsm(&'hir InlineAsm<'hir>),
2930
2931 /// Field offset (`offset_of!`)
2932 OffsetOf(&'hir Ty<'hir>, &'hir [Ident]),
2933
2934 /// A struct or struct-like variant literal expression.
2935 ///
2936 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
2937 /// where `base` is the `Option<Expr>`.
2938 Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], StructTailExpr<'hir>),
2939
2940 /// An array literal constructed from one repeated element.
2941 ///
2942 /// E.g., `[1; 5]`. The first expression is the element
2943 /// to be repeated; the second is the number of times to repeat it.
2944 Repeat(&'hir Expr<'hir>, &'hir ConstArg<'hir>),
2945
2946 /// A suspension point for coroutines (i.e., `yield <expr>`).
2947 Yield(&'hir Expr<'hir>, YieldSource),
2948
2949 /// Operators which can be used to interconvert `unsafe` binder types.
2950 /// e.g. `unsafe<'a> &'a i32` <=> `&i32`.
2951 UnsafeBinderCast(UnsafeBinderCastKind, &'hir Expr<'hir>, Option<&'hir Ty<'hir>>),
2952
2953 /// A placeholder for an expression that wasn't syntactically well formed in some way.
2954 Err(rustc_span::ErrorGuaranteed),
2955}
2956
2957#[derive(Debug, Clone, Copy, StableHash)]
2958pub enum StructTailExpr<'hir> {
2959 /// A struct expression where all the fields are explicitly enumerated: `Foo { a, b }`.
2960 None,
2961 /// A struct expression with a "base", an expression of the same type as the outer struct that
2962 /// will be used to populate any fields not explicitly mentioned: `Foo { ..base }`
2963 Base(&'hir Expr<'hir>),
2964 /// A struct expression with a `..` tail but no "base" expression. The values from the struct
2965 /// fields' default values will be used to populate any fields not explicitly mentioned:
2966 /// `Foo { .. }`.
2967 DefaultFields(Span),
2968 /// No trailing `..` was written, and also, a parse error occurred inside the struct braces.
2969 ///
2970 /// This struct should be treated similarly to as if it had an `..` in it,
2971 /// in particular rather than reporting missing fields, because the parse error
2972 /// makes which fields the struct was intended to have not fully known.
2973 NoneWithError(ErrorGuaranteed),
2974}
2975
2976/// Represents an optionally `Self`-qualified value/type path or associated extension.
2977///
2978/// To resolve the path to a `DefId`, call [`qpath_res`].
2979///
2980/// [`qpath_res`]: ../../rustc_middle/ty/struct.TypeckResults.html#method.qpath_res
2981#[derive(Debug, Clone, Copy, StableHash)]
2982pub enum QPath<'hir> {
2983 /// Path to a definition, optionally "fully-qualified" with a `Self`
2984 /// type, if the path points to an associated item in a trait.
2985 ///
2986 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
2987 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
2988 /// even though they both have the same two-segment `Clone::clone` `Path`.
2989 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
2990
2991 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
2992 /// Will be resolved by type-checking to an associated item.
2993 ///
2994 /// UFCS source paths can desugar into this, with `Vec::new` turning into
2995 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
2996 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
2997 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
2998}
2999
3000impl<'hir> QPath<'hir> {
3001 /// Returns the span of this `QPath`.
3002 pub fn span(&self) -> Span {
3003 match *self {
3004 QPath::Resolved(_, path) => path.span,
3005 QPath::TypeRelative(qself, ps) => qself.span.to(ps.ident.span),
3006 }
3007 }
3008
3009 /// Returns the span of the qself of this `QPath`. For example, `()` in
3010 /// `<() as Trait>::method`.
3011 pub fn qself_span(&self) -> Span {
3012 match *self {
3013 QPath::Resolved(_, path) => path.span,
3014 QPath::TypeRelative(qself, _) => qself.span,
3015 }
3016 }
3017}
3018
3019/// Hints at the original code for a let statement.
3020#[derive(Copy, Clone, Debug, StableHash)]
3021pub enum LocalSource {
3022 /// A `match _ { .. }`.
3023 Normal,
3024 /// When lowering async functions, we create locals within the `async move` so that
3025 /// all parameters are dropped after the future is polled.
3026 ///
3027 /// ```ignore (pseudo-Rust)
3028 /// async fn foo(<pattern> @ x: Type) {
3029 /// async move {
3030 /// let <pattern> = x;
3031 /// }
3032 /// }
3033 /// ```
3034 AsyncFn,
3035 /// A desugared `<expr>.await`.
3036 AwaitDesugar,
3037 /// A desugared `expr = expr`, where the LHS is a tuple, struct, array or underscore expression.
3038 AssignDesugar,
3039 /// A contract `#[ensures(..)]` attribute injects a let binding for the check that runs at point of return.
3040 Contract,
3041}
3042
3043/// Hints at the original code for a `match _ { .. }`.
3044#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, StableHash, Encodable, Decodable)]
3045pub enum MatchSource {
3046 /// A `match _ { .. }`.
3047 Normal,
3048 /// A `expr.match { .. }`.
3049 Postfix,
3050 /// A desugared `for _ in _ { .. }` loop.
3051 ForLoopDesugar,
3052 /// A desugared `?` operator.
3053 TryDesugar(HirId),
3054 /// A desugared `<expr>.await`.
3055 AwaitDesugar,
3056 /// A desugared `format_args!()`.
3057 FormatArgs,
3058}
3059
3060impl MatchSource {
3061 #[inline]
3062 pub const fn name(self) -> &'static str {
3063 use MatchSource::*;
3064 match self {
3065 Normal => "match",
3066 Postfix => ".match",
3067 ForLoopDesugar => "for",
3068 TryDesugar(_) => "?",
3069 AwaitDesugar => ".await",
3070 FormatArgs => "format_args!()",
3071 }
3072 }
3073}
3074
3075/// The loop type that yielded an `ExprKind::Loop`.
3076#[derive(Copy, Clone, PartialEq, Debug, StableHash)]
3077pub enum LoopSource {
3078 /// A `loop { .. }` loop.
3079 Loop,
3080 /// A `while _ { .. }` loop.
3081 While,
3082 /// A `for _ in _ { .. }` loop.
3083 ForLoop,
3084}
3085
3086impl LoopSource {
3087 pub fn name(self) -> &'static str {
3088 match self {
3089 LoopSource::Loop => "loop",
3090 LoopSource::While => "while",
3091 LoopSource::ForLoop => "for",
3092 }
3093 }
3094}
3095
3096#[derive(Copy, Clone, Debug, PartialEq, StableHash)]
3097pub enum LoopIdError {
3098 OutsideLoopScope,
3099 UnlabeledCfInWhileCondition,
3100 UnresolvedLabel,
3101}
3102
3103impl fmt::Display for LoopIdError {
3104 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3105 f.write_str(match self {
3106 LoopIdError::OutsideLoopScope => "not inside loop scope",
3107 LoopIdError::UnlabeledCfInWhileCondition => {
3108 "unlabeled control flow (break or continue) in while condition"
3109 }
3110 LoopIdError::UnresolvedLabel => "label not found",
3111 })
3112 }
3113}
3114
3115#[derive(Copy, Clone, Debug, PartialEq, StableHash)]
3116pub struct Destination {
3117 /// This is `Some(_)` iff there is an explicit user-specified 'label
3118 pub label: Option<Label>,
3119
3120 /// These errors are caught and then reported during the diagnostics pass in
3121 /// `librustc_passes/loops.rs`
3122 pub target_id: Result<HirId, LoopIdError>,
3123}
3124
3125/// The yield kind that caused an `ExprKind::Yield`.
3126#[derive(Copy, Clone, Debug, StableHash)]
3127pub enum YieldSource {
3128 /// An `<expr>.await`.
3129 Await { expr: Option<HirId> },
3130 /// A plain `yield`.
3131 Yield,
3132}
3133
3134impl fmt::Display for YieldSource {
3135 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3136 f.write_str(match self {
3137 YieldSource::Await { .. } => "`await`",
3138 YieldSource::Yield => "`yield`",
3139 })
3140 }
3141}
3142
3143// N.B., if you change this, you'll probably want to change the corresponding
3144// type structure in middle/ty.rs as well.
3145#[derive(Debug, Clone, Copy, StableHash)]
3146pub struct MutTy<'hir> {
3147 pub ty: &'hir Ty<'hir>,
3148 pub mutbl: Mutability,
3149}
3150
3151/// Represents a function's signature in a trait declaration,
3152/// trait implementation, or a free function.
3153#[derive(Debug, Clone, Copy, StableHash)]
3154pub struct FnSig<'hir> {
3155 pub header: FnHeader,
3156 pub decl: &'hir FnDecl<'hir>,
3157 pub span: Span,
3158}
3159
3160// The bodies for items are stored "out of line", in a separate
3161// hashmap in the `Crate`. Here we just record the hir-id of the item
3162// so it can fetched later.
3163#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, StableHash)]
3164pub struct TraitItemId {
3165 pub owner_id: OwnerId,
3166}
3167
3168impl TraitItemId {
3169 #[inline]
3170 pub fn hir_id(&self) -> HirId {
3171 // Items are always HIR owners.
3172 HirId::make_owner(self.owner_id.def_id)
3173 }
3174}
3175
3176/// Represents an item declaration within a trait declaration,
3177/// possibly including a default implementation. A trait item is
3178/// either required (meaning it doesn't have an implementation, just a
3179/// signature) or provided (meaning it has a default implementation).
3180#[derive(Debug, Clone, Copy, StableHash)]
3181pub struct TraitItem<'hir> {
3182 pub ident: Ident,
3183 pub owner_id: OwnerId,
3184 pub generics: &'hir Generics<'hir>,
3185 pub kind: TraitItemKind<'hir>,
3186 pub span: Span,
3187 pub defaultness: Defaultness,
3188 pub has_delayed_lints: bool,
3189}
3190
3191macro_rules! expect_methods_self_kind {
3192 ( $( $name:ident, $ret_ty:ty, $pat:pat, $ret_val:expr; )* ) => {
3193 $(
3194 #[track_caller]
3195 pub fn $name(&self) -> $ret_ty {
3196 let $pat = &self.kind else { expect_failed(stringify!($name), self) };
3197 $ret_val
3198 }
3199 )*
3200 }
3201}
3202
3203macro_rules! expect_methods_self {
3204 ( $( $name:ident, $ret_ty:ty, $pat:pat, $ret_val:expr; )* ) => {
3205 $(
3206 #[track_caller]
3207 pub fn $name(&self) -> $ret_ty {
3208 let $pat = self else { expect_failed(stringify!($name), self) };
3209 $ret_val
3210 }
3211 )*
3212 }
3213}
3214
3215#[track_caller]
3216fn expect_failed<T: fmt::Debug>(ident: &'static str, found: T) -> ! {
3217 panic!("{ident}: found {found:?}")
3218}
3219
3220impl<'hir> TraitItem<'hir> {
3221 #[inline]
3222 pub fn hir_id(&self) -> HirId {
3223 // Items are always HIR owners.
3224 HirId::make_owner(self.owner_id.def_id)
3225 }
3226
3227 pub fn trait_item_id(&self) -> TraitItemId {
3228 TraitItemId { owner_id: self.owner_id }
3229 }
3230
3231 expect_methods_self_kind! {
3232 expect_const, (&'hir Ty<'hir>, Option<ConstItemRhs<'hir>>),
3233 TraitItemKind::Const(ty, rhs, _), (ty, *rhs);
3234
3235 expect_fn, (&FnSig<'hir>, &TraitFn<'hir>),
3236 TraitItemKind::Fn(ty, trfn), (ty, trfn);
3237
3238 expect_type, (GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
3239 TraitItemKind::Type(bounds, ty), (bounds, *ty);
3240 }
3241}
3242
3243/// Represents a trait method's body (or just argument names).
3244#[derive(Debug, Clone, Copy, StableHash)]
3245pub enum TraitFn<'hir> {
3246 /// No default body in the trait, just a signature.
3247 Required(&'hir [Option<Ident>]),
3248
3249 /// Both signature and body are provided in the trait.
3250 Provided(BodyId),
3251}
3252
3253#[derive(Debug, Clone, Copy, PartialEq, Eq, StableHash)]
3254pub enum IsTypeConst {
3255 No,
3256 Yes,
3257}
3258
3259impl From<bool> for IsTypeConst {
3260 fn from(value: bool) -> Self {
3261 if value { Self::Yes } else { Self::No }
3262 }
3263}
3264
3265impl From<IsTypeConst> for bool {
3266 fn from(value: IsTypeConst) -> Self {
3267 matches!(value, IsTypeConst::Yes)
3268 }
3269}
3270
3271/// Represents a trait method or associated constant or type
3272#[derive(Debug, Clone, Copy, StableHash)]
3273pub enum TraitItemKind<'hir> {
3274 // FIXME(mgca) eventually want to move the option that is around `ConstItemRhs<'hir>`
3275 // into `ConstItemRhs`, much like `ast::ConstItemRhsKind`, but for now mark whether
3276 // this node is a TypeConst with a flag.
3277 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
3278 Const(&'hir Ty<'hir>, Option<ConstItemRhs<'hir>>, IsTypeConst),
3279 /// An associated function with an optional body.
3280 Fn(FnSig<'hir>, TraitFn<'hir>),
3281 /// An associated type with (possibly empty) bounds and optional concrete
3282 /// type.
3283 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
3284}
3285
3286// The bodies for items are stored "out of line", in a separate
3287// hashmap in the `Crate`. Here we just record the hir-id of the item
3288// so it can fetched later.
3289#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, StableHash)]
3290pub struct ImplItemId {
3291 pub owner_id: OwnerId,
3292}
3293
3294impl ImplItemId {
3295 #[inline]
3296 pub fn hir_id(&self) -> HirId {
3297 // Items are always HIR owners.
3298 HirId::make_owner(self.owner_id.def_id)
3299 }
3300}
3301
3302/// Represents an associated item within an impl block.
3303///
3304/// Refer to [`Impl`] for an impl block declaration.
3305#[derive(Debug, Clone, Copy, StableHash)]
3306pub struct ImplItem<'hir> {
3307 pub ident: Ident,
3308 pub owner_id: OwnerId,
3309 pub generics: &'hir Generics<'hir>,
3310 pub kind: ImplItemKind<'hir>,
3311 pub impl_kind: ImplItemImplKind,
3312 pub span: Span,
3313 pub has_delayed_lints: bool,
3314}
3315
3316#[derive(Debug, Clone, Copy, StableHash)]
3317pub enum ImplItemImplKind {
3318 Inherent {
3319 vis_span: Span,
3320 },
3321 Trait {
3322 defaultness: Defaultness,
3323 /// Item in the trait that this item implements
3324 trait_item_def_id: Result<DefId, ErrorGuaranteed>,
3325 },
3326}
3327
3328impl<'hir> ImplItem<'hir> {
3329 #[inline]
3330 pub fn hir_id(&self) -> HirId {
3331 // Items are always HIR owners.
3332 HirId::make_owner(self.owner_id.def_id)
3333 }
3334
3335 pub fn impl_item_id(&self) -> ImplItemId {
3336 ImplItemId { owner_id: self.owner_id }
3337 }
3338
3339 pub fn vis_span(&self) -> Option<Span> {
3340 match self.impl_kind {
3341 ImplItemImplKind::Trait { .. } => None,
3342 ImplItemImplKind::Inherent { vis_span, .. } => Some(vis_span),
3343 }
3344 }
3345
3346 expect_methods_self_kind! {
3347 expect_const, (&'hir Ty<'hir>, ConstItemRhs<'hir>), ImplItemKind::Const(ty, rhs), (ty, *rhs);
3348 expect_fn, (&FnSig<'hir>, BodyId), ImplItemKind::Fn(ty, body), (ty, *body);
3349 expect_type, &'hir Ty<'hir>, ImplItemKind::Type(ty), ty;
3350 }
3351}
3352
3353/// Represents various kinds of content within an `impl`.
3354#[derive(Debug, Clone, Copy, StableHash)]
3355pub enum ImplItemKind<'hir> {
3356 /// An associated constant of the given type, set to the constant result
3357 /// of the expression.
3358 Const(&'hir Ty<'hir>, ConstItemRhs<'hir>),
3359 /// An associated function implementation with the given signature and body.
3360 Fn(FnSig<'hir>, BodyId),
3361 /// An associated type.
3362 Type(&'hir Ty<'hir>),
3363}
3364
3365/// A constraint on an associated item.
3366///
3367/// ### Examples
3368///
3369/// * the `A = Ty` and `B = Ty` in `Trait<A = Ty, B = Ty>`
3370/// * the `G<Ty> = Ty` in `Trait<G<Ty> = Ty>`
3371/// * the `A: Bound` in `Trait<A: Bound>`
3372/// * the `RetTy` in `Trait(ArgTy, ArgTy) -> RetTy`
3373/// * the `C = { Ct }` in `Trait<C = { Ct }>` (feature `min_generic_const_args`)
3374/// * the `f(..): Bound` in `Trait<f(..): Bound>` (feature `return_type_notation`)
3375#[derive(Debug, Clone, Copy, StableHash)]
3376pub struct AssocItemConstraint<'hir> {
3377 #[stable_hash(ignore)]
3378 pub hir_id: HirId,
3379 pub ident: Ident,
3380 pub gen_args: &'hir GenericArgs<'hir>,
3381 pub kind: AssocItemConstraintKind<'hir>,
3382 pub span: Span,
3383}
3384
3385impl<'hir> AssocItemConstraint<'hir> {
3386 /// Obtain the type on the RHS of an assoc ty equality constraint if applicable.
3387 pub fn ty(self) -> Option<&'hir Ty<'hir>> {
3388 match self.kind {
3389 AssocItemConstraintKind::Equality { term: Term::Ty(ty) } => Some(ty),
3390 _ => None,
3391 }
3392 }
3393
3394 /// Obtain the const on the RHS of an assoc const equality constraint if applicable.
3395 pub fn ct(self) -> Option<&'hir ConstArg<'hir>> {
3396 match self.kind {
3397 AssocItemConstraintKind::Equality { term: Term::Const(ct) } => Some(ct),
3398 _ => None,
3399 }
3400 }
3401}
3402
3403#[derive(Debug, Clone, Copy, StableHash)]
3404pub enum Term<'hir> {
3405 Ty(&'hir Ty<'hir>),
3406 Const(&'hir ConstArg<'hir>),
3407}
3408
3409impl<'hir> From<&'hir Ty<'hir>> for Term<'hir> {
3410 fn from(ty: &'hir Ty<'hir>) -> Self {
3411 Term::Ty(ty)
3412 }
3413}
3414
3415impl<'hir> From<&'hir ConstArg<'hir>> for Term<'hir> {
3416 fn from(c: &'hir ConstArg<'hir>) -> Self {
3417 Term::Const(c)
3418 }
3419}
3420
3421/// The kind of [associated item constraint][AssocItemConstraint].
3422#[derive(Debug, Clone, Copy, StableHash)]
3423pub enum AssocItemConstraintKind<'hir> {
3424 /// An equality constraint for an associated item (e.g., `AssocTy = Ty` in `Trait<AssocTy = Ty>`).
3425 ///
3426 /// Also known as an *associated item binding* (we *bind* an associated item to a term).
3427 ///
3428 /// Furthermore, associated type equality constraints can also be referred to as *associated type
3429 /// bindings*. Similarly with associated const equality constraints and *associated const bindings*.
3430 Equality { term: Term<'hir> },
3431 /// A bound on an associated type (e.g., `AssocTy: Bound` in `Trait<AssocTy: Bound>`).
3432 Bound { bounds: &'hir [GenericBound<'hir>] },
3433}
3434
3435impl<'hir> AssocItemConstraintKind<'hir> {
3436 pub fn descr(&self) -> &'static str {
3437 match self {
3438 AssocItemConstraintKind::Equality { .. } => "binding",
3439 AssocItemConstraintKind::Bound { .. } => "constraint",
3440 }
3441 }
3442}
3443
3444/// An uninhabited enum used to make `Infer` variants on [`Ty`] and [`ConstArg`] be
3445/// unreachable. Zero-Variant enums are guaranteed to have the same layout as the never
3446/// type.
3447#[derive(Debug, Clone, Copy, StableHash)]
3448pub enum AmbigArg {}
3449
3450/// Represents a type in the `HIR`.
3451///
3452/// For an explanation of the `Unambig` generic parameter see the dev-guide:
3453/// <https://rustc-dev-guide.rust-lang.org/ambig-unambig-ty-and-consts.html>
3454#[derive(Debug, Clone, Copy, StableHash)]
3455#[repr(C)]
3456pub struct Ty<'hir, Unambig = ()> {
3457 #[stable_hash(ignore)]
3458 pub hir_id: HirId,
3459 pub span: Span,
3460 pub kind: TyKind<'hir, Unambig>,
3461}
3462
3463impl<'hir> Ty<'hir, AmbigArg> {
3464 /// Converts a `Ty` in an ambiguous position to one in an unambiguous position.
3465 ///
3466 /// Functions accepting an unambiguous types may expect the [`TyKind::Infer`] variant
3467 /// to be used. Care should be taken to separately handle infer types when calling this
3468 /// function as it cannot be handled by downstream code making use of the returned ty.
3469 ///
3470 /// In practice this may mean overriding the [`Visitor::visit_infer`][visit_infer] method on hir visitors, or
3471 /// specifically matching on [`GenericArg::Infer`] when handling generic arguments.
3472 ///
3473 /// [visit_infer]: [rustc_hir::intravisit::Visitor::visit_infer]
3474 pub fn as_unambig_ty(&self) -> &Ty<'hir> {
3475 // SAFETY: `Ty` is `repr(C)` and `TyKind` is marked `repr(u8)` so that the layout is
3476 // the same across different ZST type arguments.
3477 let ptr = self as *const Ty<'hir, AmbigArg> as *const Ty<'hir, ()>;
3478 unsafe { &*ptr }
3479 }
3480}
3481
3482impl<'hir> Ty<'hir> {
3483 /// Converts a `Ty` in an unambiguous position to one in an ambiguous position. This is
3484 /// fallible as the [`TyKind::Infer`] variant is not present in ambiguous positions.
3485 ///
3486 /// Functions accepting ambiguous types will not handle the [`TyKind::Infer`] variant, if
3487 /// infer types are relevant to you then care should be taken to handle them separately.
3488 pub fn try_as_ambig_ty(&self) -> Option<&Ty<'hir, AmbigArg>> {
3489 if let TyKind::Infer(()) = self.kind {
3490 return None;
3491 }
3492
3493 // SAFETY: `Ty` is `repr(C)` and `TyKind` is marked `repr(u8)` so that the layout is
3494 // the same across different ZST type arguments. We also asserted that the `self` is
3495 // not a `TyKind::Infer` so there is no risk of transmuting a `()` to `AmbigArg`.
3496 let ptr = self as *const Ty<'hir> as *const Ty<'hir, AmbigArg>;
3497 Some(unsafe { &*ptr })
3498 }
3499}
3500
3501impl<'hir> Ty<'hir, AmbigArg> {
3502 pub fn peel_refs(&self) -> &Ty<'hir> {
3503 let mut final_ty = self.as_unambig_ty();
3504 while let TyKind::Ref(_, MutTy { ty, .. }) = &final_ty.kind {
3505 final_ty = ty;
3506 }
3507 final_ty
3508 }
3509}
3510
3511impl<'hir> Ty<'hir> {
3512 pub fn peel_refs(&self) -> &Self {
3513 let mut final_ty = self;
3514 while let TyKind::Ref(_, MutTy { ty, .. }) = &final_ty.kind {
3515 final_ty = ty;
3516 }
3517 final_ty
3518 }
3519
3520 /// Returns `true` if `param_def_id` matches the `bounded_ty` of this predicate.
3521 pub fn as_generic_param(&self) -> Option<(DefId, Ident)> {
3522 let TyKind::Path(QPath::Resolved(None, path)) = self.kind else {
3523 return None;
3524 };
3525 let [segment] = &path.segments else {
3526 return None;
3527 };
3528 match path.res {
3529 Res::Def(DefKind::TyParam, def_id) | Res::SelfTyParam { trait_: def_id } => {
3530 Some((def_id, segment.ident))
3531 }
3532 _ => None,
3533 }
3534 }
3535
3536 pub fn find_self_aliases(&self) -> Vec<Span> {
3537 use crate::intravisit::Visitor;
3538 struct MyVisitor(Vec<Span>);
3539 impl<'v> Visitor<'v> for MyVisitor {
3540 fn visit_ty(&mut self, t: &'v Ty<'v, AmbigArg>) {
3541 if matches!(
3542 &t.kind,
3543 TyKind::Path(QPath::Resolved(
3544 _,
3545 Path { res: crate::def::Res::SelfTyAlias { .. }, .. },
3546 ))
3547 ) {
3548 self.0.push(t.span);
3549 return;
3550 }
3551 crate::intravisit::walk_ty(self, t);
3552 }
3553 }
3554
3555 let mut my_visitor = MyVisitor(vec![]);
3556 my_visitor.visit_ty_unambig(self);
3557 my_visitor.0
3558 }
3559
3560 /// Whether `ty` is a type with `_` placeholders that can be inferred. Used in diagnostics only to
3561 /// use inference to provide suggestions for the appropriate type if possible.
3562 pub fn is_suggestable_infer_ty(&self) -> bool {
3563 fn are_suggestable_generic_args(generic_args: &[GenericArg<'_>]) -> bool {
3564 generic_args.iter().any(|arg| match arg {
3565 GenericArg::Type(ty) => ty.as_unambig_ty().is_suggestable_infer_ty(),
3566 GenericArg::Infer(_) => true,
3567 _ => false,
3568 })
3569 }
3570 debug!(?self);
3571 match &self.kind {
3572 TyKind::Infer(()) => true,
3573 TyKind::Slice(ty) => ty.is_suggestable_infer_ty(),
3574 TyKind::Array(ty, length) => {
3575 ty.is_suggestable_infer_ty() || matches!(length.kind, ConstArgKind::Infer(..))
3576 }
3577 TyKind::Tup(tys) => tys.iter().any(Self::is_suggestable_infer_ty),
3578 TyKind::Ptr(mut_ty) | TyKind::Ref(_, mut_ty) => mut_ty.ty.is_suggestable_infer_ty(),
3579 TyKind::Path(QPath::TypeRelative(ty, segment)) => {
3580 ty.is_suggestable_infer_ty() || are_suggestable_generic_args(segment.args().args)
3581 }
3582 TyKind::Path(QPath::Resolved(ty_opt, Path { segments, .. })) => {
3583 ty_opt.is_some_and(Self::is_suggestable_infer_ty)
3584 || segments
3585 .iter()
3586 .any(|segment| are_suggestable_generic_args(segment.args().args))
3587 }
3588 _ => false,
3589 }
3590 }
3591}
3592
3593/// Not represented directly in the AST; referred to by name through a `ty_path`.
3594#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug, StableHash)]
3595pub enum PrimTy {
3596 Int(IntTy),
3597 Uint(UintTy),
3598 Float(FloatTy),
3599 Str,
3600 Bool,
3601 Char,
3602}
3603
3604impl PrimTy {
3605 /// All of the primitive types
3606 pub const ALL: [Self; 19] = [
3607 // any changes here should also be reflected in `PrimTy::from_name`
3608 Self::Int(IntTy::I8),
3609 Self::Int(IntTy::I16),
3610 Self::Int(IntTy::I32),
3611 Self::Int(IntTy::I64),
3612 Self::Int(IntTy::I128),
3613 Self::Int(IntTy::Isize),
3614 Self::Uint(UintTy::U8),
3615 Self::Uint(UintTy::U16),
3616 Self::Uint(UintTy::U32),
3617 Self::Uint(UintTy::U64),
3618 Self::Uint(UintTy::U128),
3619 Self::Uint(UintTy::Usize),
3620 Self::Float(FloatTy::F16),
3621 Self::Float(FloatTy::F32),
3622 Self::Float(FloatTy::F64),
3623 Self::Float(FloatTy::F128),
3624 Self::Bool,
3625 Self::Char,
3626 Self::Str,
3627 ];
3628
3629 /// Like [`PrimTy::name`], but returns a &str instead of a symbol.
3630 ///
3631 /// Used by clippy.
3632 pub fn name_str(self) -> &'static str {
3633 match self {
3634 PrimTy::Int(i) => i.name_str(),
3635 PrimTy::Uint(u) => u.name_str(),
3636 PrimTy::Float(f) => f.name_str(),
3637 PrimTy::Str => "str",
3638 PrimTy::Bool => "bool",
3639 PrimTy::Char => "char",
3640 }
3641 }
3642
3643 pub fn name(self) -> Symbol {
3644 match self {
3645 PrimTy::Int(i) => i.name(),
3646 PrimTy::Uint(u) => u.name(),
3647 PrimTy::Float(f) => f.name(),
3648 PrimTy::Str => sym::str,
3649 PrimTy::Bool => sym::bool,
3650 PrimTy::Char => sym::char,
3651 }
3652 }
3653
3654 /// Returns the matching `PrimTy` for a `Symbol` such as "str" or "i32".
3655 /// Returns `None` if no matching type is found.
3656 pub fn from_name(name: Symbol) -> Option<Self> {
3657 let ty = match name {
3658 // any changes here should also be reflected in `PrimTy::ALL`
3659 sym::i8 => Self::Int(IntTy::I8),
3660 sym::i16 => Self::Int(IntTy::I16),
3661 sym::i32 => Self::Int(IntTy::I32),
3662 sym::i64 => Self::Int(IntTy::I64),
3663 sym::i128 => Self::Int(IntTy::I128),
3664 sym::isize => Self::Int(IntTy::Isize),
3665 sym::u8 => Self::Uint(UintTy::U8),
3666 sym::u16 => Self::Uint(UintTy::U16),
3667 sym::u32 => Self::Uint(UintTy::U32),
3668 sym::u64 => Self::Uint(UintTy::U64),
3669 sym::u128 => Self::Uint(UintTy::U128),
3670 sym::usize => Self::Uint(UintTy::Usize),
3671 sym::f16 => Self::Float(FloatTy::F16),
3672 sym::f32 => Self::Float(FloatTy::F32),
3673 sym::f64 => Self::Float(FloatTy::F64),
3674 sym::f128 => Self::Float(FloatTy::F128),
3675 sym::bool => Self::Bool,
3676 sym::char => Self::Char,
3677 sym::str => Self::Str,
3678 _ => return None,
3679 };
3680 Some(ty)
3681 }
3682}
3683
3684#[derive(Debug, Clone, Copy, StableHash)]
3685pub struct FnPtrTy<'hir> {
3686 pub safety: Safety,
3687 pub abi: ExternAbi,
3688 pub generic_params: &'hir [GenericParam<'hir>],
3689 pub decl: &'hir FnDecl<'hir>,
3690 // `Option` because bare fn parameter identifiers are optional. We also end up
3691 // with `None` in some error cases, e.g. invalid parameter patterns.
3692 pub param_idents: &'hir [Option<Ident>],
3693}
3694
3695#[derive(Debug, Clone, Copy, StableHash)]
3696pub struct UnsafeBinderTy<'hir> {
3697 pub generic_params: &'hir [GenericParam<'hir>],
3698 pub inner_ty: &'hir Ty<'hir>,
3699}
3700
3701#[derive(Debug, Clone, Copy, StableHash)]
3702pub struct OpaqueTy<'hir> {
3703 #[stable_hash(ignore)]
3704 pub hir_id: HirId,
3705 pub def_id: LocalDefId,
3706 pub bounds: GenericBounds<'hir>,
3707 pub origin: OpaqueTyOrigin<LocalDefId>,
3708 pub span: Span,
3709}
3710
3711#[derive(Debug, Clone, Copy, StableHash, Encodable, Decodable)]
3712pub enum PreciseCapturingArgKind<T, U> {
3713 Lifetime(T),
3714 /// Non-lifetime argument (type or const)
3715 Param(U),
3716}
3717
3718pub type PreciseCapturingArg<'hir> =
3719 PreciseCapturingArgKind<&'hir Lifetime, PreciseCapturingNonLifetimeArg>;
3720
3721impl PreciseCapturingArg<'_> {
3722 pub fn hir_id(self) -> HirId {
3723 match self {
3724 PreciseCapturingArg::Lifetime(lt) => lt.hir_id,
3725 PreciseCapturingArg::Param(param) => param.hir_id,
3726 }
3727 }
3728
3729 pub fn name(self) -> Symbol {
3730 match self {
3731 PreciseCapturingArg::Lifetime(lt) => lt.ident.name,
3732 PreciseCapturingArg::Param(param) => param.ident.name,
3733 }
3734 }
3735}
3736
3737/// We need to have a [`Node`] for the [`HirId`] that we attach the type/const param
3738/// resolution to. Lifetimes don't have this problem, and for them, it's actually
3739/// kind of detrimental to use a custom node type versus just using [`Lifetime`],
3740/// since resolve_bound_vars operates on `Lifetime`s.
3741#[derive(Debug, Clone, Copy, StableHash)]
3742pub struct PreciseCapturingNonLifetimeArg {
3743 #[stable_hash(ignore)]
3744 pub hir_id: HirId,
3745 pub ident: Ident,
3746 pub res: Res,
3747}
3748
3749#[derive(Copy, Clone, PartialEq, Eq, Debug)]
3750#[derive(StableHash, Encodable, Decodable)]
3751pub enum RpitContext {
3752 Trait,
3753 TraitImpl,
3754}
3755
3756/// From whence the opaque type came.
3757#[derive(Copy, Clone, PartialEq, Eq, Debug)]
3758#[derive(StableHash, Encodable, Decodable)]
3759pub enum OpaqueTyOrigin<D> {
3760 /// `-> impl Trait`
3761 FnReturn {
3762 /// The defining function.
3763 parent: D,
3764 // Whether this is an RPITIT (return position impl trait in trait)
3765 in_trait_or_impl: Option<RpitContext>,
3766 },
3767 /// `async fn`
3768 AsyncFn {
3769 /// The defining function.
3770 parent: D,
3771 // Whether this is an AFIT (async fn in trait)
3772 in_trait_or_impl: Option<RpitContext>,
3773 },
3774 /// type aliases: `type Foo = impl Trait;`
3775 TyAlias {
3776 /// The type alias or associated type parent of the TAIT/ATPIT
3777 parent: D,
3778 /// associated types in impl blocks for traits.
3779 in_assoc_ty: bool,
3780 },
3781}
3782
3783// Ids of parent (or child) path segment that contains user-specified args
3784#[derive(Debug, Clone, Copy, PartialEq, Eq, StableHash)]
3785pub struct DelegationGenerics {
3786 pub parent_args_segment_id: Option<HirId>,
3787 pub child_args_segment_id: Option<HirId>,
3788 pub self_ty_id: Option<HirId>,
3789 pub propagate_self_ty: bool,
3790}
3791
3792#[derive(Debug, Clone, Copy, PartialEq, Eq, StableHash)]
3793pub enum InferDelegationSig<'hir> {
3794 Input(usize),
3795 // Place generics info here, as we always specify output type for delegations.
3796 Output(&'hir DelegationGenerics),
3797}
3798
3799#[derive(Debug, Clone, Copy, PartialEq, Eq, StableHash)]
3800pub enum InferDelegation<'hir> {
3801 /// Infer the type of this `DefId` through `tcx.type_of(def_id).instantiate_identity()`,
3802 /// used for const types propagation.
3803 DefId(DefId),
3804 /// Used during signature inheritance, `DefId` corresponds to the signature function.
3805 Sig(DefId, InferDelegationSig<'hir>),
3806}
3807
3808/// The various kinds of types recognized by the compiler.
3809///
3810/// For an explanation of the `Unambig` generic parameter see the dev-guide:
3811/// <https://rustc-dev-guide.rust-lang.org/ambig-unambig-ty-and-consts.html>
3812// SAFETY: `repr(u8)` is required so that `TyKind<()>` and `TyKind<!>` are layout compatible
3813#[repr(u8, C)]
3814#[derive(Debug, Clone, Copy, StableHash)]
3815pub enum TyKind<'hir, Unambig = ()> {
3816 /// Actual type should be inherited from `DefId` signature
3817 InferDelegation(InferDelegation<'hir>),
3818 /// A variable length slice (i.e., `[T]`).
3819 Slice(&'hir Ty<'hir>),
3820 /// A fixed length array (i.e., `[T; n]`).
3821 Array(&'hir Ty<'hir>, &'hir ConstArg<'hir>),
3822 /// A raw pointer (i.e., `*const T` or `*mut T`).
3823 Ptr(MutTy<'hir>),
3824 /// A reference (i.e., `&'a T` or `&'a mut T`).
3825 Ref(&'hir Lifetime, MutTy<'hir>),
3826 /// A function pointer (e.g., `fn(usize) -> bool`).
3827 FnPtr(&'hir FnPtrTy<'hir>),
3828 /// An unsafe binder type (e.g. `unsafe<'a> Foo<'a>`).
3829 UnsafeBinder(&'hir UnsafeBinderTy<'hir>),
3830 /// The never type (`!`).
3831 Never,
3832 /// A tuple (`(A, B, C, D, ...)`).
3833 Tup(&'hir [Ty<'hir>]),
3834 /// A path to a type definition (`module::module::...::Type`), or an
3835 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
3836 ///
3837 /// Type parameters may be stored in each `PathSegment`.
3838 Path(QPath<'hir>),
3839 /// An opaque type definition itself. This is only used for `impl Trait`.
3840 OpaqueDef(&'hir OpaqueTy<'hir>),
3841 /// A trait ascription type, which is `impl Trait` within a local binding.
3842 TraitAscription(GenericBounds<'hir>),
3843 /// A trait object type `Bound1 + Bound2 + Bound3`
3844 /// where `Bound` is a trait or a lifetime.
3845 ///
3846 /// We use pointer tagging to represent a `&'hir Lifetime` and `TraitObjectSyntax` pair
3847 /// as otherwise this type being `repr(C)` would result in `TyKind` increasing in size.
3848 TraitObject(&'hir [PolyTraitRef<'hir>], TaggedRef<'hir, Lifetime, TraitObjectSyntax>),
3849 /// Placeholder for a type that has failed to be defined.
3850 Err(rustc_span::ErrorGuaranteed),
3851 /// Pattern types (`pattern_type!(u32 is 1..)`)
3852 Pat(&'hir Ty<'hir>, &'hir TyPat<'hir>),
3853 /// Field representing type (`field_of!(Struct, field)`).
3854 ///
3855 /// The optional ident is the variant when an enum is passed `field_of!(Enum, Variant.field)`.
3856 FieldOf(&'hir Ty<'hir>, &'hir TyFieldPath),
3857 /// `TyKind::Infer` means the type should be inferred instead of it having been
3858 /// specified. This can appear anywhere in a type.
3859 ///
3860 /// This variant is not always used to represent inference types, sometimes
3861 /// [`GenericArg::Infer`] is used instead.
3862 Infer(Unambig),
3863}
3864
3865#[derive(Debug, Clone, Copy, StableHash)]
3866pub enum InlineAsmOperand<'hir> {
3867 In {
3868 reg: InlineAsmRegOrRegClass,
3869 expr: &'hir Expr<'hir>,
3870 },
3871 Out {
3872 reg: InlineAsmRegOrRegClass,
3873 late: bool,
3874 expr: Option<&'hir Expr<'hir>>,
3875 },
3876 InOut {
3877 reg: InlineAsmRegOrRegClass,
3878 late: bool,
3879 expr: &'hir Expr<'hir>,
3880 },
3881 SplitInOut {
3882 reg: InlineAsmRegOrRegClass,
3883 late: bool,
3884 in_expr: &'hir Expr<'hir>,
3885 out_expr: Option<&'hir Expr<'hir>>,
3886 },
3887 Const {
3888 anon_const: ConstBlock,
3889 },
3890 SymFn {
3891 expr: &'hir Expr<'hir>,
3892 },
3893 SymStatic {
3894 path: QPath<'hir>,
3895 def_id: DefId,
3896 },
3897 Label {
3898 block: &'hir Block<'hir>,
3899 },
3900}
3901
3902impl<'hir> InlineAsmOperand<'hir> {
3903 pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
3904 match *self {
3905 Self::In { reg, .. }
3906 | Self::Out { reg, .. }
3907 | Self::InOut { reg, .. }
3908 | Self::SplitInOut { reg, .. } => Some(reg),
3909 Self::Const { .. }
3910 | Self::SymFn { .. }
3911 | Self::SymStatic { .. }
3912 | Self::Label { .. } => None,
3913 }
3914 }
3915
3916 pub fn is_clobber(&self) -> bool {
3917 matches!(
3918 self,
3919 InlineAsmOperand::Out { reg: InlineAsmRegOrRegClass::Reg(_), late: _, expr: None }
3920 )
3921 }
3922}
3923
3924#[derive(Debug, Clone, Copy, StableHash)]
3925pub struct InlineAsm<'hir> {
3926 pub asm_macro: ast::AsmMacro,
3927 pub template: &'hir [InlineAsmTemplatePiece],
3928 pub template_strs: &'hir [(Symbol, Option<Symbol>, Span)],
3929 pub operands: &'hir [(InlineAsmOperand<'hir>, Span)],
3930 pub options: InlineAsmOptions,
3931 pub line_spans: &'hir [Span],
3932}
3933
3934impl InlineAsm<'_> {
3935 pub fn contains_label(&self) -> bool {
3936 self.operands.iter().any(|x| matches!(x.0, InlineAsmOperand::Label { .. }))
3937 }
3938}
3939
3940/// Represents a parameter in a function header.
3941#[derive(Debug, Clone, Copy, StableHash)]
3942pub struct Param<'hir> {
3943 #[stable_hash(ignore)]
3944 pub hir_id: HirId,
3945 pub pat: &'hir Pat<'hir>,
3946 pub ty_span: Span,
3947 pub span: Span,
3948}
3949
3950/// Contains the packed non-type fields of a function declaration.
3951// FIXME(splat): add the splatted argument index as a u16
3952#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
3953#[derive(Encodable, Decodable, StableHash)]
3954pub struct FnDeclFlags {
3955 /// Holds the c_variadic and lifetime_elision_allowed bitflags, and 3 bits for the `ImplicitSelfKind`.
3956 flags: u8,
3957}
3958
3959impl fmt::Debug for FnDeclFlags {
3960 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3961 let mut f = f.debug_tuple("FnDeclFlags");
3962 f.field(&format!("ImplicitSelfKind({:?})", self.implicit_self()));
3963
3964 if self.lifetime_elision_allowed() {
3965 f.field(&"LifetimeElisionAllowed");
3966 } else {
3967 f.field(&"NoLifetimeElision");
3968 };
3969
3970 if self.c_variadic() {
3971 f.field(&"CVariadic");
3972 };
3973
3974 f.finish()
3975 }
3976}
3977
3978impl FnDeclFlags {
3979 /// Mask for the implicit self kind.
3980 const IMPLICIT_SELF_MASK: u8 = 0b111;
3981
3982 /// Bitflag for a trailing C-style variadic argument.
3983 const C_VARIADIC_FLAG: u8 = 1 << 3;
3984
3985 /// Bitflag for lifetime elision.
3986 const LIFETIME_ELISION_ALLOWED_FLAG: u8 = 1 << 4;
3987
3988 /// Create a new FnDeclKind with no implicit self, no lifetime elision, and no C-style variadic argument.
3989 /// To modify these flags, use the `set_*` methods, for readability.
3990 // FIXME: use Default instead when that trait is const stable.
3991 pub const fn default() -> Self {
3992 Self { flags: 0 }
3993 .set_implicit_self(ImplicitSelfKind::None)
3994 .set_lifetime_elision_allowed(false)
3995 .set_c_variadic(false)
3996 }
3997
3998 /// Set the implicit self kind.
3999 #[must_use = "this method does not modify the receiver"]
4000 pub const fn set_implicit_self(mut self, implicit_self: ImplicitSelfKind) -> Self {
4001 self.flags &= !Self::IMPLICIT_SELF_MASK;
4002
4003 match implicit_self {
4004 ImplicitSelfKind::None => self.flags |= 0,
4005 ImplicitSelfKind::Imm => self.flags |= 1,
4006 ImplicitSelfKind::Mut => self.flags |= 2,
4007 ImplicitSelfKind::RefImm => self.flags |= 3,
4008 ImplicitSelfKind::RefMut => self.flags |= 4,
4009 }
4010
4011 self
4012 }
4013
4014 /// Set the C-style variadic argument flag.
4015 #[must_use = "this method does not modify the receiver"]
4016 pub const fn set_c_variadic(mut self, c_variadic: bool) -> Self {
4017 if c_variadic {
4018 self.flags |= Self::C_VARIADIC_FLAG;
4019 } else {
4020 self.flags &= !Self::C_VARIADIC_FLAG;
4021 }
4022
4023 self
4024 }
4025
4026 /// Set the lifetime elision allowed flag.
4027 #[must_use = "this method does not modify the receiver"]
4028 pub const fn set_lifetime_elision_allowed(mut self, allowed: bool) -> Self {
4029 if allowed {
4030 self.flags |= Self::LIFETIME_ELISION_ALLOWED_FLAG;
4031 } else {
4032 self.flags &= !Self::LIFETIME_ELISION_ALLOWED_FLAG;
4033 }
4034
4035 self
4036 }
4037
4038 /// Get the implicit self kind.
4039 pub const fn implicit_self(self) -> ImplicitSelfKind {
4040 match self.flags & Self::IMPLICIT_SELF_MASK {
4041 0 => ImplicitSelfKind::None,
4042 1 => ImplicitSelfKind::Imm,
4043 2 => ImplicitSelfKind::Mut,
4044 3 => ImplicitSelfKind::RefImm,
4045 4 => ImplicitSelfKind::RefMut,
4046 _ => unreachable!(),
4047 }
4048 }
4049
4050 /// Do the function arguments end with a C-style variadic argument?
4051 pub const fn c_variadic(self) -> bool {
4052 self.flags & Self::C_VARIADIC_FLAG != 0
4053 }
4054
4055 /// Is lifetime elision allowed?
4056 pub const fn lifetime_elision_allowed(self) -> bool {
4057 self.flags & Self::LIFETIME_ELISION_ALLOWED_FLAG != 0
4058 }
4059}
4060
4061/// Represents the header (not the body) of a function declaration.
4062#[derive(Debug, Clone, Copy, StableHash)]
4063pub struct FnDecl<'hir> {
4064 /// The types of the function's parameters.
4065 ///
4066 /// Additional argument data is stored in the function's [body](Body::params).
4067 pub inputs: &'hir [Ty<'hir>],
4068 pub output: FnRetTy<'hir>,
4069 /// The packed function declaration attributes.
4070 pub fn_decl_kind: FnDeclFlags,
4071}
4072
4073impl<'hir> FnDecl<'hir> {
4074 pub fn opt_delegation_sig_id(&self) -> Option<DefId> {
4075 if let FnRetTy::Return(ty) = self.output
4076 && let TyKind::InferDelegation(InferDelegation::Sig(sig_id, _)) = ty.kind
4077 {
4078 return Some(sig_id);
4079 }
4080 None
4081 }
4082
4083 pub fn opt_delegation_generics(&self) -> Option<&'hir DelegationGenerics> {
4084 if let FnRetTy::Return(ty) = self.output
4085 && let TyKind::InferDelegation(InferDelegation::Sig(_, kind)) = ty.kind
4086 && let InferDelegationSig::Output(generics) = kind
4087 {
4088 return Some(generics);
4089 }
4090
4091 None
4092 }
4093
4094 pub fn implicit_self(&self) -> ImplicitSelfKind {
4095 self.fn_decl_kind.implicit_self()
4096 }
4097
4098 pub fn c_variadic(&self) -> bool {
4099 self.fn_decl_kind.c_variadic()
4100 }
4101
4102 pub fn lifetime_elision_allowed(&self) -> bool {
4103 self.fn_decl_kind.lifetime_elision_allowed()
4104 }
4105
4106 pub fn dummy(span: Span) -> Self {
4107 Self {
4108 inputs: &[],
4109 output: FnRetTy::DefaultReturn(span),
4110 fn_decl_kind: FnDeclFlags::default().set_lifetime_elision_allowed(true),
4111 }
4112 }
4113}
4114
4115/// Represents what type of implicit self a function has, if any.
4116#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, StableHash)]
4117pub enum ImplicitSelfKind {
4118 /// Represents a `fn x(self);`.
4119 Imm,
4120 /// Represents a `fn x(mut self);`.
4121 Mut,
4122 /// Represents a `fn x(&self);`.
4123 RefImm,
4124 /// Represents a `fn x(&mut self);`.
4125 RefMut,
4126 /// Represents when a function does not have a self argument or
4127 /// when a function has a `self: X` argument.
4128 None,
4129}
4130
4131impl ImplicitSelfKind {
4132 /// Does this represent an implicit self?
4133 pub fn has_implicit_self(&self) -> bool {
4134 !matches!(*self, ImplicitSelfKind::None)
4135 }
4136}
4137
4138#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, StableHash)]
4139pub enum IsAsync {
4140 Async(Span),
4141 NotAsync,
4142}
4143
4144impl IsAsync {
4145 pub fn is_async(self) -> bool {
4146 matches!(self, IsAsync::Async(_))
4147 }
4148}
4149
4150#[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, StableHash)]
4151#[derive(Default)]
4152pub enum Defaultness {
4153 Default {
4154 has_value: bool,
4155 },
4156 #[default]
4157 Final,
4158}
4159
4160impl Defaultness {
4161 pub fn has_value(&self) -> bool {
4162 match *self {
4163 Defaultness::Default { has_value } => has_value,
4164 Defaultness::Final => true,
4165 }
4166 }
4167
4168 pub fn is_final(&self) -> bool {
4169 *self == Defaultness::Final
4170 }
4171
4172 pub fn is_default(&self) -> bool {
4173 matches!(*self, Defaultness::Default { .. })
4174 }
4175}
4176
4177#[derive(Debug, Clone, Copy, StableHash)]
4178pub enum FnRetTy<'hir> {
4179 /// Return type is not specified.
4180 ///
4181 /// Functions default to `()` and
4182 /// closures default to inference. Span points to where return
4183 /// type would be inserted.
4184 DefaultReturn(Span),
4185 /// Everything else.
4186 Return(&'hir Ty<'hir>),
4187}
4188
4189impl<'hir> FnRetTy<'hir> {
4190 #[inline]
4191 pub fn span(&self) -> Span {
4192 match *self {
4193 Self::DefaultReturn(span) => span,
4194 Self::Return(ref ty) => ty.span,
4195 }
4196 }
4197
4198 pub fn is_suggestable_infer_ty(&self) -> Option<&'hir Ty<'hir>> {
4199 if let Self::Return(ty) = self
4200 && ty.is_suggestable_infer_ty()
4201 {
4202 return Some(*ty);
4203 }
4204 None
4205 }
4206}
4207
4208/// Represents `for<...>` binder before a closure
4209#[derive(Copy, Clone, Debug, StableHash)]
4210pub enum ClosureBinder {
4211 /// Binder is not specified.
4212 Default,
4213 /// Binder is specified.
4214 ///
4215 /// Span points to the whole `for<...>`.
4216 For { span: Span },
4217}
4218
4219#[derive(Debug, Clone, Copy, StableHash)]
4220pub struct Mod<'hir> {
4221 pub spans: ModSpans,
4222 pub item_ids: &'hir [ItemId],
4223}
4224
4225#[derive(Copy, Clone, Debug, StableHash)]
4226pub struct ModSpans {
4227 /// A span from the first token past `{` to the last token until `}`.
4228 /// For `mod foo;`, the inner span ranges from the first token
4229 /// to the last token in the external file.
4230 pub inner_span: Span,
4231 pub inject_use_span: Span,
4232}
4233
4234#[derive(Debug, Clone, Copy, StableHash)]
4235pub struct EnumDef<'hir> {
4236 pub variants: &'hir [Variant<'hir>],
4237}
4238
4239#[derive(Debug, Clone, Copy, StableHash)]
4240pub struct Variant<'hir> {
4241 /// Name of the variant.
4242 pub ident: Ident,
4243 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
4244 #[stable_hash(ignore)]
4245 pub hir_id: HirId,
4246 pub def_id: LocalDefId,
4247 /// Fields and constructor id of the variant.
4248 pub data: VariantData<'hir>,
4249 /// Explicit discriminant (e.g., `Foo = 1`).
4250 pub disr_expr: Option<&'hir AnonConst>,
4251 /// Span
4252 pub span: Span,
4253}
4254
4255#[derive(Copy, Clone, PartialEq, Debug, StableHash)]
4256pub enum UseKind {
4257 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
4258 /// Also produced for each element of a list `use`, e.g.
4259 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
4260 ///
4261 /// The identifier is the name defined by the import. E.g. for `use
4262 /// foo::bar` it is `bar`, for `use foo::bar as baz` it is `baz`.
4263 Single(Ident),
4264
4265 /// Glob import, e.g., `use foo::*`.
4266 Glob,
4267
4268 /// Degenerate list import, e.g., `use foo::{a, b}` produces
4269 /// an additional `use foo::{}` for performing checks such as
4270 /// unstable feature gating. May be removed in the future.
4271 ListStem,
4272}
4273
4274/// References to traits in impls.
4275///
4276/// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
4277/// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
4278/// trait being referred to but just a unique `HirId` that serves as a key
4279/// within the resolution map.
4280#[derive(Clone, Debug, Copy, StableHash)]
4281pub struct TraitRef<'hir> {
4282 pub path: &'hir Path<'hir>,
4283 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
4284 #[stable_hash(ignore)]
4285 pub hir_ref_id: HirId,
4286}
4287
4288impl TraitRef<'_> {
4289 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
4290 pub fn trait_def_id(&self) -> Option<DefId> {
4291 match self.path.res {
4292 Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
4293 Res::Err => None,
4294 res => panic!("{res:?} did not resolve to a trait or trait alias"),
4295 }
4296 }
4297}
4298
4299#[derive(Clone, Debug, Copy, StableHash)]
4300pub struct PolyTraitRef<'hir> {
4301 /// The `'a` in `for<'a> Foo<&'a T>`.
4302 pub bound_generic_params: &'hir [GenericParam<'hir>],
4303
4304 /// The constness and polarity of the trait ref.
4305 ///
4306 /// The `async` modifier is lowered directly into a different trait for now.
4307 pub modifiers: TraitBoundModifiers,
4308
4309 /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
4310 pub trait_ref: TraitRef<'hir>,
4311
4312 pub span: Span,
4313}
4314
4315#[derive(Debug, Clone, Copy, StableHash)]
4316pub struct FieldDef<'hir> {
4317 pub span: Span,
4318 pub vis_span: Span,
4319 pub ident: Ident,
4320 #[stable_hash(ignore)]
4321 pub hir_id: HirId,
4322 pub def_id: LocalDefId,
4323 pub ty: &'hir Ty<'hir>,
4324 pub safety: Safety,
4325 pub default: Option<&'hir AnonConst>,
4326}
4327
4328impl FieldDef<'_> {
4329 // Still necessary in couple of places
4330 pub fn is_positional(&self) -> bool {
4331 self.ident.as_str().as_bytes()[0].is_ascii_digit()
4332 }
4333}
4334
4335/// Fields and constructor IDs of enum variants and structs.
4336#[derive(Debug, Clone, Copy, StableHash)]
4337pub enum VariantData<'hir> {
4338 /// A struct variant.
4339 ///
4340 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
4341 Struct { fields: &'hir [FieldDef<'hir>], recovered: ast::Recovered },
4342 /// A tuple variant.
4343 ///
4344 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
4345 Tuple(&'hir [FieldDef<'hir>], #[stable_hash(ignore)] HirId, LocalDefId),
4346 /// A unit variant.
4347 ///
4348 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
4349 Unit(#[stable_hash(ignore)] HirId, LocalDefId),
4350}
4351
4352impl<'hir> VariantData<'hir> {
4353 /// Return the fields of this variant.
4354 pub fn fields(&self) -> &'hir [FieldDef<'hir>] {
4355 match *self {
4356 VariantData::Struct { fields, .. } | VariantData::Tuple(fields, ..) => fields,
4357 _ => &[],
4358 }
4359 }
4360
4361 pub fn ctor(&self) -> Option<(CtorKind, HirId, LocalDefId)> {
4362 match *self {
4363 VariantData::Tuple(_, hir_id, def_id) => Some((CtorKind::Fn, hir_id, def_id)),
4364 VariantData::Unit(hir_id, def_id) => Some((CtorKind::Const, hir_id, def_id)),
4365 VariantData::Struct { .. } => None,
4366 }
4367 }
4368
4369 #[inline]
4370 pub fn ctor_kind(&self) -> Option<CtorKind> {
4371 self.ctor().map(|(kind, ..)| kind)
4372 }
4373
4374 /// Return the `HirId` of this variant's constructor, if it has one.
4375 #[inline]
4376 pub fn ctor_hir_id(&self) -> Option<HirId> {
4377 self.ctor().map(|(_, hir_id, _)| hir_id)
4378 }
4379
4380 /// Return the `LocalDefId` of this variant's constructor, if it has one.
4381 #[inline]
4382 pub fn ctor_def_id(&self) -> Option<LocalDefId> {
4383 self.ctor().map(|(.., def_id)| def_id)
4384 }
4385}
4386
4387// The bodies for items are stored "out of line", in a separate
4388// hashmap in the `Crate`. Here we just record the hir-id of the item
4389// so it can fetched later.
4390#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, Hash, StableHash)]
4391pub struct ItemId {
4392 pub owner_id: OwnerId,
4393}
4394
4395impl ItemId {
4396 #[inline]
4397 pub fn hir_id(&self) -> HirId {
4398 // Items are always HIR owners.
4399 HirId::make_owner(self.owner_id.def_id)
4400 }
4401}
4402
4403/// An item
4404///
4405/// For more details, see the [rust lang reference].
4406/// Note that the reference does not document nightly-only features.
4407/// There may be also slight differences in the names and representation of AST nodes between
4408/// the compiler and the reference.
4409///
4410/// [rust lang reference]: https://doc.rust-lang.org/reference/items.html
4411#[derive(Debug, Clone, Copy, StableHash)]
4412pub struct Item<'hir> {
4413 pub owner_id: OwnerId,
4414 pub kind: ItemKind<'hir>,
4415 pub span: Span,
4416 pub vis_span: Span,
4417 pub has_delayed_lints: bool,
4418 /// hint to speed up collection: true if the item is a static or function and has
4419 /// either an `EiiImpls` or `EiiExternTarget` attribute
4420 pub eii: bool,
4421}
4422
4423impl<'hir> Item<'hir> {
4424 #[inline]
4425 pub fn hir_id(&self) -> HirId {
4426 // Items are always HIR owners.
4427 HirId::make_owner(self.owner_id.def_id)
4428 }
4429
4430 pub fn item_id(&self) -> ItemId {
4431 ItemId { owner_id: self.owner_id }
4432 }
4433
4434 /// Check if this is an [`ItemKind::Enum`], [`ItemKind::Struct`] or
4435 /// [`ItemKind::Union`].
4436 pub fn is_adt(&self) -> bool {
4437 matches!(self.kind, ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..))
4438 }
4439
4440 /// Check if this is an [`ItemKind::Struct`] or [`ItemKind::Union`].
4441 pub fn is_struct_or_union(&self) -> bool {
4442 matches!(self.kind, ItemKind::Struct(..) | ItemKind::Union(..))
4443 }
4444
4445 expect_methods_self_kind! {
4446 expect_extern_crate, (Option<Symbol>, Ident),
4447 ItemKind::ExternCrate(s, ident), (*s, *ident);
4448
4449 expect_use, (&'hir UsePath<'hir>, UseKind), ItemKind::Use(p, uk), (p, *uk);
4450
4451 expect_static, (Mutability, Ident, &'hir Ty<'hir>, BodyId),
4452 ItemKind::Static(mutbl, ident, ty, body), (*mutbl, *ident, ty, *body);
4453
4454 expect_const, (Ident, &'hir Generics<'hir>, &'hir Ty<'hir>, ConstItemRhs<'hir>),
4455 ItemKind::Const(ident, generics, ty, rhs), (*ident, generics, ty, *rhs);
4456
4457 expect_fn, (Ident, &FnSig<'hir>, &'hir Generics<'hir>, BodyId),
4458 ItemKind::Fn { ident, sig, generics, body, .. }, (*ident, sig, generics, *body);
4459
4460 expect_macro, (Ident, &ast::MacroDef, MacroKinds),
4461 ItemKind::Macro(ident, def, mk), (*ident, def, *mk);
4462
4463 expect_mod, (Ident, &'hir Mod<'hir>), ItemKind::Mod(ident, m), (*ident, m);
4464
4465 expect_foreign_mod, (ExternAbi, &'hir [ForeignItemId]),
4466 ItemKind::ForeignMod { abi, items }, (*abi, items);
4467
4468 expect_global_asm, &'hir InlineAsm<'hir>, ItemKind::GlobalAsm { asm, .. }, asm;
4469
4470 expect_ty_alias, (Ident, &'hir Generics<'hir>, &'hir Ty<'hir>),
4471 ItemKind::TyAlias(ident, generics, ty), (*ident, generics, ty);
4472
4473 expect_enum, (Ident, &'hir Generics<'hir>, &EnumDef<'hir>),
4474 ItemKind::Enum(ident, generics, def), (*ident, generics, def);
4475
4476 expect_struct, (Ident, &'hir Generics<'hir>, &VariantData<'hir>),
4477 ItemKind::Struct(ident, generics, data), (*ident, generics, data);
4478
4479 expect_union, (Ident, &'hir Generics<'hir>, &VariantData<'hir>),
4480 ItemKind::Union(ident, generics, data), (*ident, generics, data);
4481
4482 expect_trait,
4483 (
4484 &'hir ImplRestriction<'hir>,
4485 Constness,
4486 IsAuto,
4487 Safety,
4488 Ident,
4489 &'hir Generics<'hir>,
4490 GenericBounds<'hir>,
4491 &'hir [TraitItemId]
4492 ),
4493 ItemKind::Trait { impl_restriction, constness, is_auto, safety, ident, generics, bounds, items },
4494 (impl_restriction, *constness, *is_auto, *safety, *ident, generics, bounds, items);
4495
4496 expect_trait_alias, (Constness, Ident, &'hir Generics<'hir>, GenericBounds<'hir>),
4497 ItemKind::TraitAlias(constness, ident, generics, bounds), (*constness, *ident, generics, bounds);
4498
4499 expect_impl, &Impl<'hir>, ItemKind::Impl(imp), imp;
4500 }
4501}
4502
4503#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
4504#[derive(Encodable, Decodable, StableHash, Default)]
4505pub enum Safety {
4506 /// This is the default variant, because the compiler messing up
4507 /// metadata encoding and failing to encode a `Safe` flag, means
4508 /// downstream crates think a thing is `Unsafe` instead of silently
4509 /// treating an unsafe thing as safe.
4510 #[default]
4511 Unsafe,
4512 Safe,
4513}
4514
4515impl Safety {
4516 pub fn prefix_str(self) -> &'static str {
4517 match self {
4518 Self::Unsafe => "unsafe ",
4519 Self::Safe => "",
4520 }
4521 }
4522
4523 #[inline]
4524 pub fn is_unsafe(self) -> bool {
4525 !self.is_safe()
4526 }
4527
4528 #[inline]
4529 pub fn is_safe(self) -> bool {
4530 match self {
4531 Self::Unsafe => false,
4532 Self::Safe => true,
4533 }
4534 }
4535}
4536
4537impl fmt::Display for Safety {
4538 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4539 f.write_str(match *self {
4540 Self::Unsafe => "unsafe",
4541 Self::Safe => "safe",
4542 })
4543 }
4544}
4545
4546#[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, StableHash)]
4547#[derive(Default)]
4548pub enum Constness {
4549 #[default]
4550 Const,
4551 NotConst,
4552}
4553
4554impl fmt::Display for Constness {
4555 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4556 f.write_str(match *self {
4557 Self::Const => "const",
4558 Self::NotConst => "non-const",
4559 })
4560 }
4561}
4562
4563#[derive(Debug, Clone, Copy, StableHash)]
4564pub struct ImplRestriction<'hir> {
4565 pub kind: RestrictionKind<'hir>,
4566 pub span: Span,
4567}
4568
4569#[derive(Debug, Clone, Copy, StableHash)]
4570pub enum RestrictionKind<'hir> {
4571 /// The restriction does not affect the item.
4572 Unrestricted,
4573 /// The restriction only applies outside of this path.
4574 Restricted(&'hir Path<'hir, DefId>),
4575}
4576
4577/// The actual safety specified in syntax. We may treat
4578/// its safety different within the type system to create a
4579/// "sound by default" system that needs checking this enum
4580/// explicitly to allow unsafe operations.
4581#[derive(Copy, Clone, Debug, StableHash, PartialEq, Eq)]
4582pub enum HeaderSafety {
4583 /// A safe function annotated with `#[target_features]`.
4584 /// The type system treats this function as an unsafe function,
4585 /// but safety checking will check this enum to treat it as safe
4586 /// and allowing calling other safe target feature functions with
4587 /// the same features without requiring an additional unsafe block.
4588 SafeTargetFeatures,
4589 Normal(Safety),
4590}
4591
4592impl From<Safety> for HeaderSafety {
4593 fn from(v: Safety) -> Self {
4594 Self::Normal(v)
4595 }
4596}
4597
4598#[derive(Copy, Clone, Debug, StableHash)]
4599pub struct FnHeader {
4600 pub safety: HeaderSafety,
4601 pub constness: Constness,
4602 pub asyncness: IsAsync,
4603 pub abi: ExternAbi,
4604}
4605
4606impl FnHeader {
4607 pub fn is_async(&self) -> bool {
4608 matches!(self.asyncness, IsAsync::Async(_))
4609 }
4610
4611 pub fn is_const(&self) -> bool {
4612 matches!(self.constness, Constness::Const)
4613 }
4614
4615 pub fn is_unsafe(&self) -> bool {
4616 self.safety().is_unsafe()
4617 }
4618
4619 pub fn is_safe(&self) -> bool {
4620 self.safety().is_safe()
4621 }
4622
4623 pub fn safety(&self) -> Safety {
4624 match self.safety {
4625 HeaderSafety::SafeTargetFeatures => Safety::Unsafe,
4626 HeaderSafety::Normal(safety) => safety,
4627 }
4628 }
4629}
4630
4631#[derive(Debug, Clone, Copy, StableHash)]
4632pub enum ItemKind<'hir> {
4633 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
4634 ///
4635 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
4636 ExternCrate(Option<Symbol>, Ident),
4637
4638 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
4639 ///
4640 /// or just
4641 ///
4642 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
4643 Use(&'hir UsePath<'hir>, UseKind),
4644
4645 /// A `static` item.
4646 Static(Mutability, Ident, &'hir Ty<'hir>, BodyId),
4647 /// A `const` item.
4648 Const(Ident, &'hir Generics<'hir>, &'hir Ty<'hir>, ConstItemRhs<'hir>),
4649 /// A function declaration.
4650 Fn {
4651 sig: FnSig<'hir>,
4652 ident: Ident,
4653 generics: &'hir Generics<'hir>,
4654 body: BodyId,
4655 /// Whether this function actually has a body.
4656 /// For functions without a body, `body` is synthesized (to avoid ICEs all over the
4657 /// compiler), but that code should never be translated.
4658 has_body: bool,
4659 },
4660 /// A MBE macro definition (`macro_rules!` or `macro`).
4661 Macro(Ident, &'hir ast::MacroDef, MacroKinds),
4662 /// A module.
4663 Mod(Ident, &'hir Mod<'hir>),
4664 /// An external module, e.g. `extern { .. }`.
4665 ForeignMod { abi: ExternAbi, items: &'hir [ForeignItemId] },
4666 /// Module-level inline assembly (from `global_asm!`).
4667 GlobalAsm {
4668 asm: &'hir InlineAsm<'hir>,
4669 /// A fake body which stores typeck results for the global asm's sym_fn
4670 /// operands, which are represented as path expressions. This body contains
4671 /// a single [`ExprKind::InlineAsm`] which points to the asm in the field
4672 /// above, and which is typechecked like a inline asm expr just for the
4673 /// typeck results.
4674 fake_body: BodyId,
4675 },
4676 /// A type alias, e.g., `type Foo = Bar<u8>`.
4677 TyAlias(Ident, &'hir Generics<'hir>, &'hir Ty<'hir>),
4678 /// An enum definition, e.g., `enum Foo<A, B> { C<A>, D<B> }`.
4679 Enum(Ident, &'hir Generics<'hir>, EnumDef<'hir>),
4680 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
4681 Struct(Ident, &'hir Generics<'hir>, VariantData<'hir>),
4682 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
4683 Union(Ident, &'hir Generics<'hir>, VariantData<'hir>),
4684 /// A trait definition.
4685 Trait {
4686 impl_restriction: &'hir ImplRestriction<'hir>,
4687 constness: Constness,
4688 is_auto: IsAuto,
4689 safety: Safety,
4690 ident: Ident,
4691 generics: &'hir Generics<'hir>,
4692 bounds: GenericBounds<'hir>,
4693 items: &'hir [TraitItemId],
4694 },
4695 /// A trait alias.
4696 TraitAlias(Constness, Ident, &'hir Generics<'hir>, GenericBounds<'hir>),
4697
4698 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
4699 Impl(Impl<'hir>),
4700}
4701
4702/// Represents an impl block declaration.
4703///
4704/// E.g., `impl $Type { .. }` or `impl $Trait for $Type { .. }`
4705/// Refer to [`ImplItem`] for an associated item within an impl block.
4706#[derive(Debug, Clone, Copy, StableHash)]
4707pub struct Impl<'hir> {
4708 pub generics: &'hir Generics<'hir>,
4709 pub of_trait: Option<&'hir TraitImplHeader<'hir>>,
4710 pub self_ty: &'hir Ty<'hir>,
4711 pub items: &'hir [ImplItemId],
4712 pub constness: Constness,
4713}
4714
4715#[derive(Debug, Clone, Copy, StableHash)]
4716pub struct TraitImplHeader<'hir> {
4717 pub safety: Safety,
4718 pub polarity: ImplPolarity,
4719 pub defaultness: Defaultness,
4720 // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata
4721 // decoding as `Span`s cannot be decoded when a `Session` is not available.
4722 pub defaultness_span: Option<Span>,
4723 pub trait_ref: TraitRef<'hir>,
4724}
4725
4726impl ItemKind<'_> {
4727 pub fn ident(&self) -> Option<Ident> {
4728 match *self {
4729 ItemKind::ExternCrate(_, ident)
4730 | ItemKind::Use(_, UseKind::Single(ident))
4731 | ItemKind::Static(_, ident, ..)
4732 | ItemKind::Const(ident, ..)
4733 | ItemKind::Fn { ident, .. }
4734 | ItemKind::Macro(ident, ..)
4735 | ItemKind::Mod(ident, ..)
4736 | ItemKind::TyAlias(ident, ..)
4737 | ItemKind::Enum(ident, ..)
4738 | ItemKind::Struct(ident, ..)
4739 | ItemKind::Union(ident, ..)
4740 | ItemKind::Trait { ident, .. }
4741 | ItemKind::TraitAlias(_, ident, ..) => Some(ident),
4742
4743 ItemKind::Use(_, UseKind::Glob | UseKind::ListStem)
4744 | ItemKind::ForeignMod { .. }
4745 | ItemKind::GlobalAsm { .. }
4746 | ItemKind::Impl(_) => None,
4747 }
4748 }
4749
4750 pub fn generics(&self) -> Option<&Generics<'_>> {
4751 Some(match self {
4752 ItemKind::Fn { generics, .. }
4753 | ItemKind::TyAlias(_, generics, _)
4754 | ItemKind::Const(_, generics, _, _)
4755 | ItemKind::Enum(_, generics, _)
4756 | ItemKind::Struct(_, generics, _)
4757 | ItemKind::Union(_, generics, _)
4758 | ItemKind::Trait { generics, .. }
4759 | ItemKind::TraitAlias(_, _, generics, _)
4760 | ItemKind::Impl(Impl { generics, .. }) => generics,
4761 _ => return None,
4762 })
4763 }
4764
4765 pub fn recovered(&self) -> bool {
4766 match self {
4767 ItemKind::Struct(
4768 _,
4769 _,
4770 VariantData::Struct { recovered: ast::Recovered::Yes(_), .. },
4771 ) => true,
4772 ItemKind::Union(
4773 _,
4774 _,
4775 VariantData::Struct { recovered: ast::Recovered::Yes(_), .. },
4776 ) => true,
4777 ItemKind::Enum(_, _, def) => def.variants.iter().any(|v| match v.data {
4778 VariantData::Struct { recovered: ast::Recovered::Yes(_), .. } => true,
4779 _ => false,
4780 }),
4781 _ => false,
4782 }
4783 }
4784}
4785
4786// The bodies for items are stored "out of line", in a separate
4787// hashmap in the `Crate`. Here we just record the hir-id of the item
4788// so it can fetched later.
4789#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, StableHash)]
4790pub struct ForeignItemId {
4791 pub owner_id: OwnerId,
4792}
4793
4794impl ForeignItemId {
4795 #[inline]
4796 pub fn hir_id(&self) -> HirId {
4797 // Items are always HIR owners.
4798 HirId::make_owner(self.owner_id.def_id)
4799 }
4800}
4801
4802#[derive(Debug, Clone, Copy, StableHash)]
4803pub struct ForeignItem<'hir> {
4804 pub ident: Ident,
4805 pub kind: ForeignItemKind<'hir>,
4806 pub owner_id: OwnerId,
4807 pub span: Span,
4808 pub vis_span: Span,
4809 pub has_delayed_lints: bool,
4810}
4811
4812impl ForeignItem<'_> {
4813 #[inline]
4814 pub fn hir_id(&self) -> HirId {
4815 // Items are always HIR owners.
4816 HirId::make_owner(self.owner_id.def_id)
4817 }
4818
4819 pub fn foreign_item_id(&self) -> ForeignItemId {
4820 ForeignItemId { owner_id: self.owner_id }
4821 }
4822}
4823
4824/// An item within an `extern` block.
4825#[derive(Debug, Clone, Copy, StableHash)]
4826pub enum ForeignItemKind<'hir> {
4827 /// A foreign function.
4828 ///
4829 /// All argument idents are actually always present (i.e. `Some`), but
4830 /// `&[Option<Ident>]` is used because of code paths shared with `TraitFn`
4831 /// and `FnPtrTy`. The sharing is due to all of these cases not allowing
4832 /// arbitrary patterns for parameters.
4833 Fn(FnSig<'hir>, &'hir [Option<Ident>], &'hir Generics<'hir>),
4834 /// A foreign static item (`static ext: u8`).
4835 Static(&'hir Ty<'hir>, Mutability, Safety),
4836 /// A foreign type.
4837 Type,
4838}
4839
4840/// A variable captured by a closure.
4841#[derive(Debug, Copy, Clone, StableHash)]
4842pub struct Upvar {
4843 /// First span where it is accessed (there can be multiple).
4844 pub span: Span,
4845}
4846
4847// The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
4848// has length > 0 if the trait is found through an chain of imports, starting with the
4849// import/use statement in the scope where the trait is used.
4850#[derive(Debug, Clone, Copy, StableHash)]
4851pub struct TraitCandidate<'hir> {
4852 pub def_id: DefId,
4853 pub import_ids: &'hir [LocalDefId],
4854 // Indicates whether this trait candidate is ambiguously glob imported
4855 // in it's scope. Related to the AMBIGUOUS_GLOB_IMPORTED_TRAITS lint.
4856 // If this is set to true and the trait is used as a result of method lookup, this
4857 // lint is thrown.
4858 pub lint_ambiguous: bool,
4859}
4860
4861#[derive(Copy, Clone, Debug, StableHash)]
4862pub enum OwnerNode<'hir> {
4863 Item(&'hir Item<'hir>),
4864 ForeignItem(&'hir ForeignItem<'hir>),
4865 TraitItem(&'hir TraitItem<'hir>),
4866 ImplItem(&'hir ImplItem<'hir>),
4867 Crate(&'hir Mod<'hir>),
4868 Synthetic,
4869}
4870
4871impl<'hir> OwnerNode<'hir> {
4872 pub fn span(&self) -> Span {
4873 match self {
4874 OwnerNode::Item(Item { span, .. })
4875 | OwnerNode::ForeignItem(ForeignItem { span, .. })
4876 | OwnerNode::ImplItem(ImplItem { span, .. })
4877 | OwnerNode::TraitItem(TraitItem { span, .. }) => *span,
4878 OwnerNode::Crate(Mod { spans: ModSpans { inner_span, .. }, .. }) => *inner_span,
4879 OwnerNode::Synthetic => unreachable!(),
4880 }
4881 }
4882
4883 pub fn fn_sig(self) -> Option<&'hir FnSig<'hir>> {
4884 match self {
4885 OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4886 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4887 | OwnerNode::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4888 | OwnerNode::ForeignItem(ForeignItem {
4889 kind: ForeignItemKind::Fn(fn_sig, _, _), ..
4890 }) => Some(fn_sig),
4891 _ => None,
4892 }
4893 }
4894
4895 pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
4896 match self {
4897 OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
4898 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
4899 | OwnerNode::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
4900 | OwnerNode::ForeignItem(ForeignItem {
4901 kind: ForeignItemKind::Fn(fn_sig, _, _), ..
4902 }) => Some(fn_sig.decl),
4903 _ => None,
4904 }
4905 }
4906
4907 pub fn body_id(&self) -> Option<BodyId> {
4908 match self {
4909 OwnerNode::Item(Item {
4910 kind:
4911 ItemKind::Static(_, _, _, body)
4912 | ItemKind::Const(.., ConstItemRhs::Body(body))
4913 | ItemKind::Fn { body, .. },
4914 ..
4915 })
4916 | OwnerNode::TraitItem(TraitItem {
4917 kind:
4918 TraitItemKind::Fn(_, TraitFn::Provided(body))
4919 | TraitItemKind::Const(_, Some(ConstItemRhs::Body(body)), _),
4920 ..
4921 })
4922 | OwnerNode::ImplItem(ImplItem {
4923 kind: ImplItemKind::Fn(_, body) | ImplItemKind::Const(_, ConstItemRhs::Body(body)),
4924 ..
4925 }) => Some(*body),
4926 _ => None,
4927 }
4928 }
4929
4930 pub fn generics(self) -> Option<&'hir Generics<'hir>> {
4931 Node::generics(self.into())
4932 }
4933
4934 pub fn def_id(self) -> OwnerId {
4935 match self {
4936 OwnerNode::Item(Item { owner_id, .. })
4937 | OwnerNode::TraitItem(TraitItem { owner_id, .. })
4938 | OwnerNode::ImplItem(ImplItem { owner_id, .. })
4939 | OwnerNode::ForeignItem(ForeignItem { owner_id, .. }) => *owner_id,
4940 OwnerNode::Crate(..) => crate::CRATE_HIR_ID.owner,
4941 OwnerNode::Synthetic => unreachable!(),
4942 }
4943 }
4944
4945 /// Check if node is an impl block.
4946 pub fn is_impl_block(&self) -> bool {
4947 matches!(self, OwnerNode::Item(Item { kind: ItemKind::Impl(_), .. }))
4948 }
4949
4950 expect_methods_self! {
4951 expect_item, &'hir Item<'hir>, OwnerNode::Item(n), n;
4952 expect_foreign_item, &'hir ForeignItem<'hir>, OwnerNode::ForeignItem(n), n;
4953 expect_impl_item, &'hir ImplItem<'hir>, OwnerNode::ImplItem(n), n;
4954 expect_trait_item, &'hir TraitItem<'hir>, OwnerNode::TraitItem(n), n;
4955 }
4956}
4957
4958impl<'hir> From<&'hir Item<'hir>> for OwnerNode<'hir> {
4959 fn from(val: &'hir Item<'hir>) -> Self {
4960 OwnerNode::Item(val)
4961 }
4962}
4963
4964impl<'hir> From<&'hir ForeignItem<'hir>> for OwnerNode<'hir> {
4965 fn from(val: &'hir ForeignItem<'hir>) -> Self {
4966 OwnerNode::ForeignItem(val)
4967 }
4968}
4969
4970impl<'hir> From<&'hir ImplItem<'hir>> for OwnerNode<'hir> {
4971 fn from(val: &'hir ImplItem<'hir>) -> Self {
4972 OwnerNode::ImplItem(val)
4973 }
4974}
4975
4976impl<'hir> From<&'hir TraitItem<'hir>> for OwnerNode<'hir> {
4977 fn from(val: &'hir TraitItem<'hir>) -> Self {
4978 OwnerNode::TraitItem(val)
4979 }
4980}
4981
4982impl<'hir> From<OwnerNode<'hir>> for Node<'hir> {
4983 fn from(val: OwnerNode<'hir>) -> Self {
4984 match val {
4985 OwnerNode::Item(n) => Node::Item(n),
4986 OwnerNode::ForeignItem(n) => Node::ForeignItem(n),
4987 OwnerNode::ImplItem(n) => Node::ImplItem(n),
4988 OwnerNode::TraitItem(n) => Node::TraitItem(n),
4989 OwnerNode::Crate(n) => Node::Crate(n),
4990 OwnerNode::Synthetic => Node::Synthetic,
4991 }
4992 }
4993}
4994
4995#[derive(Copy, Clone, Debug, StableHash)]
4996pub enum Node<'hir> {
4997 Param(&'hir Param<'hir>),
4998 Item(&'hir Item<'hir>),
4999 ForeignItem(&'hir ForeignItem<'hir>),
5000 TraitItem(&'hir TraitItem<'hir>),
5001 ImplItem(&'hir ImplItem<'hir>),
5002 Variant(&'hir Variant<'hir>),
5003 Field(&'hir FieldDef<'hir>),
5004 AnonConst(&'hir AnonConst),
5005 ConstBlock(&'hir ConstBlock),
5006 ConstArg(&'hir ConstArg<'hir>),
5007 Expr(&'hir Expr<'hir>),
5008 ExprField(&'hir ExprField<'hir>),
5009 ConstArgExprField(&'hir ConstArgExprField<'hir>),
5010 Stmt(&'hir Stmt<'hir>),
5011 PathSegment(&'hir PathSegment<'hir>),
5012 Ty(&'hir Ty<'hir>),
5013 AssocItemConstraint(&'hir AssocItemConstraint<'hir>),
5014 TraitRef(&'hir TraitRef<'hir>),
5015 OpaqueTy(&'hir OpaqueTy<'hir>),
5016 TyPat(&'hir TyPat<'hir>),
5017 Pat(&'hir Pat<'hir>),
5018 PatField(&'hir PatField<'hir>),
5019 /// Needed as its own node with its own HirId for tracking
5020 /// the unadjusted type of literals within patterns
5021 /// (e.g. byte str literals not being of slice type).
5022 PatExpr(&'hir PatExpr<'hir>),
5023 Arm(&'hir Arm<'hir>),
5024 Block(&'hir Block<'hir>),
5025 LetStmt(&'hir LetStmt<'hir>),
5026 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
5027 /// with synthesized constructors.
5028 Ctor(&'hir VariantData<'hir>),
5029 Lifetime(&'hir Lifetime),
5030 GenericParam(&'hir GenericParam<'hir>),
5031 Crate(&'hir Mod<'hir>),
5032 Infer(&'hir InferArg),
5033 WherePredicate(&'hir WherePredicate<'hir>),
5034 PreciseCapturingNonLifetimeArg(&'hir PreciseCapturingNonLifetimeArg),
5035 // Created by query feeding
5036 Synthetic,
5037 Err(Span),
5038}
5039
5040impl<'hir> Node<'hir> {
5041 /// Get the identifier of this `Node`, if applicable.
5042 ///
5043 /// # Edge cases
5044 ///
5045 /// Calling `.ident()` on a [`Node::Ctor`] will return `None`
5046 /// because `Ctor`s do not have identifiers themselves.
5047 /// Instead, call `.ident()` on the parent struct/variant, like so:
5048 ///
5049 /// ```ignore (illustrative)
5050 /// ctor
5051 /// .ctor_hir_id()
5052 /// .map(|ctor_id| tcx.parent_hir_node(ctor_id))
5053 /// .and_then(|parent| parent.ident())
5054 /// ```
5055 pub fn ident(&self) -> Option<Ident> {
5056 match self {
5057 Node::Item(item) => item.kind.ident(),
5058 Node::TraitItem(TraitItem { ident, .. })
5059 | Node::ImplItem(ImplItem { ident, .. })
5060 | Node::ForeignItem(ForeignItem { ident, .. })
5061 | Node::Field(FieldDef { ident, .. })
5062 | Node::Variant(Variant { ident, .. })
5063 | Node::PathSegment(PathSegment { ident, .. }) => Some(*ident),
5064 Node::Lifetime(lt) => Some(lt.ident),
5065 Node::GenericParam(p) => Some(p.name.ident()),
5066 Node::AssocItemConstraint(c) => Some(c.ident),
5067 Node::PatField(f) => Some(f.ident),
5068 Node::ExprField(f) => Some(f.ident),
5069 Node::ConstArgExprField(f) => Some(f.field),
5070 Node::PreciseCapturingNonLifetimeArg(a) => Some(a.ident),
5071 Node::Param(..)
5072 | Node::AnonConst(..)
5073 | Node::ConstBlock(..)
5074 | Node::ConstArg(..)
5075 | Node::Expr(..)
5076 | Node::Stmt(..)
5077 | Node::Block(..)
5078 | Node::Ctor(..)
5079 | Node::Pat(..)
5080 | Node::TyPat(..)
5081 | Node::PatExpr(..)
5082 | Node::Arm(..)
5083 | Node::LetStmt(..)
5084 | Node::Crate(..)
5085 | Node::Ty(..)
5086 | Node::TraitRef(..)
5087 | Node::OpaqueTy(..)
5088 | Node::Infer(..)
5089 | Node::WherePredicate(..)
5090 | Node::Synthetic
5091 | Node::Err(..) => None,
5092 }
5093 }
5094
5095 pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
5096 match self {
5097 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
5098 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
5099 | Node::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
5100 | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_sig, _, _), .. }) => {
5101 Some(fn_sig.decl)
5102 }
5103 Node::Expr(Expr { kind: ExprKind::Closure(Closure { fn_decl, .. }), .. }) => {
5104 Some(fn_decl)
5105 }
5106 _ => None,
5107 }
5108 }
5109
5110 /// Get a `hir::Impl` if the node is an impl block for the given `trait_def_id`.
5111 pub fn impl_block_of_trait(self, trait_def_id: DefId) -> Option<&'hir Impl<'hir>> {
5112 if let Node::Item(Item { kind: ItemKind::Impl(impl_block), .. }) = self
5113 && let Some(of_trait) = impl_block.of_trait
5114 && let Some(trait_id) = of_trait.trait_ref.trait_def_id()
5115 && trait_id == trait_def_id
5116 {
5117 Some(impl_block)
5118 } else {
5119 None
5120 }
5121 }
5122
5123 pub fn fn_sig(self) -> Option<&'hir FnSig<'hir>> {
5124 match self {
5125 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
5126 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
5127 | Node::Item(Item { kind: ItemKind::Fn { sig: fn_sig, .. }, .. })
5128 | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_sig, _, _), .. }) => {
5129 Some(fn_sig)
5130 }
5131 _ => None,
5132 }
5133 }
5134
5135 /// Get the type for constants, assoc types, type aliases and statics.
5136 pub fn ty(self) -> Option<&'hir Ty<'hir>> {
5137 match self {
5138 Node::Item(it) => match it.kind {
5139 ItemKind::TyAlias(_, _, ty)
5140 | ItemKind::Static(_, _, ty, _)
5141 | ItemKind::Const(_, _, ty, _) => Some(ty),
5142 ItemKind::Impl(impl_item) => Some(&impl_item.self_ty),
5143 _ => None,
5144 },
5145 Node::TraitItem(it) => match it.kind {
5146 TraitItemKind::Const(ty, _, _) => Some(ty),
5147 TraitItemKind::Type(_, ty) => ty,
5148 _ => None,
5149 },
5150 Node::ImplItem(it) => match it.kind {
5151 ImplItemKind::Const(ty, _) => Some(ty),
5152 ImplItemKind::Type(ty) => Some(ty),
5153 _ => None,
5154 },
5155 Node::ForeignItem(it) => match it.kind {
5156 ForeignItemKind::Static(ty, ..) => Some(ty),
5157 _ => None,
5158 },
5159 Node::GenericParam(param) => match param.kind {
5160 GenericParamKind::Lifetime { .. } => None,
5161 GenericParamKind::Type { default, .. } => default,
5162 GenericParamKind::Const { ty, .. } => Some(ty),
5163 },
5164 _ => None,
5165 }
5166 }
5167
5168 pub fn alias_ty(self) -> Option<&'hir Ty<'hir>> {
5169 match self {
5170 Node::Item(Item { kind: ItemKind::TyAlias(_, _, ty), .. }) => Some(ty),
5171 _ => None,
5172 }
5173 }
5174
5175 #[inline]
5176 pub fn associated_body(&self) -> Option<(LocalDefId, BodyId)> {
5177 match self {
5178 Node::Item(Item {
5179 owner_id,
5180 kind:
5181 ItemKind::Const(.., ConstItemRhs::Body(body))
5182 | ItemKind::Static(.., body)
5183 | ItemKind::Fn { body, .. },
5184 ..
5185 })
5186 | Node::TraitItem(TraitItem {
5187 owner_id,
5188 kind:
5189 TraitItemKind::Const(_, Some(ConstItemRhs::Body(body)), _)
5190 | TraitItemKind::Fn(_, TraitFn::Provided(body)),
5191 ..
5192 })
5193 | Node::ImplItem(ImplItem {
5194 owner_id,
5195 kind: ImplItemKind::Const(.., ConstItemRhs::Body(body)) | ImplItemKind::Fn(_, body),
5196 ..
5197 }) => Some((owner_id.def_id, *body)),
5198
5199 Node::Item(Item {
5200 owner_id, kind: ItemKind::GlobalAsm { asm: _, fake_body }, ..
5201 }) => Some((owner_id.def_id, *fake_body)),
5202
5203 Node::Expr(Expr { kind: ExprKind::Closure(Closure { def_id, body, .. }), .. }) => {
5204 Some((*def_id, *body))
5205 }
5206
5207 Node::AnonConst(constant) => Some((constant.def_id, constant.body)),
5208 Node::ConstBlock(constant) => Some((constant.def_id, constant.body)),
5209
5210 _ => None,
5211 }
5212 }
5213
5214 pub fn body_id(&self) -> Option<BodyId> {
5215 Some(self.associated_body()?.1)
5216 }
5217
5218 pub fn generics(self) -> Option<&'hir Generics<'hir>> {
5219 match self {
5220 Node::ForeignItem(ForeignItem {
5221 kind: ForeignItemKind::Fn(_, _, generics), ..
5222 })
5223 | Node::TraitItem(TraitItem { generics, .. })
5224 | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
5225 Node::Item(item) => item.kind.generics(),
5226 _ => None,
5227 }
5228 }
5229
5230 pub fn as_owner(self) -> Option<OwnerNode<'hir>> {
5231 match self {
5232 Node::Item(i) => Some(OwnerNode::Item(i)),
5233 Node::ForeignItem(i) => Some(OwnerNode::ForeignItem(i)),
5234 Node::TraitItem(i) => Some(OwnerNode::TraitItem(i)),
5235 Node::ImplItem(i) => Some(OwnerNode::ImplItem(i)),
5236 Node::Crate(i) => Some(OwnerNode::Crate(i)),
5237 Node::Synthetic => Some(OwnerNode::Synthetic),
5238 _ => None,
5239 }
5240 }
5241
5242 pub fn fn_kind(self) -> Option<FnKind<'hir>> {
5243 match self {
5244 Node::Item(i) => match i.kind {
5245 ItemKind::Fn { ident, sig, generics, .. } => {
5246 Some(FnKind::ItemFn(ident, generics, sig.header))
5247 }
5248 _ => None,
5249 },
5250 Node::TraitItem(ti) => match ti.kind {
5251 TraitItemKind::Fn(ref sig, _) => Some(FnKind::Method(ti.ident, sig)),
5252 _ => None,
5253 },
5254 Node::ImplItem(ii) => match ii.kind {
5255 ImplItemKind::Fn(ref sig, _) => Some(FnKind::Method(ii.ident, sig)),
5256 _ => None,
5257 },
5258 Node::Expr(e) => match e.kind {
5259 ExprKind::Closure { .. } => Some(FnKind::Closure),
5260 _ => None,
5261 },
5262 _ => None,
5263 }
5264 }
5265
5266 expect_methods_self! {
5267 expect_param, &'hir Param<'hir>, Node::Param(n), n;
5268 expect_item, &'hir Item<'hir>, Node::Item(n), n;
5269 expect_foreign_item, &'hir ForeignItem<'hir>, Node::ForeignItem(n), n;
5270 expect_trait_item, &'hir TraitItem<'hir>, Node::TraitItem(n), n;
5271 expect_impl_item, &'hir ImplItem<'hir>, Node::ImplItem(n), n;
5272 expect_variant, &'hir Variant<'hir>, Node::Variant(n), n;
5273 expect_field, &'hir FieldDef<'hir>, Node::Field(n), n;
5274 expect_anon_const, &'hir AnonConst, Node::AnonConst(n), n;
5275 expect_inline_const, &'hir ConstBlock, Node::ConstBlock(n), n;
5276 expect_expr, &'hir Expr<'hir>, Node::Expr(n), n;
5277 expect_expr_field, &'hir ExprField<'hir>, Node::ExprField(n), n;
5278 expect_stmt, &'hir Stmt<'hir>, Node::Stmt(n), n;
5279 expect_path_segment, &'hir PathSegment<'hir>, Node::PathSegment(n), n;
5280 expect_ty, &'hir Ty<'hir>, Node::Ty(n), n;
5281 expect_assoc_item_constraint, &'hir AssocItemConstraint<'hir>, Node::AssocItemConstraint(n), n;
5282 expect_trait_ref, &'hir TraitRef<'hir>, Node::TraitRef(n), n;
5283 expect_opaque_ty, &'hir OpaqueTy<'hir>, Node::OpaqueTy(n), n;
5284 expect_pat, &'hir Pat<'hir>, Node::Pat(n), n;
5285 expect_pat_field, &'hir PatField<'hir>, Node::PatField(n), n;
5286 expect_arm, &'hir Arm<'hir>, Node::Arm(n), n;
5287 expect_block, &'hir Block<'hir>, Node::Block(n), n;
5288 expect_let_stmt, &'hir LetStmt<'hir>, Node::LetStmt(n), n;
5289 expect_ctor, &'hir VariantData<'hir>, Node::Ctor(n), n;
5290 expect_lifetime, &'hir Lifetime, Node::Lifetime(n), n;
5291 expect_generic_param, &'hir GenericParam<'hir>, Node::GenericParam(n), n;
5292 expect_crate, &'hir Mod<'hir>, Node::Crate(n), n;
5293 expect_infer, &'hir InferArg, Node::Infer(n), n;
5294 expect_closure, &'hir Closure<'hir>, Node::Expr(Expr { kind: ExprKind::Closure(n), .. }), n;
5295 }
5296}
5297
5298// Some nodes are used a lot. Make sure they don't unintentionally get bigger.
5299#[cfg(target_pointer_width = "64")]
5300mod size_asserts {
5301 use rustc_data_structures::static_assert_size;
5302
5303 use super::*;
5304 // tidy-alphabetical-start
5305 static_assert_size!(Block<'_>, 48);
5306 static_assert_size!(Body<'_>, 24);
5307 static_assert_size!(Expr<'_>, 64);
5308 static_assert_size!(ExprKind<'_>, 48);
5309 static_assert_size!(FnDecl<'_>, 40);
5310 static_assert_size!(ForeignItem<'_>, 96);
5311 static_assert_size!(ForeignItemKind<'_>, 56);
5312 static_assert_size!(GenericArg<'_>, 16);
5313 static_assert_size!(GenericBound<'_>, 64);
5314 static_assert_size!(Generics<'_>, 56);
5315 static_assert_size!(Impl<'_>, 48);
5316 static_assert_size!(ImplItem<'_>, 88);
5317 static_assert_size!(ImplItemKind<'_>, 40);
5318 static_assert_size!(Item<'_>, 88);
5319 static_assert_size!(ItemKind<'_>, 64);
5320 static_assert_size!(LetStmt<'_>, 64);
5321 static_assert_size!(Param<'_>, 32);
5322 static_assert_size!(Pat<'_>, 80);
5323 static_assert_size!(PatKind<'_>, 56);
5324 static_assert_size!(Path<'_>, 40);
5325 static_assert_size!(PathSegment<'_>, 48);
5326 static_assert_size!(QPath<'_>, 24);
5327 static_assert_size!(Res, 12);
5328 static_assert_size!(Stmt<'_>, 32);
5329 static_assert_size!(StmtKind<'_>, 16);
5330 static_assert_size!(TraitImplHeader<'_>, 48);
5331 static_assert_size!(TraitItem<'_>, 88);
5332 static_assert_size!(TraitItemKind<'_>, 48);
5333 static_assert_size!(Ty<'_>, 48);
5334 static_assert_size!(TyKind<'_>, 32);
5335 // tidy-alphabetical-end
5336}
5337
5338#[cfg(test)]
5339mod tests;