1 use crate::def::{CtorKind, DefKind, Res};
2 use crate::def_id::DefId;
3 pub(crate) use crate::hir_id::{HirId, ItemLocalId, OwnerId};
4 use crate::intravisit::FnKind;
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;
26 use smallvec::SmallVec;
29 #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)]
33 /// Either "`'a`", referring to a named lifetime definition,
34 /// `'_` referring to an anonymous lifetime (either explicitly `'_` or `&type`),
35 /// or "``" (i.e., `kw::Empty`) when appearing in path.
37 /// See `Lifetime::suggestion_position` for practical use.
40 /// Semantics of this lifetime.
41 pub res: LifetimeName,
44 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
45 #[derive(HashStable_Generic)]
47 /// Some user-given name like `T` or `'x`.
50 /// Synthetic name generated when user elided a lifetime in an impl header.
52 /// E.g., the lifetimes in cases like these:
53 /// ```ignore (fragment)
55 /// impl Foo<'_> for u32
57 /// in that case, we rewrite to
58 /// ```ignore (fragment)
59 /// impl<'f> Foo for &'f u32
60 /// impl<'f> Foo<'f> for u32
62 /// where `'f` is something like `Fresh(0)`. The indices are
63 /// unique per impl, but not necessarily continuous.
66 /// Indicates an illegal name was given and an error has been
67 /// reported (so we should squelch other derived errors). Occurs
68 /// when, e.g., `'_` is used in the wrong place.
73 pub fn ident(&self) -> Ident {
75 ParamName::Plain(ident) => ident,
76 ParamName::Fresh | ParamName::Error => Ident::with_dummy_span(kw::UnderscoreLifetime),
80 pub fn normalize_to_macros_2_0(&self) -> ParamName {
82 ParamName::Plain(ident) => ParamName::Plain(ident.normalize_to_macros_2_0()),
83 param_name => param_name,
88 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
89 #[derive(HashStable_Generic)]
90 pub enum LifetimeName {
91 /// User-given names or fresh (synthetic) names.
94 /// Implicit lifetime in a context like `dyn Foo`. This is
95 /// distinguished from implicit lifetimes elsewhere because the
96 /// lifetime that they default to must appear elsewhere within the
97 /// enclosing type. This means that, in an `impl Trait` context, we
98 /// don't have to create a parameter for them. That is, `impl
99 /// Trait<Item = &u32>` expands to an opaque type like `type
100 /// Foo<'a> = impl Trait<Item = &'a u32>`, but `impl Trait<item =
101 /// dyn Bar>` expands to `type Foo = impl Trait<Item = dyn Bar +
102 /// 'static>`. The latter uses `ImplicitObjectLifetimeDefault` so
103 /// that surrounding code knows not to create a lifetime
105 ImplicitObjectLifetimeDefault,
107 /// Indicates an error during lowering (usually `'_` in wrong place)
108 /// that was already reported.
111 /// User wrote an anonymous lifetime, either `'_` or nothing.
112 /// The semantics of this lifetime should be inferred by typechecking code.
115 /// User wrote `'static`.
120 pub fn is_elided(&self) -> bool {
122 LifetimeName::ImplicitObjectLifetimeDefault | LifetimeName::Infer => true,
124 // It might seem surprising that `Fresh` counts as not *elided*
125 // -- but this is because, as far as the code in the compiler is
126 // concerned -- `Fresh` variants act equivalently to "some fresh name".
127 // They correspond to early-bound regions on an impl, in other words.
128 LifetimeName::Error | LifetimeName::Param(..) | LifetimeName::Static => false,
133 impl fmt::Display for Lifetime {
134 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
135 if self.ident.name != kw::Empty { self.ident.name.fmt(f) } else { "'_".fmt(f) }
139 pub enum LifetimeSuggestionPosition {
140 /// The user wrote `'a` or `'_`.
142 /// The user wrote `&type` or `&mut type`.
144 /// The user wrote `Path` and omitted the `<'_>`.
146 /// The user wrote `Path<T>`, and omitted the `'_,`.
148 /// The user wrote `dyn Trait` and omitted the `+ '_`.
153 pub fn is_elided(&self) -> bool {
157 pub fn is_anonymous(&self) -> bool {
158 self.ident.name == kw::Empty || self.ident.name == kw::UnderscoreLifetime
161 pub fn suggestion_position(&self) -> (LifetimeSuggestionPosition, Span) {
162 if self.ident.name == kw::Empty {
163 if self.ident.span.is_empty() {
164 (LifetimeSuggestionPosition::ElidedPathArgument, self.ident.span)
166 (LifetimeSuggestionPosition::ElidedPath, self.ident.span.shrink_to_hi())
168 } else if self.res == LifetimeName::ImplicitObjectLifetimeDefault {
169 (LifetimeSuggestionPosition::ObjectDefault, self.ident.span)
170 } else if self.ident.span.is_empty() {
171 (LifetimeSuggestionPosition::Ampersand, self.ident.span)
173 (LifetimeSuggestionPosition::Normal, self.ident.span)
177 pub fn is_static(&self) -> bool {
178 self.res == LifetimeName::Static
182 /// A `Path` is essentially Rust's notion of a name; for instance,
183 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
184 /// along with a bunch of supporting information.
185 #[derive(Debug, HashStable_Generic)]
186 pub struct Path<'hir> {
188 /// The resolution for the path.
190 /// The segments in the path: the things separated by `::`.
191 pub segments: &'hir [PathSegment<'hir>],
195 pub fn is_global(&self) -> bool {
196 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
200 /// A segment of a path: an identifier, an optional lifetime, and a set of
202 #[derive(Debug, HashStable_Generic)]
203 pub struct PathSegment<'hir> {
204 /// The identifier portion of this path segment.
209 /// Type/lifetime parameters attached to this path. They come in
210 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
211 /// this is more than just simple syntactic sugar; the use of
212 /// parens affects the region binding rules, so we preserve the
214 pub args: Option<&'hir GenericArgs<'hir>>,
216 /// Whether to infer remaining type parameters, if any.
217 /// This only applies to expression and pattern paths, and
218 /// out of those only the segments with no type parameters
219 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
220 pub infer_args: bool,
223 impl<'hir> PathSegment<'hir> {
224 /// Converts an identifier to the corresponding segment.
225 pub fn new(ident: Ident, hir_id: HirId, res: Res) -> PathSegment<'hir> {
226 PathSegment { ident, hir_id, res, infer_args: true, args: None }
229 pub fn invalid() -> Self {
230 Self::new(Ident::empty(), HirId::INVALID, Res::Err)
233 pub fn args(&self) -> &GenericArgs<'hir> {
234 if let Some(ref args) = self.args {
237 const DUMMY: &GenericArgs<'_> = &GenericArgs::none();
243 #[derive(Encodable, Debug, HashStable_Generic)]
244 pub struct ConstArg {
245 pub value: AnonConst,
249 #[derive(Encodable, Debug, HashStable_Generic)]
250 pub struct InferArg {
256 pub fn to_ty(&self) -> Ty<'_> {
257 Ty { kind: TyKind::Infer, span: self.span, hir_id: self.hir_id }
261 #[derive(Debug, HashStable_Generic)]
262 pub enum GenericArg<'hir> {
263 Lifetime(&'hir Lifetime),
264 Type(&'hir Ty<'hir>),
269 impl GenericArg<'_> {
270 pub fn span(&self) -> Span {
272 GenericArg::Lifetime(l) => l.ident.span,
273 GenericArg::Type(t) => t.span,
274 GenericArg::Const(c) => c.span,
275 GenericArg::Infer(i) => i.span,
279 pub fn hir_id(&self) -> HirId {
281 GenericArg::Lifetime(l) => l.hir_id,
282 GenericArg::Type(t) => t.hir_id,
283 GenericArg::Const(c) => c.value.hir_id,
284 GenericArg::Infer(i) => i.hir_id,
288 pub fn is_synthetic(&self) -> bool {
289 matches!(self, GenericArg::Lifetime(lifetime) if lifetime.ident == Ident::empty())
292 pub fn descr(&self) -> &'static str {
294 GenericArg::Lifetime(_) => "lifetime",
295 GenericArg::Type(_) => "type",
296 GenericArg::Const(_) => "constant",
297 GenericArg::Infer(_) => "inferred",
301 pub fn to_ord(&self) -> ast::ParamKindOrd {
303 GenericArg::Lifetime(_) => ast::ParamKindOrd::Lifetime,
304 GenericArg::Type(_) | GenericArg::Const(_) | GenericArg::Infer(_) => {
305 ast::ParamKindOrd::TypeOrConst
310 pub fn is_ty_or_const(&self) -> bool {
312 GenericArg::Lifetime(_) => false,
313 GenericArg::Type(_) | GenericArg::Const(_) | GenericArg::Infer(_) => true,
318 #[derive(Debug, HashStable_Generic)]
319 pub struct GenericArgs<'hir> {
320 /// The generic arguments for this path segment.
321 pub args: &'hir [GenericArg<'hir>],
322 /// Bindings (equality constraints) on associated types, if present.
323 /// E.g., `Foo<A = Bar>`.
324 pub bindings: &'hir [TypeBinding<'hir>],
325 /// Were arguments written in parenthesized form `Fn(T) -> U`?
326 /// This is required mostly for pretty-printing and diagnostics,
327 /// but also for changing lifetime elision rules to be "function-like".
328 pub parenthesized: bool,
329 /// The span encompassing arguments and the surrounding brackets `<>` or `()`
330 /// Foo<A, B, AssocTy = D> Fn(T, U, V) -> W
331 /// ^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^
332 /// Note that this may be:
333 /// - empty, if there are no generic brackets (but there may be hidden lifetimes)
334 /// - dummy, if this was generated while desugaring
338 impl<'hir> GenericArgs<'hir> {
339 pub const fn none() -> Self {
340 Self { args: &[], bindings: &[], parenthesized: false, span_ext: DUMMY_SP }
343 pub fn inputs(&self) -> &[Ty<'hir>] {
344 if self.parenthesized {
345 for arg in self.args {
347 GenericArg::Lifetime(_) => {}
348 GenericArg::Type(ref ty) => {
349 if let TyKind::Tup(ref tys) = ty.kind {
354 GenericArg::Const(_) => {}
355 GenericArg::Infer(_) => {}
359 panic!("GenericArgs::inputs: not a `Fn(T) -> U`");
363 pub fn has_type_params(&self) -> bool {
364 self.args.iter().any(|arg| matches!(arg, GenericArg::Type(_)))
367 pub fn has_err(&self) -> bool {
368 self.args.iter().any(|arg| match arg {
369 GenericArg::Type(ty) => matches!(ty.kind, TyKind::Err),
371 }) || self.bindings.iter().any(|arg| match arg.kind {
372 TypeBindingKind::Equality { term: Term::Ty(ty) } => matches!(ty.kind, TyKind::Err),
378 pub fn num_type_params(&self) -> usize {
379 self.args.iter().filter(|arg| matches!(arg, GenericArg::Type(_))).count()
383 pub fn num_lifetime_params(&self) -> usize {
384 self.args.iter().filter(|arg| matches!(arg, GenericArg::Lifetime(_))).count()
388 pub fn has_lifetime_params(&self) -> bool {
389 self.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)))
393 /// This function returns the number of type and const generic params.
394 /// It should only be used for diagnostics.
395 pub fn num_generic_params(&self) -> usize {
396 self.args.iter().filter(|arg| !matches!(arg, GenericArg::Lifetime(_))).count()
399 /// The span encompassing the text inside the surrounding brackets.
400 /// It will also include bindings if they aren't in the form `-> Ret`
401 /// Returns `None` if the span is empty (e.g. no brackets) or dummy
402 pub fn span(&self) -> Option<Span> {
403 let span_ext = self.span_ext()?;
404 Some(span_ext.with_lo(span_ext.lo() + BytePos(1)).with_hi(span_ext.hi() - BytePos(1)))
407 /// Returns span encompassing arguments and their surrounding `<>` or `()`
408 pub fn span_ext(&self) -> Option<Span> {
409 Some(self.span_ext).filter(|span| !span.is_empty())
412 pub fn is_empty(&self) -> bool {
417 /// A modifier on a bound, currently this is only used for `?Sized`, where the
418 /// modifier is `Maybe`. Negative bounds should also be handled here.
419 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
420 #[derive(HashStable_Generic)]
421 pub enum TraitBoundModifier {
427 /// The AST represents all type param bounds as types.
428 /// `typeck::collect::compute_bounds` matches these against
429 /// the "special" built-in traits (see `middle::lang_items`) and
430 /// detects `Copy`, `Send` and `Sync`.
431 #[derive(Clone, Debug, HashStable_Generic)]
432 pub enum GenericBound<'hir> {
433 Trait(PolyTraitRef<'hir>, TraitBoundModifier),
434 // FIXME(davidtwco): Introduce `PolyTraitRef::LangItem`
435 LangItemTrait(LangItem, Span, HirId, &'hir GenericArgs<'hir>),
436 Outlives(&'hir Lifetime),
439 impl GenericBound<'_> {
440 pub fn trait_ref(&self) -> Option<&TraitRef<'_>> {
442 GenericBound::Trait(data, _) => Some(&data.trait_ref),
447 pub fn span(&self) -> Span {
449 GenericBound::Trait(t, ..) => t.span,
450 GenericBound::LangItemTrait(_, span, ..) => *span,
451 GenericBound::Outlives(l) => l.ident.span,
456 pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
458 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
459 pub enum LifetimeParamKind {
460 // Indicates that the lifetime definition was explicitly declared (e.g., in
461 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
464 // Indication that the lifetime was elided (e.g., in both cases in
465 // `fn foo(x: &u8) -> &'_ u8 { x }`).
468 // Indication that the lifetime name was somehow in error.
472 #[derive(Debug, HashStable_Generic)]
473 pub enum GenericParamKind<'hir> {
474 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
476 kind: LifetimeParamKind,
479 default: Option<&'hir Ty<'hir>>,
484 /// Optional default value for the const generic param
485 default: Option<AnonConst>,
489 #[derive(Debug, HashStable_Generic)]
490 pub struct GenericParam<'hir> {
492 pub def_id: LocalDefId,
495 pub pure_wrt_drop: bool,
496 pub kind: GenericParamKind<'hir>,
497 pub colon_span: Option<Span>,
500 impl<'hir> GenericParam<'hir> {
501 /// Synthetic type-parameters are inserted after normal ones.
502 /// In order for normal parameters to be able to refer to synthetic ones,
503 /// scans them first.
504 pub fn is_impl_trait(&self) -> bool {
505 matches!(self.kind, GenericParamKind::Type { synthetic: true, .. })
508 /// This can happen for `async fn`, e.g. `async fn f<'_>(&'_ self)`.
510 /// See `lifetime_to_generic_param` in `rustc_ast_lowering` for more information.
511 pub fn is_elided_lifetime(&self) -> bool {
512 matches!(self.kind, GenericParamKind::Lifetime { kind: LifetimeParamKind::Elided })
517 pub struct GenericParamCount {
518 pub lifetimes: usize,
524 /// Represents lifetimes and type parameters attached to a declaration
525 /// of a function, enum, trait, etc.
526 #[derive(Debug, HashStable_Generic)]
527 pub struct Generics<'hir> {
528 pub params: &'hir [GenericParam<'hir>],
529 pub predicates: &'hir [WherePredicate<'hir>],
530 pub has_where_clause_predicates: bool,
531 pub where_clause_span: Span,
535 impl<'hir> Generics<'hir> {
536 pub const fn empty() -> &'hir Generics<'hir> {
537 const NOPE: Generics<'_> = Generics {
540 has_where_clause_predicates: false,
541 where_clause_span: DUMMY_SP,
547 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'hir>> {
548 for param in self.params {
549 if name == param.name.ident().name {
556 pub fn spans(&self) -> MultiSpan {
557 if self.params.is_empty() {
560 self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
564 /// If there are generic parameters, return where to introduce a new one.
565 pub fn span_for_lifetime_suggestion(&self) -> Option<Span> {
566 if let Some(first) = self.params.first()
567 && self.span.contains(first.span)
569 // `fn foo<A>(t: impl Trait)`
570 // ^ suggest `'a, ` here
571 Some(first.span.shrink_to_lo())
577 /// If there are generic parameters, return where to introduce a new one.
578 pub fn span_for_param_suggestion(&self) -> Option<Span> {
579 if self.params.iter().any(|p| self.span.contains(p.span)) {
580 // `fn foo<A>(t: impl Trait)`
581 // ^ suggest `, T: Trait` here
582 let span = self.span.with_lo(self.span.hi() - BytePos(1)).shrink_to_lo();
589 /// `Span` where further predicates would be suggested, accounting for trailing commas, like
590 /// in `fn foo<T>(t: T) where T: Foo,` so we don't suggest two trailing commas.
591 pub fn tail_span_for_predicate_suggestion(&self) -> Span {
592 let end = self.where_clause_span.shrink_to_hi();
593 if self.has_where_clause_predicates {
596 .rfind(|&p| p.in_where_clause())
597 .map_or(end, |p| p.span())
605 pub fn add_where_or_trailing_comma(&self) -> &'static str {
606 if self.has_where_clause_predicates {
608 } else if self.where_clause_span.is_empty() {
611 // No where clause predicates, but we have `where` token
616 pub fn bounds_for_param(
618 param_def_id: LocalDefId,
619 ) -> impl Iterator<Item = &WhereBoundPredicate<'hir>> {
620 self.predicates.iter().filter_map(move |pred| match pred {
621 WherePredicate::BoundPredicate(bp) if bp.is_param_bound(param_def_id.to_def_id()) => {
628 pub fn outlives_for_param(
630 param_def_id: LocalDefId,
631 ) -> impl Iterator<Item = &WhereRegionPredicate<'_>> {
632 self.predicates.iter().filter_map(move |pred| match pred {
633 WherePredicate::RegionPredicate(rp) if rp.is_param_bound(param_def_id) => Some(rp),
638 pub fn bounds_span_for_suggestions(&self, param_def_id: LocalDefId) -> Option<Span> {
639 self.bounds_for_param(param_def_id).flat_map(|bp| bp.bounds.iter().rev()).find_map(
641 // We include bounds that come from a `#[derive(_)]` but point at the user's code,
642 // as we use this method to get a span appropriate for suggestions.
643 let bs = bound.span();
644 if bs.can_be_used_for_suggestions() { Some(bs.shrink_to_hi()) } else { None }
649 pub fn span_for_predicate_removal(&self, pos: usize) -> Span {
650 let predicate = &self.predicates[pos];
651 let span = predicate.span();
653 if !predicate.in_where_clause() {
659 // We need to find out which comma to remove.
660 if pos < self.predicates.len() - 1 {
661 let next_pred = &self.predicates[pos + 1];
662 if next_pred.in_where_clause() {
663 // where T: ?Sized, Foo: Bar,
665 return span.until(next_pred.span());
670 let prev_pred = &self.predicates[pos - 1];
671 if prev_pred.in_where_clause() {
672 // where Foo: Bar, T: ?Sized,
674 return prev_pred.span().shrink_to_hi().to(span);
678 // This is the only predicate in the where clause.
681 self.where_clause_span
684 pub fn span_for_bound_removal(&self, predicate_pos: usize, bound_pos: usize) -> Span {
685 let predicate = &self.predicates[predicate_pos];
686 let bounds = predicate.bounds();
688 if bounds.len() == 1 {
689 return self.span_for_predicate_removal(predicate_pos);
692 let span = bounds[bound_pos].span();
694 // where T: ?Sized + Bar, Foo: Bar,
696 span.to(bounds[1].span().shrink_to_lo())
698 // where T: Bar + ?Sized, Foo: Bar,
700 bounds[bound_pos - 1].span().shrink_to_hi().to(span)
705 /// A single predicate in a where-clause.
706 #[derive(Debug, HashStable_Generic)]
707 pub enum WherePredicate<'hir> {
708 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
709 BoundPredicate(WhereBoundPredicate<'hir>),
710 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
711 RegionPredicate(WhereRegionPredicate<'hir>),
712 /// An equality predicate (unsupported).
713 EqPredicate(WhereEqPredicate<'hir>),
716 impl<'hir> WherePredicate<'hir> {
717 pub fn span(&self) -> Span {
719 WherePredicate::BoundPredicate(p) => p.span,
720 WherePredicate::RegionPredicate(p) => p.span,
721 WherePredicate::EqPredicate(p) => p.span,
725 pub fn in_where_clause(&self) -> bool {
727 WherePredicate::BoundPredicate(p) => p.origin == PredicateOrigin::WhereClause,
728 WherePredicate::RegionPredicate(p) => p.in_where_clause,
729 WherePredicate::EqPredicate(_) => false,
733 pub fn bounds(&self) -> GenericBounds<'hir> {
735 WherePredicate::BoundPredicate(p) => p.bounds,
736 WherePredicate::RegionPredicate(p) => p.bounds,
737 WherePredicate::EqPredicate(_) => &[],
742 #[derive(Copy, Clone, Debug, HashStable_Generic, PartialEq, Eq)]
743 pub enum PredicateOrigin {
749 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
750 #[derive(Debug, HashStable_Generic)]
751 pub struct WhereBoundPredicate<'hir> {
754 /// Origin of the predicate.
755 pub origin: PredicateOrigin,
756 /// Any generics from a `for` binding.
757 pub bound_generic_params: &'hir [GenericParam<'hir>],
758 /// The type being bounded.
759 pub bounded_ty: &'hir Ty<'hir>,
760 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
761 pub bounds: GenericBounds<'hir>,
764 impl<'hir> WhereBoundPredicate<'hir> {
765 /// Returns `true` if `param_def_id` matches the `bounded_ty` of this predicate.
766 pub fn is_param_bound(&self, param_def_id: DefId) -> bool {
767 self.bounded_ty.as_generic_param().map_or(false, |(def_id, _)| def_id == param_def_id)
771 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
772 #[derive(Debug, HashStable_Generic)]
773 pub struct WhereRegionPredicate<'hir> {
775 pub in_where_clause: bool,
776 pub lifetime: &'hir Lifetime,
777 pub bounds: GenericBounds<'hir>,
780 impl<'hir> WhereRegionPredicate<'hir> {
781 /// Returns `true` if `param_def_id` matches the `lifetime` of this predicate.
782 pub fn is_param_bound(&self, param_def_id: LocalDefId) -> bool {
783 self.lifetime.res == LifetimeName::Param(param_def_id)
787 /// An equality predicate (e.g., `T = int`); currently unsupported.
788 #[derive(Debug, HashStable_Generic)]
789 pub struct WhereEqPredicate<'hir> {
791 pub lhs_ty: &'hir Ty<'hir>,
792 pub rhs_ty: &'hir Ty<'hir>,
795 /// HIR node coupled with its parent's id in the same HIR owner.
797 /// The parent is trash when the node is a HIR owner.
798 #[derive(Clone, Debug)]
799 pub struct ParentedNode<'tcx> {
800 pub parent: ItemLocalId,
801 pub node: Node<'tcx>,
804 /// Attributes owned by a HIR owner.
806 pub struct AttributeMap<'tcx> {
807 pub map: SortedMap<ItemLocalId, &'tcx [Attribute]>,
808 pub hash: Fingerprint,
811 impl<'tcx> AttributeMap<'tcx> {
812 pub const EMPTY: &'static AttributeMap<'static> =
813 &AttributeMap { map: SortedMap::new(), hash: Fingerprint::ZERO };
816 pub fn get(&self, id: ItemLocalId) -> &'tcx [Attribute] {
817 self.map.get(&id).copied().unwrap_or(&[])
821 /// Map of all HIR nodes inside the current owner.
822 /// These nodes are mapped by `ItemLocalId` alongside the index of their parent node.
823 /// The HIR tree, including bodies, is pre-hashed.
824 pub struct OwnerNodes<'tcx> {
825 /// Pre-computed hash of the full HIR.
826 pub hash_including_bodies: Fingerprint,
827 /// Pre-computed hash of the item signature, sithout recursing into the body.
828 pub hash_without_bodies: Fingerprint,
829 /// Full HIR for the current owner.
830 // The zeroth node's parent should never be accessed: the owner's parent is computed by the
831 // hir_owner_parent query. It is set to `ItemLocalId::INVALID` to force an ICE if accidentally
833 pub nodes: IndexVec<ItemLocalId, Option<ParentedNode<'tcx>>>,
834 /// Content of local bodies.
835 pub bodies: SortedMap<ItemLocalId, &'tcx Body<'tcx>>,
836 /// Non-owning definitions contained in this owner.
837 pub local_id_to_def_id: SortedMap<ItemLocalId, LocalDefId>,
840 impl<'tcx> OwnerNodes<'tcx> {
841 pub fn node(&self) -> OwnerNode<'tcx> {
842 use rustc_index::vec::Idx;
843 let node = self.nodes[ItemLocalId::new(0)].as_ref().unwrap().node;
844 let node = node.as_owner().unwrap(); // Indexing must ensure it is an OwnerNode.
849 impl fmt::Debug for OwnerNodes<'_> {
850 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
851 f.debug_struct("OwnerNodes")
852 // Do not print all the pointers to all the nodes, as it would be unreadable.
853 .field("node", &self.nodes[ItemLocalId::from_u32(0)])
859 .map(|(id, parented_node)| (id, parented_node.as_ref().map(|node| node.parent)))
860 .collect::<Vec<_>>(),
862 .field("bodies", &self.bodies)
863 .field("local_id_to_def_id", &self.local_id_to_def_id)
864 .field("hash_without_bodies", &self.hash_without_bodies)
865 .field("hash_including_bodies", &self.hash_including_bodies)
870 /// Full information resulting from lowering an AST node.
871 #[derive(Debug, HashStable_Generic)]
872 pub struct OwnerInfo<'hir> {
873 /// Contents of the HIR.
874 pub nodes: OwnerNodes<'hir>,
875 /// Map from each nested owner to its parent's local id.
876 pub parenting: FxHashMap<LocalDefId, ItemLocalId>,
877 /// Collected attributes of the HIR nodes.
878 pub attrs: AttributeMap<'hir>,
879 /// Map indicating what traits are in scope for places where this
880 /// is relevant; generated by resolve.
881 pub trait_map: FxHashMap<ItemLocalId, Box<[TraitCandidate]>>,
884 impl<'tcx> OwnerInfo<'tcx> {
886 pub fn node(&self) -> OwnerNode<'tcx> {
891 #[derive(Copy, Clone, Debug, HashStable_Generic)]
892 pub enum MaybeOwner<T> {
895 /// Used as a placeholder for unused LocalDefId.
899 impl<T> MaybeOwner<T> {
900 pub fn as_owner(self) -> Option<T> {
902 MaybeOwner::Owner(i) => Some(i),
903 MaybeOwner::NonOwner(_) | MaybeOwner::Phantom => None,
907 pub fn map<U>(self, f: impl FnOnce(T) -> U) -> MaybeOwner<U> {
909 MaybeOwner::Owner(i) => MaybeOwner::Owner(f(i)),
910 MaybeOwner::NonOwner(hir_id) => MaybeOwner::NonOwner(hir_id),
911 MaybeOwner::Phantom => MaybeOwner::Phantom,
915 pub fn unwrap(self) -> T {
917 MaybeOwner::Owner(i) => i,
918 MaybeOwner::NonOwner(_) | MaybeOwner::Phantom => panic!("Not a HIR owner"),
923 /// The top-level data structure that stores the entire contents of
924 /// the crate currently being compiled.
926 /// For more details, see the [rustc dev guide].
928 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
930 pub struct Crate<'hir> {
931 pub owners: IndexVec<LocalDefId, MaybeOwner<&'hir OwnerInfo<'hir>>>,
932 pub hir_hash: Fingerprint,
935 #[derive(Debug, HashStable_Generic)]
936 pub struct Closure<'hir> {
937 pub def_id: LocalDefId,
938 pub binder: ClosureBinder,
939 pub capture_clause: CaptureBy,
940 pub bound_generic_params: &'hir [GenericParam<'hir>],
941 pub fn_decl: &'hir FnDecl<'hir>,
943 pub fn_decl_span: Span,
944 pub movability: Option<Movability>,
947 /// A block of statements `{ .. }`, which may have a label (in this case the
948 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
949 /// the `rules` being anything but `DefaultBlock`.
950 #[derive(Debug, HashStable_Generic)]
951 pub struct Block<'hir> {
952 /// Statements in a block.
953 pub stmts: &'hir [Stmt<'hir>],
954 /// An expression at the end of the block
955 /// without a semicolon, if any.
956 pub expr: Option<&'hir Expr<'hir>>,
957 #[stable_hasher(ignore)]
959 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
960 pub rules: BlockCheckMode,
962 /// If true, then there may exist `break 'a` values that aim to
963 /// break out of this block early.
964 /// Used by `'label: {}` blocks and by `try {}` blocks.
965 pub targeted_by_break: bool,
968 impl<'hir> Block<'hir> {
969 pub fn innermost_block(&self) -> &Block<'hir> {
970 let mut block = self;
971 while let Some(Expr { kind: ExprKind::Block(inner_block, _), .. }) = block.expr {
978 #[derive(Debug, HashStable_Generic)]
979 pub struct Pat<'hir> {
980 #[stable_hasher(ignore)]
982 pub kind: PatKind<'hir>,
984 /// Whether to use default binding modes.
985 /// At present, this is false only for destructuring assignment.
986 pub default_binding_modes: bool,
989 impl<'hir> Pat<'hir> {
990 // FIXME(#19596) this is a workaround, but there should be a better way
991 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) -> bool {
998 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
999 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
1000 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
1001 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
1002 Slice(before, slice, after) => {
1003 before.iter().chain(slice).chain(after.iter()).all(|p| p.walk_short_(it))
1008 /// Walk the pattern in left-to-right order,
1009 /// short circuiting (with `.all(..)`) if `false` is returned.
1011 /// Note that when visiting e.g. `Tuple(ps)`,
1012 /// if visiting `ps[0]` returns `false`,
1013 /// then `ps[1]` will not be visited.
1014 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) -> bool {
1015 self.walk_short_(&mut it)
1018 // FIXME(#19596) this is a workaround, but there should be a better way
1019 fn walk_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) {
1026 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
1027 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
1028 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
1029 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
1030 Slice(before, slice, after) => {
1031 before.iter().chain(slice).chain(after.iter()).for_each(|p| p.walk_(it))
1036 /// Walk the pattern in left-to-right order.
1038 /// If `it(pat)` returns `false`, the children are not visited.
1039 pub fn walk(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) {
1043 /// Walk the pattern in left-to-right order.
1045 /// If you always want to recurse, prefer this method over `walk`.
1046 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
1054 /// A single field in a struct pattern.
1056 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
1057 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
1058 /// except `is_shorthand` is true.
1059 #[derive(Debug, HashStable_Generic)]
1060 pub struct PatField<'hir> {
1061 #[stable_hasher(ignore)]
1063 /// The identifier for the field.
1065 /// The pattern the field is destructured to.
1066 pub pat: &'hir Pat<'hir>,
1067 pub is_shorthand: bool,
1071 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1077 impl fmt::Display for RangeEnd {
1078 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1079 f.write_str(match self {
1080 RangeEnd::Included => "..=",
1081 RangeEnd::Excluded => "..",
1086 // Equivalent to `Option<usize>`. That type takes up 16 bytes on 64-bit, but
1087 // this type only takes up 4 bytes, at the cost of being restricted to a
1088 // maximum value of `u32::MAX - 1`. In practice, this is more than enough.
1089 #[derive(Clone, Copy, PartialEq, Eq, Hash, HashStable_Generic)]
1090 pub struct DotDotPos(u32);
1093 /// Panics if n >= u32::MAX.
1094 pub fn new(n: Option<usize>) -> Self {
1097 assert!(n < u32::MAX as usize);
1100 None => Self(u32::MAX),
1104 pub fn as_opt_usize(&self) -> Option<usize> {
1105 if self.0 == u32::MAX { None } else { Some(self.0 as usize) }
1109 impl fmt::Debug for DotDotPos {
1110 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1111 self.as_opt_usize().fmt(f)
1115 #[derive(Debug, HashStable_Generic)]
1116 pub enum PatKind<'hir> {
1117 /// Represents a wildcard pattern (i.e., `_`).
1120 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
1121 /// The `HirId` is the canonical ID for the variable being bound,
1122 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
1123 /// which is the pattern ID of the first `x`.
1124 Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
1126 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
1127 /// The `bool` is `true` in the presence of a `..`.
1128 Struct(QPath<'hir>, &'hir [PatField<'hir>], bool),
1130 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
1131 /// If the `..` pattern fragment is present, then `DotDotPos` denotes its position.
1132 /// `0 <= position <= subpats.len()`
1133 TupleStruct(QPath<'hir>, &'hir [Pat<'hir>], DotDotPos),
1135 /// An or-pattern `A | B | C`.
1136 /// Invariant: `pats.len() >= 2`.
1137 Or(&'hir [Pat<'hir>]),
1139 /// A path pattern for a unit struct/variant or a (maybe-associated) constant.
1142 /// A tuple pattern (e.g., `(a, b)`).
1143 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
1144 /// `0 <= position <= subpats.len()`
1145 Tuple(&'hir [Pat<'hir>], DotDotPos),
1147 /// A `box` pattern.
1148 Box(&'hir Pat<'hir>),
1150 /// A reference pattern (e.g., `&mut (a, b)`).
1151 Ref(&'hir Pat<'hir>, Mutability),
1154 Lit(&'hir Expr<'hir>),
1156 /// A range pattern (e.g., `1..=2` or `1..2`).
1157 Range(Option<&'hir Expr<'hir>>, Option<&'hir Expr<'hir>>, RangeEnd),
1159 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
1161 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
1162 /// If `slice` exists, then `after` can be non-empty.
1164 /// The representation for e.g., `[a, b, .., c, d]` is:
1165 /// ```ignore (illustrative)
1166 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
1168 Slice(&'hir [Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [Pat<'hir>]),
1171 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1172 pub enum BinOpKind {
1173 /// The `+` operator (addition).
1175 /// The `-` operator (subtraction).
1177 /// The `*` operator (multiplication).
1179 /// The `/` operator (division).
1181 /// The `%` operator (modulus).
1183 /// The `&&` operator (logical and).
1185 /// The `||` operator (logical or).
1187 /// The `^` operator (bitwise xor).
1189 /// The `&` operator (bitwise and).
1191 /// The `|` operator (bitwise or).
1193 /// The `<<` operator (shift left).
1195 /// The `>>` operator (shift right).
1197 /// The `==` operator (equality).
1199 /// The `<` operator (less than).
1201 /// The `<=` operator (less than or equal to).
1203 /// The `!=` operator (not equal to).
1205 /// The `>=` operator (greater than or equal to).
1207 /// The `>` operator (greater than).
1212 pub fn as_str(self) -> &'static str {
1214 BinOpKind::Add => "+",
1215 BinOpKind::Sub => "-",
1216 BinOpKind::Mul => "*",
1217 BinOpKind::Div => "/",
1218 BinOpKind::Rem => "%",
1219 BinOpKind::And => "&&",
1220 BinOpKind::Or => "||",
1221 BinOpKind::BitXor => "^",
1222 BinOpKind::BitAnd => "&",
1223 BinOpKind::BitOr => "|",
1224 BinOpKind::Shl => "<<",
1225 BinOpKind::Shr => ">>",
1226 BinOpKind::Eq => "==",
1227 BinOpKind::Lt => "<",
1228 BinOpKind::Le => "<=",
1229 BinOpKind::Ne => "!=",
1230 BinOpKind::Ge => ">=",
1231 BinOpKind::Gt => ">",
1235 pub fn is_lazy(self) -> bool {
1236 matches!(self, BinOpKind::And | BinOpKind::Or)
1239 pub fn is_shift(self) -> bool {
1240 matches!(self, BinOpKind::Shl | BinOpKind::Shr)
1243 pub fn is_comparison(self) -> bool {
1250 | BinOpKind::Ge => true,
1262 | BinOpKind::Shr => false,
1266 /// Returns `true` if the binary operator takes its arguments by value.
1267 pub fn is_by_value(self) -> bool {
1268 !self.is_comparison()
1272 impl Into<ast::BinOpKind> for BinOpKind {
1273 fn into(self) -> ast::BinOpKind {
1275 BinOpKind::Add => ast::BinOpKind::Add,
1276 BinOpKind::Sub => ast::BinOpKind::Sub,
1277 BinOpKind::Mul => ast::BinOpKind::Mul,
1278 BinOpKind::Div => ast::BinOpKind::Div,
1279 BinOpKind::Rem => ast::BinOpKind::Rem,
1280 BinOpKind::And => ast::BinOpKind::And,
1281 BinOpKind::Or => ast::BinOpKind::Or,
1282 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1283 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1284 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1285 BinOpKind::Shl => ast::BinOpKind::Shl,
1286 BinOpKind::Shr => ast::BinOpKind::Shr,
1287 BinOpKind::Eq => ast::BinOpKind::Eq,
1288 BinOpKind::Lt => ast::BinOpKind::Lt,
1289 BinOpKind::Le => ast::BinOpKind::Le,
1290 BinOpKind::Ne => ast::BinOpKind::Ne,
1291 BinOpKind::Ge => ast::BinOpKind::Ge,
1292 BinOpKind::Gt => ast::BinOpKind::Gt,
1297 pub type BinOp = Spanned<BinOpKind>;
1299 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1301 /// The `*` operator (dereferencing).
1303 /// The `!` operator (logical negation).
1305 /// The `-` operator (negation).
1310 pub fn as_str(self) -> &'static str {
1318 /// Returns `true` if the unary operator takes its argument by value.
1319 pub fn is_by_value(self) -> bool {
1320 matches!(self, Self::Neg | Self::Not)
1325 #[derive(Debug, HashStable_Generic)]
1326 pub struct Stmt<'hir> {
1328 pub kind: StmtKind<'hir>,
1332 /// The contents of a statement.
1333 #[derive(Debug, HashStable_Generic)]
1334 pub enum StmtKind<'hir> {
1335 /// A local (`let`) binding.
1336 Local(&'hir Local<'hir>),
1338 /// An item binding.
1341 /// An expression without a trailing semi-colon (must have unit type).
1342 Expr(&'hir Expr<'hir>),
1344 /// An expression with a trailing semi-colon (may have any type).
1345 Semi(&'hir Expr<'hir>),
1348 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <init>;`).
1349 #[derive(Debug, HashStable_Generic)]
1350 pub struct Local<'hir> {
1351 pub pat: &'hir Pat<'hir>,
1352 /// Type annotation, if any (otherwise the type will be inferred).
1353 pub ty: Option<&'hir Ty<'hir>>,
1354 /// Initializer expression to set the value, if any.
1355 pub init: Option<&'hir Expr<'hir>>,
1356 /// Else block for a `let...else` binding.
1357 pub els: Option<&'hir Block<'hir>>,
1360 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1361 /// desugaring. Otherwise will be `Normal`.
1362 pub source: LocalSource,
1365 /// Represents a single arm of a `match` expression, e.g.
1366 /// `<pat> (if <guard>) => <body>`.
1367 #[derive(Debug, HashStable_Generic)]
1368 pub struct Arm<'hir> {
1369 #[stable_hasher(ignore)]
1372 /// If this pattern and the optional guard matches, then `body` is evaluated.
1373 pub pat: &'hir Pat<'hir>,
1374 /// Optional guard clause.
1375 pub guard: Option<Guard<'hir>>,
1376 /// The expression the arm evaluates to if this arm matches.
1377 pub body: &'hir Expr<'hir>,
1380 /// Represents a `let <pat>[: <ty>] = <expr>` expression (not a Local), occurring in an `if-let` or
1381 /// `let-else`, evaluating to a boolean. Typically the pattern is refutable.
1383 /// In an if-let, imagine it as `if (let <pat> = <expr>) { ... }`; in a let-else, it is part of the
1384 /// desugaring to if-let. Only let-else supports the type annotation at present.
1385 #[derive(Debug, HashStable_Generic)]
1386 pub struct Let<'hir> {
1389 pub pat: &'hir Pat<'hir>,
1390 pub ty: Option<&'hir Ty<'hir>>,
1391 pub init: &'hir Expr<'hir>,
1394 #[derive(Debug, HashStable_Generic)]
1395 pub enum Guard<'hir> {
1396 If(&'hir Expr<'hir>),
1397 IfLet(&'hir Let<'hir>),
1400 impl<'hir> Guard<'hir> {
1401 /// Returns the body of the guard
1403 /// In other words, returns the e in either of the following:
1406 /// - `if let x = e`
1407 pub fn body(&self) -> &'hir Expr<'hir> {
1409 Guard::If(e) | Guard::IfLet(Let { init: e, .. }) => e,
1414 #[derive(Debug, HashStable_Generic)]
1415 pub struct ExprField<'hir> {
1416 #[stable_hasher(ignore)]
1419 pub expr: &'hir Expr<'hir>,
1421 pub is_shorthand: bool,
1424 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1425 pub enum BlockCheckMode {
1427 UnsafeBlock(UnsafeSource),
1430 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1431 pub enum UnsafeSource {
1436 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
1441 /// The body of a function, closure, or constant value. In the case of
1442 /// a function, the body contains not only the function body itself
1443 /// (which is an expression), but also the argument patterns, since
1444 /// those are something that the caller doesn't really care about.
1449 /// fn foo((x, y): (u32, u32)) -> u32 {
1454 /// Here, the `Body` associated with `foo()` would contain:
1456 /// - an `params` array containing the `(x, y)` pattern
1457 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1458 /// - `generator_kind` would be `None`
1460 /// All bodies have an **owner**, which can be accessed via the HIR
1461 /// map using `body_owner_def_id()`.
1462 #[derive(Debug, HashStable_Generic)]
1463 pub struct Body<'hir> {
1464 pub params: &'hir [Param<'hir>],
1465 pub value: &'hir Expr<'hir>,
1466 pub generator_kind: Option<GeneratorKind>,
1469 impl<'hir> Body<'hir> {
1470 pub fn id(&self) -> BodyId {
1471 BodyId { hir_id: self.value.hir_id }
1474 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1479 /// The type of source expression that caused this generator to be created.
1480 #[derive(Clone, PartialEq, PartialOrd, Eq, Hash, Debug, Copy)]
1481 #[derive(HashStable_Generic, Encodable, Decodable)]
1482 pub enum GeneratorKind {
1483 /// An explicit `async` block or the body of an async function.
1484 Async(AsyncGeneratorKind),
1486 /// A generator literal created via a `yield` inside a closure.
1490 impl fmt::Display for GeneratorKind {
1491 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1493 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1494 GeneratorKind::Gen => f.write_str("generator"),
1499 impl GeneratorKind {
1500 pub fn descr(&self) -> &'static str {
1502 GeneratorKind::Async(ask) => ask.descr(),
1503 GeneratorKind::Gen => "generator",
1508 /// In the case of a generator created as part of an async construct,
1509 /// which kind of async construct caused it to be created?
1511 /// This helps error messages but is also used to drive coercions in
1512 /// type-checking (see #60424).
1513 #[derive(Clone, PartialEq, PartialOrd, Eq, Hash, Debug, Copy)]
1514 #[derive(HashStable_Generic, Encodable, Decodable)]
1515 pub enum AsyncGeneratorKind {
1516 /// An explicit `async` block written by the user.
1519 /// An explicit `async` closure written by the user.
1522 /// The `async` block generated as the body of an async function.
1526 impl fmt::Display for AsyncGeneratorKind {
1527 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1528 f.write_str(match self {
1529 AsyncGeneratorKind::Block => "async block",
1530 AsyncGeneratorKind::Closure => "async closure body",
1531 AsyncGeneratorKind::Fn => "async fn body",
1536 impl AsyncGeneratorKind {
1537 pub fn descr(&self) -> &'static str {
1539 AsyncGeneratorKind::Block => "`async` block",
1540 AsyncGeneratorKind::Closure => "`async` closure body",
1541 AsyncGeneratorKind::Fn => "`async fn` body",
1546 #[derive(Copy, Clone, Debug)]
1547 pub enum BodyOwnerKind {
1548 /// Functions and methods.
1554 /// Constants and associated constants.
1557 /// Initializer of a `static` item.
1561 impl BodyOwnerKind {
1562 pub fn is_fn_or_closure(self) -> bool {
1564 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1565 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1570 /// The kind of an item that requires const-checking.
1571 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1572 pub enum ConstContext {
1576 /// A `static` or `static mut`.
1579 /// A `const`, associated `const`, or other const context.
1581 /// Other contexts include:
1582 /// - Array length expressions
1583 /// - Enum discriminants
1584 /// - Const generics
1586 /// For the most part, other contexts are treated just like a regular `const`, so they are
1587 /// lumped into the same category.
1592 /// A description of this const context that can appear between backticks in an error message.
1594 /// E.g. `const` or `static mut`.
1595 pub fn keyword_name(self) -> &'static str {
1597 Self::Const => "const",
1598 Self::Static(Mutability::Not) => "static",
1599 Self::Static(Mutability::Mut) => "static mut",
1600 Self::ConstFn => "const fn",
1605 /// A colloquial, trivially pluralizable description of this const context for use in error
1607 impl fmt::Display for ConstContext {
1608 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1610 Self::Const => write!(f, "constant"),
1611 Self::Static(_) => write!(f, "static"),
1612 Self::ConstFn => write!(f, "constant function"),
1617 // NOTE: `IntoDiagnosticArg` impl for `ConstContext` lives in `rustc_errors`
1618 // due to a cyclical dependency between hir that crate.
1621 pub type Lit = Spanned<LitKind>;
1623 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1630 pub fn hir_id(&self) -> HirId {
1632 &ArrayLen::Infer(hir_id, _) | &ArrayLen::Body(AnonConst { hir_id, .. }) => hir_id,
1637 /// A constant (expression) that's not an item or associated item,
1638 /// but needs its own `DefId` for type-checking, const-eval, etc.
1639 /// These are usually found nested inside types (e.g., array lengths)
1640 /// or expressions (e.g., repeat counts), and also used to define
1641 /// explicit discriminant values for enum variants.
1643 /// You can check if this anon const is a default in a const param
1644 /// `const N: usize = { ... }` with `tcx.hir().opt_const_param_default_param_def_id(..)`
1645 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1646 pub struct AnonConst {
1648 pub def_id: LocalDefId,
1653 #[derive(Debug, HashStable_Generic)]
1654 pub struct Expr<'hir> {
1656 pub kind: ExprKind<'hir>,
1661 pub fn precedence(&self) -> ExprPrecedence {
1663 ExprKind::Box(_) => ExprPrecedence::Box,
1664 ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1665 ExprKind::Array(_) => ExprPrecedence::Array,
1666 ExprKind::Call(..) => ExprPrecedence::Call,
1667 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1668 ExprKind::Tup(_) => ExprPrecedence::Tup,
1669 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1670 ExprKind::Unary(..) => ExprPrecedence::Unary,
1671 ExprKind::Lit(_) => ExprPrecedence::Lit,
1672 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1673 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1674 ExprKind::If(..) => ExprPrecedence::If,
1675 ExprKind::Let(..) => ExprPrecedence::Let,
1676 ExprKind::Loop(..) => ExprPrecedence::Loop,
1677 ExprKind::Match(..) => ExprPrecedence::Match,
1678 ExprKind::Closure { .. } => ExprPrecedence::Closure,
1679 ExprKind::Block(..) => ExprPrecedence::Block,
1680 ExprKind::Assign(..) => ExprPrecedence::Assign,
1681 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1682 ExprKind::Field(..) => ExprPrecedence::Field,
1683 ExprKind::Index(..) => ExprPrecedence::Index,
1684 ExprKind::Path(..) => ExprPrecedence::Path,
1685 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1686 ExprKind::Break(..) => ExprPrecedence::Break,
1687 ExprKind::Continue(..) => ExprPrecedence::Continue,
1688 ExprKind::Ret(..) => ExprPrecedence::Ret,
1689 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1690 ExprKind::Struct(..) => ExprPrecedence::Struct,
1691 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1692 ExprKind::Yield(..) => ExprPrecedence::Yield,
1693 ExprKind::Err => ExprPrecedence::Err,
1697 /// Whether this looks like a place expr, without checking for deref
1699 /// This will return `true` in some potentially surprising cases such as
1700 /// `CONSTANT.field`.
1701 pub fn is_syntactic_place_expr(&self) -> bool {
1702 self.is_place_expr(|_| true)
1705 /// Whether this is a place expression.
1707 /// `allow_projections_from` should return `true` if indexing a field or index expression based
1708 /// on the given expression should be considered a place expression.
1709 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1711 ExprKind::Path(QPath::Resolved(_, ref path)) => {
1712 matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static(_), _) | Res::Err)
1715 // Type ascription inherits its place expression kind from its
1717 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1718 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1720 ExprKind::Unary(UnOp::Deref, _) => true,
1722 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1723 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1726 // Lang item paths cannot currently be local variables or statics.
1727 ExprKind::Path(QPath::LangItem(..)) => false,
1729 // Partially qualified paths in expressions can only legally
1730 // refer to associated items which are always rvalues.
1731 ExprKind::Path(QPath::TypeRelative(..))
1732 | ExprKind::Call(..)
1733 | ExprKind::MethodCall(..)
1734 | ExprKind::Struct(..)
1737 | ExprKind::Match(..)
1738 | ExprKind::Closure { .. }
1739 | ExprKind::Block(..)
1740 | ExprKind::Repeat(..)
1741 | ExprKind::Array(..)
1742 | ExprKind::Break(..)
1743 | ExprKind::Continue(..)
1746 | ExprKind::Loop(..)
1747 | ExprKind::Assign(..)
1748 | ExprKind::InlineAsm(..)
1749 | ExprKind::AssignOp(..)
1751 | ExprKind::ConstBlock(..)
1752 | ExprKind::Unary(..)
1754 | ExprKind::AddrOf(..)
1755 | ExprKind::Binary(..)
1756 | ExprKind::Yield(..)
1757 | ExprKind::Cast(..)
1758 | ExprKind::DropTemps(..)
1759 | ExprKind::Err => false,
1763 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1764 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1765 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1766 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1767 /// beyond remembering to call this function before doing analysis on it.
1768 pub fn peel_drop_temps(&self) -> &Self {
1769 let mut expr = self;
1770 while let ExprKind::DropTemps(inner) = &expr.kind {
1776 pub fn peel_blocks(&self) -> &Self {
1777 let mut expr = self;
1778 while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind {
1784 pub fn can_have_side_effects(&self) -> bool {
1785 match self.peel_drop_temps().kind {
1786 ExprKind::Path(_) | ExprKind::Lit(_) => false,
1787 ExprKind::Type(base, _)
1788 | ExprKind::Unary(_, base)
1789 | ExprKind::Field(base, _)
1790 | ExprKind::Index(base, _)
1791 | ExprKind::AddrOf(.., base)
1792 | ExprKind::Cast(base, _) => {
1793 // This isn't exactly true for `Index` and all `Unary`, but we are using this
1794 // method exclusively for diagnostics and there's a *cultural* pressure against
1795 // them being used only for its side-effects.
1796 base.can_have_side_effects()
1798 ExprKind::Struct(_, fields, init) => fields
1800 .map(|field| field.expr)
1801 .chain(init.into_iter())
1802 .all(|e| e.can_have_side_effects()),
1804 ExprKind::Array(args)
1805 | ExprKind::Tup(args)
1809 ExprKind::Path(QPath::Resolved(
1811 Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. },
1816 ) => args.iter().all(|arg| arg.can_have_side_effects()),
1818 | ExprKind::Match(..)
1819 | ExprKind::MethodCall(..)
1820 | ExprKind::Call(..)
1821 | ExprKind::Closure { .. }
1822 | ExprKind::Block(..)
1823 | ExprKind::Repeat(..)
1824 | ExprKind::Break(..)
1825 | ExprKind::Continue(..)
1828 | ExprKind::Loop(..)
1829 | ExprKind::Assign(..)
1830 | ExprKind::InlineAsm(..)
1831 | ExprKind::AssignOp(..)
1832 | ExprKind::ConstBlock(..)
1834 | ExprKind::Binary(..)
1835 | ExprKind::Yield(..)
1836 | ExprKind::DropTemps(..)
1837 | ExprKind::Err => true,
1841 /// To a first-order approximation, is this a pattern?
1842 pub fn is_approximately_pattern(&self) -> bool {
1845 | ExprKind::Array(_)
1846 | ExprKind::Call(..)
1850 | ExprKind::Struct(..) => true,
1855 pub fn method_ident(&self) -> Option<Ident> {
1857 ExprKind::MethodCall(receiver_method, ..) => Some(receiver_method.ident),
1858 ExprKind::Unary(_, expr) | ExprKind::AddrOf(.., expr) => expr.method_ident(),
1864 /// Checks if the specified expression is a built-in range literal.
1865 /// (See: `LoweringContext::lower_expr()`).
1866 pub fn is_range_literal(expr: &Expr<'_>) -> bool {
1868 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1869 ExprKind::Struct(ref qpath, _, _) => matches!(
1874 | LangItem::RangeFrom
1875 | LangItem::RangeFull
1876 | LangItem::RangeToInclusive,
1881 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1882 ExprKind::Call(ref func, _) => {
1883 matches!(func.kind, ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, ..)))
1890 #[derive(Debug, HashStable_Generic)]
1891 pub enum ExprKind<'hir> {
1892 /// A `box x` expression.
1893 Box(&'hir Expr<'hir>),
1894 /// Allow anonymous constants from an inline `const` block
1895 ConstBlock(AnonConst),
1896 /// An array (e.g., `[a, b, c, d]`).
1897 Array(&'hir [Expr<'hir>]),
1898 /// A function call.
1900 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1901 /// and the second field is the list of arguments.
1902 /// This also represents calling the constructor of
1903 /// tuple-like ADTs such as tuple structs and enum variants.
1904 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1905 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1907 /// The `PathSegment` represents the method name and its generic arguments
1908 /// (within the angle brackets).
1909 /// The `&Expr` is the expression that evaluates
1910 /// to the object on which the method is being called on (the receiver),
1911 /// and the `&[Expr]` is the rest of the arguments.
1912 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1913 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, x, [a, b, c, d], span)`.
1914 /// The final `Span` represents the span of the function and arguments
1915 /// (e.g. `foo::<Bar, Baz>(a, b, c, d)` in `x.foo::<Bar, Baz>(a, b, c, d)`
1917 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1918 /// the `hir_id` of the `MethodCall` node itself.
1920 /// [`type_dependent_def_id`]: ../../rustc_middle/ty/struct.TypeckResults.html#method.type_dependent_def_id
1921 MethodCall(&'hir PathSegment<'hir>, &'hir Expr<'hir>, &'hir [Expr<'hir>], Span),
1922 /// A tuple (e.g., `(a, b, c, d)`).
1923 Tup(&'hir [Expr<'hir>]),
1924 /// A binary operation (e.g., `a + b`, `a * b`).
1925 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1926 /// A unary operation (e.g., `!x`, `*x`).
1927 Unary(UnOp, &'hir Expr<'hir>),
1928 /// A literal (e.g., `1`, `"foo"`).
1930 /// A cast (e.g., `foo as f64`).
1931 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1932 /// A type reference (e.g., `Foo`).
1933 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1934 /// Wraps the expression in a terminating scope.
1935 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1937 /// This construct only exists to tweak the drop order in HIR lowering.
1938 /// An example of that is the desugaring of `for` loops.
1939 DropTemps(&'hir Expr<'hir>),
1940 /// A `let $pat = $expr` expression.
1942 /// These are not `Local` and only occur as expressions.
1943 /// The `let Some(x) = foo()` in `if let Some(x) = foo()` is an example of `Let(..)`.
1944 Let(&'hir Let<'hir>),
1945 /// An `if` block, with an optional else block.
1947 /// I.e., `if <expr> { <expr> } else { <expr> }`.
1948 If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
1949 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1951 /// I.e., `'label: loop { <block> }`.
1953 /// The `Span` is the loop header (`for x in y`/`while let pat = expr`).
1954 Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span),
1955 /// A `match` block, with a source that indicates whether or not it is
1956 /// the result of a desugaring, and if so, which kind.
1957 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1958 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1960 /// The `Span` is the argument block `|...|`.
1962 /// This may also be a generator literal or an `async block` as indicated by the
1963 /// `Option<Movability>`.
1964 Closure(&'hir Closure<'hir>),
1965 /// A block (e.g., `'label: { ... }`).
1966 Block(&'hir Block<'hir>, Option<Label>),
1968 /// An assignment (e.g., `a = foo()`).
1969 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1970 /// An assignment with an operator.
1973 AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1974 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1975 Field(&'hir Expr<'hir>, Ident),
1976 /// An indexing operation (`foo[2]`).
1977 Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1979 /// Path to a definition, possibly containing lifetime or type parameters.
1982 /// A referencing operation (i.e., `&a` or `&mut a`).
1983 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1984 /// A `break`, with an optional label to break.
1985 Break(Destination, Option<&'hir Expr<'hir>>),
1986 /// A `continue`, with an optional label.
1987 Continue(Destination),
1988 /// A `return`, with an optional value to be returned.
1989 Ret(Option<&'hir Expr<'hir>>),
1991 /// Inline assembly (from `asm!`), with its outputs and inputs.
1992 InlineAsm(&'hir InlineAsm<'hir>),
1994 /// A struct or struct-like variant literal expression.
1996 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1997 /// where `base` is the `Option<Expr>`.
1998 Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], Option<&'hir Expr<'hir>>),
2000 /// An array literal constructed from one repeated element.
2002 /// E.g., `[1; 5]`. The first expression is the element
2003 /// to be repeated; the second is the number of times to repeat it.
2004 Repeat(&'hir Expr<'hir>, ArrayLen),
2006 /// A suspension point for generators (i.e., `yield <expr>`).
2007 Yield(&'hir Expr<'hir>, YieldSource),
2009 /// A placeholder for an expression that wasn't syntactically well formed in some way.
2013 /// Represents an optionally `Self`-qualified value/type path or associated extension.
2015 /// To resolve the path to a `DefId`, call [`qpath_res`].
2017 /// [`qpath_res`]: ../../rustc_middle/ty/struct.TypeckResults.html#method.qpath_res
2018 #[derive(Debug, HashStable_Generic)]
2019 pub enum QPath<'hir> {
2020 /// Path to a definition, optionally "fully-qualified" with a `Self`
2021 /// type, if the path points to an associated item in a trait.
2023 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
2024 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
2025 /// even though they both have the same two-segment `Clone::clone` `Path`.
2026 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
2028 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
2029 /// Will be resolved by type-checking to an associated item.
2031 /// UFCS source paths can desugar into this, with `Vec::new` turning into
2032 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
2033 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
2034 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
2036 /// Reference to a `#[lang = "foo"]` item. `HirId` of the inner expr.
2037 LangItem(LangItem, Span, Option<HirId>),
2040 impl<'hir> QPath<'hir> {
2041 /// Returns the span of this `QPath`.
2042 pub fn span(&self) -> Span {
2044 QPath::Resolved(_, path) => path.span,
2045 QPath::TypeRelative(qself, ps) => qself.span.to(ps.ident.span),
2046 QPath::LangItem(_, span, _) => span,
2050 /// Returns the span of the qself of this `QPath`. For example, `()` in
2051 /// `<() as Trait>::method`.
2052 pub fn qself_span(&self) -> Span {
2054 QPath::Resolved(_, path) => path.span,
2055 QPath::TypeRelative(qself, _) => qself.span,
2056 QPath::LangItem(_, span, _) => span,
2060 /// Returns the span of the last segment of this `QPath`. For example, `method` in
2061 /// `<() as Trait>::method`.
2062 pub fn last_segment_span(&self) -> Span {
2064 QPath::Resolved(_, path) => path.segments.last().unwrap().ident.span,
2065 QPath::TypeRelative(_, segment) => segment.ident.span,
2066 QPath::LangItem(_, span, _) => span,
2071 /// Hints at the original code for a let statement.
2072 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2073 pub enum LocalSource {
2074 /// A `match _ { .. }`.
2076 /// When lowering async functions, we create locals within the `async move` so that
2077 /// all parameters are dropped after the future is polled.
2079 /// ```ignore (pseudo-Rust)
2080 /// async fn foo(<pattern> @ x: Type) {
2082 /// let <pattern> = x;
2087 /// A desugared `<expr>.await`.
2089 /// A desugared `expr = expr`, where the LHS is a tuple, struct or array.
2090 /// The span is that of the `=` sign.
2091 AssignDesugar(Span),
2094 /// Hints at the original code for a `match _ { .. }`.
2095 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
2096 #[derive(HashStable_Generic)]
2097 pub enum MatchSource {
2098 /// A `match _ { .. }`.
2100 /// A desugared `for _ in _ { .. }` loop.
2102 /// A desugared `?` operator.
2104 /// A desugared `<expr>.await`.
2110 pub const fn name(self) -> &'static str {
2114 ForLoopDesugar => "for",
2116 AwaitDesugar => ".await",
2121 /// The loop type that yielded an `ExprKind::Loop`.
2122 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2123 pub enum LoopSource {
2124 /// A `loop { .. }` loop.
2126 /// A `while _ { .. }` loop.
2128 /// A `for _ in _ { .. }` loop.
2133 pub fn name(self) -> &'static str {
2135 LoopSource::Loop => "loop",
2136 LoopSource::While => "while",
2137 LoopSource::ForLoop => "for",
2142 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2143 pub enum LoopIdError {
2145 UnlabeledCfInWhileCondition,
2149 impl fmt::Display for LoopIdError {
2150 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2151 f.write_str(match self {
2152 LoopIdError::OutsideLoopScope => "not inside loop scope",
2153 LoopIdError::UnlabeledCfInWhileCondition => {
2154 "unlabeled control flow (break or continue) in while condition"
2156 LoopIdError::UnresolvedLabel => "label not found",
2161 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2162 pub struct Destination {
2163 /// This is `Some(_)` iff there is an explicit user-specified 'label
2164 pub label: Option<Label>,
2166 /// These errors are caught and then reported during the diagnostics pass in
2167 /// `librustc_passes/loops.rs`
2168 pub target_id: Result<HirId, LoopIdError>,
2171 /// The yield kind that caused an `ExprKind::Yield`.
2172 #[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
2173 pub enum YieldSource {
2174 /// An `<expr>.await`.
2175 Await { expr: Option<HirId> },
2176 /// A plain `yield`.
2181 pub fn is_await(&self) -> bool {
2182 matches!(self, YieldSource::Await { .. })
2186 impl fmt::Display for YieldSource {
2187 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2188 f.write_str(match self {
2189 YieldSource::Await { .. } => "`await`",
2190 YieldSource::Yield => "`yield`",
2195 impl From<GeneratorKind> for YieldSource {
2196 fn from(kind: GeneratorKind) -> Self {
2198 // Guess based on the kind of the current generator.
2199 GeneratorKind::Gen => Self::Yield,
2200 GeneratorKind::Async(_) => Self::Await { expr: None },
2205 // N.B., if you change this, you'll probably want to change the corresponding
2206 // type structure in middle/ty.rs as well.
2207 #[derive(Debug, HashStable_Generic)]
2208 pub struct MutTy<'hir> {
2209 pub ty: &'hir Ty<'hir>,
2210 pub mutbl: Mutability,
2213 /// Represents a function's signature in a trait declaration,
2214 /// trait implementation, or a free function.
2215 #[derive(Debug, HashStable_Generic)]
2216 pub struct FnSig<'hir> {
2217 pub header: FnHeader,
2218 pub decl: &'hir FnDecl<'hir>,
2222 // The bodies for items are stored "out of line", in a separate
2223 // hashmap in the `Crate`. Here we just record the hir-id of the item
2224 // so it can fetched later.
2225 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2226 pub struct TraitItemId {
2227 pub owner_id: OwnerId,
2232 pub fn hir_id(&self) -> HirId {
2233 // Items are always HIR owners.
2234 HirId::make_owner(self.owner_id.def_id)
2238 /// Represents an item declaration within a trait declaration,
2239 /// possibly including a default implementation. A trait item is
2240 /// either required (meaning it doesn't have an implementation, just a
2241 /// signature) or provided (meaning it has a default implementation).
2242 #[derive(Debug, HashStable_Generic)]
2243 pub struct TraitItem<'hir> {
2245 pub owner_id: OwnerId,
2246 pub generics: &'hir Generics<'hir>,
2247 pub kind: TraitItemKind<'hir>,
2249 pub defaultness: Defaultness,
2252 impl TraitItem<'_> {
2254 pub fn hir_id(&self) -> HirId {
2255 // Items are always HIR owners.
2256 HirId::make_owner(self.owner_id.def_id)
2259 pub fn trait_item_id(&self) -> TraitItemId {
2260 TraitItemId { owner_id: self.owner_id }
2264 /// Represents a trait method's body (or just argument names).
2265 #[derive(Encodable, Debug, HashStable_Generic)]
2266 pub enum TraitFn<'hir> {
2267 /// No default body in the trait, just a signature.
2268 Required(&'hir [Ident]),
2270 /// Both signature and body are provided in the trait.
2274 /// Represents a trait method or associated constant or type
2275 #[derive(Debug, HashStable_Generic)]
2276 pub enum TraitItemKind<'hir> {
2277 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
2278 Const(&'hir Ty<'hir>, Option<BodyId>),
2279 /// An associated function with an optional body.
2280 Fn(FnSig<'hir>, TraitFn<'hir>),
2281 /// An associated type with (possibly empty) bounds and optional concrete
2283 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
2286 // The bodies for items are stored "out of line", in a separate
2287 // hashmap in the `Crate`. Here we just record the hir-id of the item
2288 // so it can fetched later.
2289 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2290 pub struct ImplItemId {
2291 pub owner_id: OwnerId,
2296 pub fn hir_id(&self) -> HirId {
2297 // Items are always HIR owners.
2298 HirId::make_owner(self.owner_id.def_id)
2302 /// Represents anything within an `impl` block.
2303 #[derive(Debug, HashStable_Generic)]
2304 pub struct ImplItem<'hir> {
2306 pub owner_id: OwnerId,
2307 pub generics: &'hir Generics<'hir>,
2308 pub kind: ImplItemKind<'hir>,
2309 pub defaultness: Defaultness,
2316 pub fn hir_id(&self) -> HirId {
2317 // Items are always HIR owners.
2318 HirId::make_owner(self.owner_id.def_id)
2321 pub fn impl_item_id(&self) -> ImplItemId {
2322 ImplItemId { owner_id: self.owner_id }
2326 /// Represents various kinds of content within an `impl`.
2327 #[derive(Debug, HashStable_Generic)]
2328 pub enum ImplItemKind<'hir> {
2329 /// An associated constant of the given type, set to the constant result
2330 /// of the expression.
2331 Const(&'hir Ty<'hir>, BodyId),
2332 /// An associated function implementation with the given signature and body.
2333 Fn(FnSig<'hir>, BodyId),
2334 /// An associated type.
2335 Type(&'hir Ty<'hir>),
2338 /// The name of the associated type for `Fn` return types.
2339 pub const FN_OUTPUT_NAME: Symbol = sym::Output;
2341 /// Bind a type to an associated type (i.e., `A = Foo`).
2343 /// Bindings like `A: Debug` are represented as a special type `A =
2344 /// $::Debug` that is understood by the astconv code.
2346 /// FIXME(alexreg): why have a separate type for the binding case,
2347 /// wouldn't it be better to make the `ty` field an enum like the
2350 /// ```ignore (pseudo-rust)
2351 /// enum TypeBindingKind {
2356 #[derive(Debug, HashStable_Generic)]
2357 pub struct TypeBinding<'hir> {
2360 pub gen_args: &'hir GenericArgs<'hir>,
2361 pub kind: TypeBindingKind<'hir>,
2365 #[derive(Debug, HashStable_Generic)]
2366 pub enum Term<'hir> {
2371 impl<'hir> From<&'hir Ty<'hir>> for Term<'hir> {
2372 fn from(ty: &'hir Ty<'hir>) -> Self {
2377 impl<'hir> From<AnonConst> for Term<'hir> {
2378 fn from(c: AnonConst) -> Self {
2383 // Represents the two kinds of type bindings.
2384 #[derive(Debug, HashStable_Generic)]
2385 pub enum TypeBindingKind<'hir> {
2386 /// E.g., `Foo<Bar: Send>`.
2387 Constraint { bounds: &'hir [GenericBound<'hir>] },
2388 /// E.g., `Foo<Bar = ()>`, `Foo<Bar = ()>`
2389 Equality { term: Term<'hir> },
2392 impl TypeBinding<'_> {
2393 pub fn ty(&self) -> &Ty<'_> {
2395 TypeBindingKind::Equality { term: Term::Ty(ref ty) } => ty,
2396 _ => panic!("expected equality type binding for parenthesized generic args"),
2399 pub fn opt_const(&self) -> Option<&'_ AnonConst> {
2401 TypeBindingKind::Equality { term: Term::Const(ref c) } => Some(c),
2407 #[derive(Debug, HashStable_Generic)]
2408 pub struct Ty<'hir> {
2410 pub kind: TyKind<'hir>,
2414 impl<'hir> Ty<'hir> {
2415 /// Returns `true` if `param_def_id` matches the `bounded_ty` of this predicate.
2416 pub fn as_generic_param(&self) -> Option<(DefId, Ident)> {
2417 let TyKind::Path(QPath::Resolved(None, path)) = self.kind else {
2420 let [segment] = &path.segments else {
2424 Res::Def(DefKind::TyParam, def_id) | Res::SelfTyParam { trait_: def_id } => {
2425 Some((def_id, segment.ident))
2431 pub fn peel_refs(&self) -> &Self {
2432 let mut final_ty = self;
2433 while let TyKind::Rptr(_, MutTy { ty, .. }) = &final_ty.kind {
2439 pub fn find_self_aliases(&self) -> Vec<Span> {
2440 use crate::intravisit::Visitor;
2441 struct MyVisitor(Vec<Span>);
2442 impl<'v> Visitor<'v> for MyVisitor {
2443 fn visit_ty(&mut self, t: &'v Ty<'v>) {
2446 TyKind::Path(QPath::Resolved(
2448 Path { res: crate::def::Res::SelfTyAlias { .. }, .. },
2451 self.0.push(t.span);
2454 crate::intravisit::walk_ty(self, t);
2458 let mut my_visitor = MyVisitor(vec![]);
2459 my_visitor.visit_ty(self);
2464 /// Not represented directly in the AST; referred to by name through a `ty_path`.
2465 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
2466 #[derive(HashStable_Generic)]
2477 /// All of the primitive types
2478 pub const ALL: [Self; 17] = [
2479 // any changes here should also be reflected in `PrimTy::from_name`
2480 Self::Int(IntTy::I8),
2481 Self::Int(IntTy::I16),
2482 Self::Int(IntTy::I32),
2483 Self::Int(IntTy::I64),
2484 Self::Int(IntTy::I128),
2485 Self::Int(IntTy::Isize),
2486 Self::Uint(UintTy::U8),
2487 Self::Uint(UintTy::U16),
2488 Self::Uint(UintTy::U32),
2489 Self::Uint(UintTy::U64),
2490 Self::Uint(UintTy::U128),
2491 Self::Uint(UintTy::Usize),
2492 Self::Float(FloatTy::F32),
2493 Self::Float(FloatTy::F64),
2499 /// Like [`PrimTy::name`], but returns a &str instead of a symbol.
2502 pub fn name_str(self) -> &'static str {
2504 PrimTy::Int(i) => i.name_str(),
2505 PrimTy::Uint(u) => u.name_str(),
2506 PrimTy::Float(f) => f.name_str(),
2507 PrimTy::Str => "str",
2508 PrimTy::Bool => "bool",
2509 PrimTy::Char => "char",
2513 pub fn name(self) -> Symbol {
2515 PrimTy::Int(i) => i.name(),
2516 PrimTy::Uint(u) => u.name(),
2517 PrimTy::Float(f) => f.name(),
2518 PrimTy::Str => sym::str,
2519 PrimTy::Bool => sym::bool,
2520 PrimTy::Char => sym::char,
2524 /// Returns the matching `PrimTy` for a `Symbol` such as "str" or "i32".
2525 /// Returns `None` if no matching type is found.
2526 pub fn from_name(name: Symbol) -> Option<Self> {
2527 let ty = match name {
2528 // any changes here should also be reflected in `PrimTy::ALL`
2529 sym::i8 => Self::Int(IntTy::I8),
2530 sym::i16 => Self::Int(IntTy::I16),
2531 sym::i32 => Self::Int(IntTy::I32),
2532 sym::i64 => Self::Int(IntTy::I64),
2533 sym::i128 => Self::Int(IntTy::I128),
2534 sym::isize => Self::Int(IntTy::Isize),
2535 sym::u8 => Self::Uint(UintTy::U8),
2536 sym::u16 => Self::Uint(UintTy::U16),
2537 sym::u32 => Self::Uint(UintTy::U32),
2538 sym::u64 => Self::Uint(UintTy::U64),
2539 sym::u128 => Self::Uint(UintTy::U128),
2540 sym::usize => Self::Uint(UintTy::Usize),
2541 sym::f32 => Self::Float(FloatTy::F32),
2542 sym::f64 => Self::Float(FloatTy::F64),
2543 sym::bool => Self::Bool,
2544 sym::char => Self::Char,
2545 sym::str => Self::Str,
2552 #[derive(Debug, HashStable_Generic)]
2553 pub struct BareFnTy<'hir> {
2554 pub unsafety: Unsafety,
2556 pub generic_params: &'hir [GenericParam<'hir>],
2557 pub decl: &'hir FnDecl<'hir>,
2558 pub param_names: &'hir [Ident],
2561 #[derive(Debug, HashStable_Generic)]
2562 pub struct OpaqueTy<'hir> {
2563 pub generics: &'hir Generics<'hir>,
2564 pub bounds: GenericBounds<'hir>,
2565 pub origin: OpaqueTyOrigin,
2569 /// From whence the opaque type came.
2570 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2571 pub enum OpaqueTyOrigin {
2573 FnReturn(LocalDefId),
2575 AsyncFn(LocalDefId),
2576 /// type aliases: `type Foo = impl Trait;`
2580 /// The various kinds of types recognized by the compiler.
2581 #[derive(Debug, HashStable_Generic)]
2582 pub enum TyKind<'hir> {
2583 /// A variable length slice (i.e., `[T]`).
2584 Slice(&'hir Ty<'hir>),
2585 /// A fixed length array (i.e., `[T; n]`).
2586 Array(&'hir Ty<'hir>, ArrayLen),
2587 /// A raw pointer (i.e., `*const T` or `*mut T`).
2589 /// A reference (i.e., `&'a T` or `&'a mut T`).
2590 Rptr(&'hir Lifetime, MutTy<'hir>),
2591 /// A bare function (e.g., `fn(usize) -> bool`).
2592 BareFn(&'hir BareFnTy<'hir>),
2593 /// The never type (`!`).
2595 /// A tuple (`(A, B, C, D, ...)`).
2596 Tup(&'hir [Ty<'hir>]),
2597 /// A path to a type definition (`module::module::...::Type`), or an
2598 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2600 /// Type parameters may be stored in each `PathSegment`.
2602 /// An opaque type definition itself. This is only used for `impl Trait`.
2604 /// The generic argument list contains the lifetimes (and in the future
2605 /// possibly parameters) that are actually bound on the `impl Trait`.
2607 /// The last parameter specifies whether this opaque appears in a trait definition.
2608 OpaqueDef(ItemId, &'hir [GenericArg<'hir>], bool),
2609 /// A trait object type `Bound1 + Bound2 + Bound3`
2610 /// where `Bound` is a trait or a lifetime.
2611 TraitObject(&'hir [PolyTraitRef<'hir>], &'hir Lifetime, TraitObjectSyntax),
2614 /// `TyKind::Infer` means the type should be inferred instead of it having been
2615 /// specified. This can appear anywhere in a type.
2617 /// Placeholder for a type that has failed to be defined.
2621 #[derive(Debug, HashStable_Generic)]
2622 pub enum InlineAsmOperand<'hir> {
2624 reg: InlineAsmRegOrRegClass,
2625 expr: &'hir Expr<'hir>,
2628 reg: InlineAsmRegOrRegClass,
2630 expr: Option<&'hir Expr<'hir>>,
2633 reg: InlineAsmRegOrRegClass,
2635 expr: &'hir Expr<'hir>,
2638 reg: InlineAsmRegOrRegClass,
2640 in_expr: &'hir Expr<'hir>,
2641 out_expr: Option<&'hir Expr<'hir>>,
2644 anon_const: AnonConst,
2647 anon_const: AnonConst,
2655 impl<'hir> InlineAsmOperand<'hir> {
2656 pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
2658 Self::In { reg, .. }
2659 | Self::Out { reg, .. }
2660 | Self::InOut { reg, .. }
2661 | Self::SplitInOut { reg, .. } => Some(reg),
2662 Self::Const { .. } | Self::SymFn { .. } | Self::SymStatic { .. } => None,
2666 pub fn is_clobber(&self) -> bool {
2669 InlineAsmOperand::Out { reg: InlineAsmRegOrRegClass::Reg(_), late: _, expr: None }
2674 #[derive(Debug, HashStable_Generic)]
2675 pub struct InlineAsm<'hir> {
2676 pub template: &'hir [InlineAsmTemplatePiece],
2677 pub template_strs: &'hir [(Symbol, Option<Symbol>, Span)],
2678 pub operands: &'hir [(InlineAsmOperand<'hir>, Span)],
2679 pub options: InlineAsmOptions,
2680 pub line_spans: &'hir [Span],
2683 /// Represents a parameter in a function header.
2684 #[derive(Debug, HashStable_Generic)]
2685 pub struct Param<'hir> {
2687 pub pat: &'hir Pat<'hir>,
2692 /// Represents the header (not the body) of a function declaration.
2693 #[derive(Debug, HashStable_Generic)]
2694 pub struct FnDecl<'hir> {
2695 /// The types of the function's parameters.
2697 /// Additional argument data is stored in the function's [body](Body::params).
2698 pub inputs: &'hir [Ty<'hir>],
2699 pub output: FnRetTy<'hir>,
2700 pub c_variadic: bool,
2701 /// Does the function have an implicit self?
2702 pub implicit_self: ImplicitSelfKind,
2703 /// Is lifetime elision allowed.
2704 pub lifetime_elision_allowed: bool,
2707 /// Represents what type of implicit self a function has, if any.
2708 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2709 pub enum ImplicitSelfKind {
2710 /// Represents a `fn x(self);`.
2712 /// Represents a `fn x(mut self);`.
2714 /// Represents a `fn x(&self);`.
2716 /// Represents a `fn x(&mut self);`.
2718 /// Represents when a function does not have a self argument or
2719 /// when a function has a `self: X` argument.
2723 impl ImplicitSelfKind {
2724 /// Does this represent an implicit self?
2725 pub fn has_implicit_self(&self) -> bool {
2726 !matches!(*self, ImplicitSelfKind::None)
2730 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable, Debug)]
2731 #[derive(HashStable_Generic)]
2738 pub fn is_async(self) -> bool {
2739 self == IsAsync::Async
2743 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable, HashStable_Generic)]
2744 pub enum Defaultness {
2745 Default { has_value: bool },
2750 pub fn has_value(&self) -> bool {
2752 Defaultness::Default { has_value } => has_value,
2753 Defaultness::Final => true,
2757 pub fn is_final(&self) -> bool {
2758 *self == Defaultness::Final
2761 pub fn is_default(&self) -> bool {
2762 matches!(*self, Defaultness::Default { .. })
2766 #[derive(Debug, HashStable_Generic)]
2767 pub enum FnRetTy<'hir> {
2768 /// Return type is not specified.
2770 /// Functions default to `()` and
2771 /// closures default to inference. Span points to where return
2772 /// type would be inserted.
2773 DefaultReturn(Span),
2774 /// Everything else.
2775 Return(&'hir Ty<'hir>),
2780 pub fn span(&self) -> Span {
2782 Self::DefaultReturn(span) => span,
2783 Self::Return(ref ty) => ty.span,
2788 /// Represents `for<...>` binder before a closure
2789 #[derive(Copy, Clone, Debug, HashStable_Generic)]
2790 pub enum ClosureBinder {
2791 /// Binder is not specified.
2793 /// Binder is specified.
2795 /// Span points to the whole `for<...>`.
2799 #[derive(Encodable, Debug, HashStable_Generic)]
2800 pub struct Mod<'hir> {
2801 pub spans: ModSpans,
2802 pub item_ids: &'hir [ItemId],
2805 #[derive(Copy, Clone, Debug, HashStable_Generic, Encodable)]
2806 pub struct ModSpans {
2807 /// A span from the first token past `{` to the last token until `}`.
2808 /// For `mod foo;`, the inner span ranges from the first token
2809 /// to the last token in the external file.
2810 pub inner_span: Span,
2811 pub inject_use_span: Span,
2814 #[derive(Debug, HashStable_Generic)]
2815 pub struct EnumDef<'hir> {
2816 pub variants: &'hir [Variant<'hir>],
2819 #[derive(Debug, HashStable_Generic)]
2820 pub struct Variant<'hir> {
2821 /// Name of the variant.
2823 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2825 pub def_id: LocalDefId,
2826 /// Fields and constructor id of the variant.
2827 pub data: VariantData<'hir>,
2828 /// Explicit discriminant (e.g., `Foo = 1`).
2829 pub disr_expr: Option<AnonConst>,
2834 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2836 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2837 /// Also produced for each element of a list `use`, e.g.
2838 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2841 /// Glob import, e.g., `use foo::*`.
2844 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2845 /// an additional `use foo::{}` for performing checks such as
2846 /// unstable feature gating. May be removed in the future.
2850 /// References to traits in impls.
2852 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2853 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2854 /// trait being referred to but just a unique `HirId` that serves as a key
2855 /// within the resolution map.
2856 #[derive(Clone, Debug, HashStable_Generic)]
2857 pub struct TraitRef<'hir> {
2858 pub path: &'hir Path<'hir>,
2859 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2860 #[stable_hasher(ignore)]
2861 pub hir_ref_id: HirId,
2865 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2866 pub fn trait_def_id(&self) -> Option<DefId> {
2867 match self.path.res {
2868 Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
2870 _ => unreachable!(),
2875 #[derive(Clone, Debug, HashStable_Generic)]
2876 pub struct PolyTraitRef<'hir> {
2877 /// The `'a` in `for<'a> Foo<&'a T>`.
2878 pub bound_generic_params: &'hir [GenericParam<'hir>],
2880 /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
2881 pub trait_ref: TraitRef<'hir>,
2886 #[derive(Debug, HashStable_Generic)]
2887 pub struct FieldDef<'hir> {
2892 pub def_id: LocalDefId,
2893 pub ty: &'hir Ty<'hir>,
2897 // Still necessary in couple of places
2898 pub fn is_positional(&self) -> bool {
2899 let first = self.ident.as_str().as_bytes()[0];
2900 (b'0'..=b'9').contains(&first)
2904 /// Fields and constructor IDs of enum variants and structs.
2905 #[derive(Debug, HashStable_Generic)]
2906 pub enum VariantData<'hir> {
2907 /// A struct variant.
2909 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2910 Struct(&'hir [FieldDef<'hir>], /* recovered */ bool),
2911 /// A tuple variant.
2913 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2914 Tuple(&'hir [FieldDef<'hir>], HirId, LocalDefId),
2917 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2918 Unit(HirId, LocalDefId),
2921 impl<'hir> VariantData<'hir> {
2922 /// Return the fields of this variant.
2923 pub fn fields(&self) -> &'hir [FieldDef<'hir>] {
2925 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2930 pub fn ctor(&self) -> Option<(CtorKind, HirId, LocalDefId)> {
2932 VariantData::Tuple(_, hir_id, def_id) => Some((CtorKind::Fn, hir_id, def_id)),
2933 VariantData::Unit(hir_id, def_id) => Some((CtorKind::Const, hir_id, def_id)),
2934 VariantData::Struct(..) => None,
2939 pub fn ctor_kind(&self) -> Option<CtorKind> {
2940 self.ctor().map(|(kind, ..)| kind)
2943 /// Return the `HirId` of this variant's constructor, if it has one.
2945 pub fn ctor_hir_id(&self) -> Option<HirId> {
2946 self.ctor().map(|(_, hir_id, _)| hir_id)
2949 /// Return the `LocalDefId` of this variant's constructor, if it has one.
2951 pub fn ctor_def_id(&self) -> Option<LocalDefId> {
2952 self.ctor().map(|(.., def_id)| def_id)
2956 // The bodies for items are stored "out of line", in a separate
2957 // hashmap in the `Crate`. Here we just record the hir-id of the item
2958 // so it can fetched later.
2959 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
2961 pub owner_id: OwnerId,
2966 pub fn hir_id(&self) -> HirId {
2967 // Items are always HIR owners.
2968 HirId::make_owner(self.owner_id.def_id)
2974 /// The name might be a dummy name in case of anonymous items
2975 #[derive(Debug, HashStable_Generic)]
2976 pub struct Item<'hir> {
2978 pub owner_id: OwnerId,
2979 pub kind: ItemKind<'hir>,
2986 pub fn hir_id(&self) -> HirId {
2987 // Items are always HIR owners.
2988 HirId::make_owner(self.owner_id.def_id)
2991 pub fn item_id(&self) -> ItemId {
2992 ItemId { owner_id: self.owner_id }
2996 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2997 #[derive(Encodable, Decodable, HashStable_Generic)]
3004 pub fn prefix_str(&self) -> &'static str {
3006 Self::Unsafe => "unsafe ",
3012 impl fmt::Display for Unsafety {
3013 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3014 f.write_str(match *self {
3015 Self::Unsafe => "unsafe",
3016 Self::Normal => "normal",
3021 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
3022 #[derive(Encodable, Decodable, HashStable_Generic)]
3023 pub enum Constness {
3028 impl fmt::Display for Constness {
3029 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3030 f.write_str(match *self {
3031 Self::Const => "const",
3032 Self::NotConst => "non-const",
3037 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
3038 pub struct FnHeader {
3039 pub unsafety: Unsafety,
3040 pub constness: Constness,
3041 pub asyncness: IsAsync,
3046 pub fn is_async(&self) -> bool {
3047 matches!(&self.asyncness, IsAsync::Async)
3050 pub fn is_const(&self) -> bool {
3051 matches!(&self.constness, Constness::Const)
3054 pub fn is_unsafe(&self) -> bool {
3055 matches!(&self.unsafety, Unsafety::Unsafe)
3059 #[derive(Debug, HashStable_Generic)]
3060 pub enum ItemKind<'hir> {
3061 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
3063 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
3064 ExternCrate(Option<Symbol>),
3066 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
3070 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
3071 Use(&'hir Path<'hir>, UseKind),
3073 /// A `static` item.
3074 Static(&'hir Ty<'hir>, Mutability, BodyId),
3076 Const(&'hir Ty<'hir>, BodyId),
3077 /// A function declaration.
3078 Fn(FnSig<'hir>, &'hir Generics<'hir>, BodyId),
3079 /// A MBE macro definition (`macro_rules!` or `macro`).
3080 Macro(ast::MacroDef, MacroKind),
3082 Mod(&'hir Mod<'hir>),
3083 /// An external module, e.g. `extern { .. }`.
3084 ForeignMod { abi: Abi, items: &'hir [ForeignItemRef] },
3085 /// Module-level inline assembly (from `global_asm!`).
3086 GlobalAsm(&'hir InlineAsm<'hir>),
3087 /// A type alias, e.g., `type Foo = Bar<u8>`.
3088 TyAlias(&'hir Ty<'hir>, &'hir Generics<'hir>),
3089 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
3090 OpaqueTy(OpaqueTy<'hir>),
3091 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
3092 Enum(EnumDef<'hir>, &'hir Generics<'hir>),
3093 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
3094 Struct(VariantData<'hir>, &'hir Generics<'hir>),
3095 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
3096 Union(VariantData<'hir>, &'hir Generics<'hir>),
3097 /// A trait definition.
3098 Trait(IsAuto, Unsafety, &'hir Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
3100 TraitAlias(&'hir Generics<'hir>, GenericBounds<'hir>),
3102 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
3103 Impl(&'hir Impl<'hir>),
3106 #[derive(Debug, HashStable_Generic)]
3107 pub struct Impl<'hir> {
3108 pub unsafety: Unsafety,
3109 pub polarity: ImplPolarity,
3110 pub defaultness: Defaultness,
3111 // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata
3112 // decoding as `Span`s cannot be decoded when a `Session` is not available.
3113 pub defaultness_span: Option<Span>,
3114 pub constness: Constness,
3115 pub generics: &'hir Generics<'hir>,
3117 /// The trait being implemented, if any.
3118 pub of_trait: Option<TraitRef<'hir>>,
3120 pub self_ty: &'hir Ty<'hir>,
3121 pub items: &'hir [ImplItemRef],
3125 pub fn generics(&self) -> Option<&Generics<'_>> {
3127 ItemKind::Fn(_, ref generics, _)
3128 | ItemKind::TyAlias(_, ref generics)
3129 | ItemKind::OpaqueTy(OpaqueTy { ref generics, .. })
3130 | ItemKind::Enum(_, ref generics)
3131 | ItemKind::Struct(_, ref generics)
3132 | ItemKind::Union(_, ref generics)
3133 | ItemKind::Trait(_, _, ref generics, _, _)
3134 | ItemKind::TraitAlias(ref generics, _)
3135 | ItemKind::Impl(Impl { ref generics, .. }) => generics,
3140 pub fn descr(&self) -> &'static str {
3142 ItemKind::ExternCrate(..) => "extern crate",
3143 ItemKind::Use(..) => "`use` import",
3144 ItemKind::Static(..) => "static item",
3145 ItemKind::Const(..) => "constant item",
3146 ItemKind::Fn(..) => "function",
3147 ItemKind::Macro(..) => "macro",
3148 ItemKind::Mod(..) => "module",
3149 ItemKind::ForeignMod { .. } => "extern block",
3150 ItemKind::GlobalAsm(..) => "global asm item",
3151 ItemKind::TyAlias(..) => "type alias",
3152 ItemKind::OpaqueTy(..) => "opaque type",
3153 ItemKind::Enum(..) => "enum",
3154 ItemKind::Struct(..) => "struct",
3155 ItemKind::Union(..) => "union",
3156 ItemKind::Trait(..) => "trait",
3157 ItemKind::TraitAlias(..) => "trait alias",
3158 ItemKind::Impl(..) => "implementation",
3163 /// A reference from an trait to one of its associated items. This
3164 /// contains the item's id, naturally, but also the item's name and
3165 /// some other high-level details (like whether it is an associated
3166 /// type or method, and whether it is public). This allows other
3167 /// passes to find the impl they want without loading the ID (which
3168 /// means fewer edges in the incremental compilation graph).
3169 #[derive(Encodable, Debug, HashStable_Generic)]
3170 pub struct TraitItemRef {
3171 pub id: TraitItemId,
3173 pub kind: AssocItemKind,
3177 /// A reference from an impl to one of its associated items. This
3178 /// contains the item's ID, naturally, but also the item's name and
3179 /// some other high-level details (like whether it is an associated
3180 /// type or method, and whether it is public). This allows other
3181 /// passes to find the impl they want without loading the ID (which
3182 /// means fewer edges in the incremental compilation graph).
3183 #[derive(Debug, HashStable_Generic)]
3184 pub struct ImplItemRef {
3187 pub kind: AssocItemKind,
3189 /// When we are in a trait impl, link to the trait-item's id.
3190 pub trait_item_def_id: Option<DefId>,
3193 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
3194 pub enum AssocItemKind {
3196 Fn { has_self: bool },
3200 // The bodies for items are stored "out of line", in a separate
3201 // hashmap in the `Crate`. Here we just record the hir-id of the item
3202 // so it can fetched later.
3203 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
3204 pub struct ForeignItemId {
3205 pub owner_id: OwnerId,
3208 impl ForeignItemId {
3210 pub fn hir_id(&self) -> HirId {
3211 // Items are always HIR owners.
3212 HirId::make_owner(self.owner_id.def_id)
3216 /// A reference from a foreign block to one of its items. This
3217 /// contains the item's ID, naturally, but also the item's name and
3218 /// some other high-level details (like whether it is an associated
3219 /// type or method, and whether it is public). This allows other
3220 /// passes to find the impl they want without loading the ID (which
3221 /// means fewer edges in the incremental compilation graph).
3222 #[derive(Debug, HashStable_Generic)]
3223 pub struct ForeignItemRef {
3224 pub id: ForeignItemId,
3229 #[derive(Debug, HashStable_Generic)]
3230 pub struct ForeignItem<'hir> {
3232 pub kind: ForeignItemKind<'hir>,
3233 pub owner_id: OwnerId,
3238 impl ForeignItem<'_> {
3240 pub fn hir_id(&self) -> HirId {
3241 // Items are always HIR owners.
3242 HirId::make_owner(self.owner_id.def_id)
3245 pub fn foreign_item_id(&self) -> ForeignItemId {
3246 ForeignItemId { owner_id: self.owner_id }
3250 /// An item within an `extern` block.
3251 #[derive(Debug, HashStable_Generic)]
3252 pub enum ForeignItemKind<'hir> {
3253 /// A foreign function.
3254 Fn(&'hir FnDecl<'hir>, &'hir [Ident], &'hir Generics<'hir>),
3255 /// A foreign static item (`static ext: u8`).
3256 Static(&'hir Ty<'hir>, Mutability),
3261 /// A variable captured by a closure.
3262 #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)]
3264 /// First span where it is accessed (there can be multiple).
3268 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
3269 // has length > 0 if the trait is found through an chain of imports, starting with the
3270 // import/use statement in the scope where the trait is used.
3271 #[derive(Encodable, Decodable, Clone, Debug, HashStable_Generic)]
3272 pub struct TraitCandidate {
3274 pub import_ids: SmallVec<[LocalDefId; 1]>,
3277 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3278 pub enum OwnerNode<'hir> {
3279 Item(&'hir Item<'hir>),
3280 ForeignItem(&'hir ForeignItem<'hir>),
3281 TraitItem(&'hir TraitItem<'hir>),
3282 ImplItem(&'hir ImplItem<'hir>),
3283 Crate(&'hir Mod<'hir>),
3286 impl<'hir> OwnerNode<'hir> {
3287 pub fn ident(&self) -> Option<Ident> {
3289 OwnerNode::Item(Item { ident, .. })
3290 | OwnerNode::ForeignItem(ForeignItem { ident, .. })
3291 | OwnerNode::ImplItem(ImplItem { ident, .. })
3292 | OwnerNode::TraitItem(TraitItem { ident, .. }) => Some(*ident),
3293 OwnerNode::Crate(..) => None,
3297 pub fn span(&self) -> Span {
3299 OwnerNode::Item(Item { span, .. })
3300 | OwnerNode::ForeignItem(ForeignItem { span, .. })
3301 | OwnerNode::ImplItem(ImplItem { span, .. })
3302 | OwnerNode::TraitItem(TraitItem { span, .. }) => *span,
3303 OwnerNode::Crate(Mod { spans: ModSpans { inner_span, .. }, .. }) => *inner_span,
3307 pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
3309 OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3310 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3311 | OwnerNode::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3312 OwnerNode::ForeignItem(ForeignItem {
3313 kind: ForeignItemKind::Fn(fn_decl, _, _),
3315 }) => Some(fn_decl),
3320 pub fn body_id(&self) -> Option<BodyId> {
3322 OwnerNode::TraitItem(TraitItem {
3323 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3326 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3327 | OwnerNode::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3332 pub fn generics(self) -> Option<&'hir Generics<'hir>> {
3333 Node::generics(self.into())
3336 pub fn def_id(self) -> OwnerId {
3338 OwnerNode::Item(Item { owner_id, .. })
3339 | OwnerNode::TraitItem(TraitItem { owner_id, .. })
3340 | OwnerNode::ImplItem(ImplItem { owner_id, .. })
3341 | OwnerNode::ForeignItem(ForeignItem { owner_id, .. }) => *owner_id,
3342 OwnerNode::Crate(..) => crate::CRATE_HIR_ID.owner,
3346 pub fn expect_item(self) -> &'hir Item<'hir> {
3348 OwnerNode::Item(n) => n,
3353 pub fn expect_foreign_item(self) -> &'hir ForeignItem<'hir> {
3355 OwnerNode::ForeignItem(n) => n,
3360 pub fn expect_impl_item(self) -> &'hir ImplItem<'hir> {
3362 OwnerNode::ImplItem(n) => n,
3367 pub fn expect_trait_item(self) -> &'hir TraitItem<'hir> {
3369 OwnerNode::TraitItem(n) => n,
3375 impl<'hir> Into<OwnerNode<'hir>> for &'hir Item<'hir> {
3376 fn into(self) -> OwnerNode<'hir> {
3377 OwnerNode::Item(self)
3381 impl<'hir> Into<OwnerNode<'hir>> for &'hir ForeignItem<'hir> {
3382 fn into(self) -> OwnerNode<'hir> {
3383 OwnerNode::ForeignItem(self)
3387 impl<'hir> Into<OwnerNode<'hir>> for &'hir ImplItem<'hir> {
3388 fn into(self) -> OwnerNode<'hir> {
3389 OwnerNode::ImplItem(self)
3393 impl<'hir> Into<OwnerNode<'hir>> for &'hir TraitItem<'hir> {
3394 fn into(self) -> OwnerNode<'hir> {
3395 OwnerNode::TraitItem(self)
3399 impl<'hir> Into<Node<'hir>> for OwnerNode<'hir> {
3400 fn into(self) -> Node<'hir> {
3402 OwnerNode::Item(n) => Node::Item(n),
3403 OwnerNode::ForeignItem(n) => Node::ForeignItem(n),
3404 OwnerNode::ImplItem(n) => Node::ImplItem(n),
3405 OwnerNode::TraitItem(n) => Node::TraitItem(n),
3406 OwnerNode::Crate(n) => Node::Crate(n),
3411 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3412 pub enum Node<'hir> {
3413 Param(&'hir Param<'hir>),
3414 Item(&'hir Item<'hir>),
3415 ForeignItem(&'hir ForeignItem<'hir>),
3416 TraitItem(&'hir TraitItem<'hir>),
3417 ImplItem(&'hir ImplItem<'hir>),
3418 Variant(&'hir Variant<'hir>),
3419 Field(&'hir FieldDef<'hir>),
3420 AnonConst(&'hir AnonConst),
3421 Expr(&'hir Expr<'hir>),
3422 ExprField(&'hir ExprField<'hir>),
3423 Stmt(&'hir Stmt<'hir>),
3424 PathSegment(&'hir PathSegment<'hir>),
3426 TypeBinding(&'hir TypeBinding<'hir>),
3427 TraitRef(&'hir TraitRef<'hir>),
3428 Pat(&'hir Pat<'hir>),
3429 PatField(&'hir PatField<'hir>),
3430 Arm(&'hir Arm<'hir>),
3431 Block(&'hir Block<'hir>),
3432 Local(&'hir Local<'hir>),
3434 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
3435 /// with synthesized constructors.
3436 Ctor(&'hir VariantData<'hir>),
3438 Lifetime(&'hir Lifetime),
3439 GenericParam(&'hir GenericParam<'hir>),
3441 Crate(&'hir Mod<'hir>),
3443 Infer(&'hir InferArg),
3446 impl<'hir> Node<'hir> {
3447 /// Get the identifier of this `Node`, if applicable.
3451 /// Calling `.ident()` on a [`Node::Ctor`] will return `None`
3452 /// because `Ctor`s do not have identifiers themselves.
3453 /// Instead, call `.ident()` on the parent struct/variant, like so:
3455 /// ```ignore (illustrative)
3458 /// .and_then(|ctor_id| tcx.hir().find(tcx.hir().get_parent_node(ctor_id)))
3459 /// .and_then(|parent| parent.ident())
3461 pub fn ident(&self) -> Option<Ident> {
3463 Node::TraitItem(TraitItem { ident, .. })
3464 | Node::ImplItem(ImplItem { ident, .. })
3465 | Node::ForeignItem(ForeignItem { ident, .. })
3466 | Node::Field(FieldDef { ident, .. })
3467 | Node::Variant(Variant { ident, .. })
3468 | Node::Item(Item { ident, .. })
3469 | Node::PathSegment(PathSegment { ident, .. }) => Some(*ident),
3470 Node::Lifetime(lt) => Some(lt.ident),
3471 Node::GenericParam(p) => Some(p.name.ident()),
3472 Node::TypeBinding(b) => Some(b.ident),
3474 | Node::AnonConst(..)
3480 | Node::PatField(..)
3481 | Node::ExprField(..)
3486 | Node::TraitRef(..)
3487 | Node::Infer(..) => None,
3491 pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
3493 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3494 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3495 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3496 Node::Expr(Expr { kind: ExprKind::Closure(Closure { fn_decl, .. }), .. })
3497 | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
3504 pub fn fn_sig(self) -> Option<&'hir FnSig<'hir>> {
3506 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3507 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3508 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig),
3513 pub fn body_id(&self) -> Option<BodyId> {
3515 Node::TraitItem(TraitItem {
3516 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3519 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3520 | Node::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3525 pub fn generics(self) -> Option<&'hir Generics<'hir>> {
3527 Node::ForeignItem(ForeignItem {
3528 kind: ForeignItemKind::Fn(_, _, generics), ..
3530 | Node::TraitItem(TraitItem { generics, .. })
3531 | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
3532 Node::Item(item) => item.kind.generics(),
3537 pub fn as_owner(self) -> Option<OwnerNode<'hir>> {
3539 Node::Item(i) => Some(OwnerNode::Item(i)),
3540 Node::ForeignItem(i) => Some(OwnerNode::ForeignItem(i)),
3541 Node::TraitItem(i) => Some(OwnerNode::TraitItem(i)),
3542 Node::ImplItem(i) => Some(OwnerNode::ImplItem(i)),
3543 Node::Crate(i) => Some(OwnerNode::Crate(i)),
3548 pub fn fn_kind(self) -> Option<FnKind<'hir>> {
3550 Node::Item(i) => match i.kind {
3551 ItemKind::Fn(ref sig, ref generics, _) => {
3552 Some(FnKind::ItemFn(i.ident, generics, sig.header))
3556 Node::TraitItem(ti) => match ti.kind {
3557 TraitItemKind::Fn(ref sig, TraitFn::Provided(_)) => {
3558 Some(FnKind::Method(ti.ident, sig))
3562 Node::ImplItem(ii) => match ii.kind {
3563 ImplItemKind::Fn(ref sig, _) => Some(FnKind::Method(ii.ident, sig)),
3566 Node::Expr(e) => match e.kind {
3567 ExprKind::Closure { .. } => Some(FnKind::Closure),
3574 /// Get the fields for the tuple-constructor,
3575 /// if this node is a tuple constructor, otherwise None
3576 pub fn tuple_fields(&self) -> Option<&'hir [FieldDef<'hir>]> {
3577 if let Node::Ctor(&VariantData::Tuple(fields, _, _)) = self { Some(fields) } else { None }
3581 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3582 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
3585 // tidy-alphabetical-start
3586 static_assert_size!(Block<'_>, 48);
3587 static_assert_size!(Body<'_>, 32);
3588 static_assert_size!(Expr<'_>, 64);
3589 static_assert_size!(ExprKind<'_>, 48);
3590 static_assert_size!(FnDecl<'_>, 40);
3591 static_assert_size!(ForeignItem<'_>, 72);
3592 static_assert_size!(ForeignItemKind<'_>, 40);
3593 static_assert_size!(GenericArg<'_>, 32);
3594 static_assert_size!(GenericBound<'_>, 48);
3595 static_assert_size!(Generics<'_>, 56);
3596 static_assert_size!(Impl<'_>, 80);
3597 static_assert_size!(ImplItem<'_>, 80);
3598 static_assert_size!(ImplItemKind<'_>, 32);
3599 static_assert_size!(Item<'_>, 80);
3600 static_assert_size!(ItemKind<'_>, 48);
3601 static_assert_size!(Local<'_>, 64);
3602 static_assert_size!(Param<'_>, 32);
3603 static_assert_size!(Pat<'_>, 72);
3604 static_assert_size!(Path<'_>, 40);
3605 static_assert_size!(PathSegment<'_>, 48);
3606 static_assert_size!(PatKind<'_>, 48);
3607 static_assert_size!(QPath<'_>, 24);
3608 static_assert_size!(Res, 12);
3609 static_assert_size!(Stmt<'_>, 32);
3610 static_assert_size!(StmtKind<'_>, 16);
3611 // tidy-alphabetical-end
3612 // FIXME: move the tidy directive to the end after the next bootstrap bump
3614 static_assert_size!(TraitItem<'_>, 88);
3615 #[cfg(not(bootstrap))]
3616 static_assert_size!(TraitItem<'_>, 80);
3618 static_assert_size!(TraitItemKind<'_>, 48);
3619 #[cfg(not(bootstrap))]
3620 static_assert_size!(TraitItemKind<'_>, 40);
3621 static_assert_size!(Ty<'_>, 48);
3622 static_assert_size!(TyKind<'_>, 32);