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