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