1 use crate::def::{DefKind, Namespace, Res};
2 use crate::def_id::DefId;
3 crate use crate::hir_id::HirId;
4 use crate::{itemlikevisit, LangItem};
6 use rustc_ast::util::parser::ExprPrecedence;
7 use rustc_ast::{self as ast, CrateSugar, LlvmAsmDialect};
8 use rustc_ast::{AttrVec, Attribute, FloatTy, IntTy, Label, LitKind, StrStyle, UintTy};
9 pub use rustc_ast::{BorrowKind, ImplPolarity, IsAuto};
10 pub use rustc_ast::{CaptureBy, Movability, Mutability};
11 use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
12 use rustc_data_structures::sync::{par_for_each_in, Send, Sync};
13 use rustc_macros::HashStable_Generic;
14 use rustc_span::def_id::LocalDefId;
15 use rustc_span::source_map::Spanned;
16 use rustc_span::symbol::{kw, sym, Ident, Symbol};
17 use rustc_span::{MultiSpan, Span, DUMMY_SP};
18 use rustc_target::asm::InlineAsmRegOrRegClass;
19 use rustc_target::spec::abi::Abi;
21 use smallvec::SmallVec;
22 use std::collections::{BTreeMap, BTreeSet};
25 #[derive(Copy, Clone, Encodable, HashStable_Generic)]
30 /// Either "`'a`", referring to a named lifetime definition,
31 /// or "``" (i.e., `kw::Invalid`), for elision placeholders.
33 /// HIR lowering inserts these placeholders in type paths that
34 /// refer to type definitions needing lifetime parameters,
35 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
36 pub name: LifetimeName,
39 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
40 #[derive(HashStable_Generic)]
42 /// Some user-given name like `T` or `'x`.
45 /// Synthetic name generated when user elided a lifetime in an impl header.
47 /// E.g., the lifetimes in cases like these:
50 /// impl Foo<'_> for u32
52 /// in that case, we rewrite to
54 /// impl<'f> Foo for &'f u32
55 /// impl<'f> Foo<'f> for u32
57 /// where `'f` is something like `Fresh(0)`. The indices are
58 /// unique per impl, but not necessarily continuous.
61 /// Indicates an illegal name was given and an error has been
62 /// reported (so we should squelch other derived errors). Occurs
63 /// when, e.g., `'_` is used in the wrong place.
68 pub fn ident(&self) -> Ident {
70 ParamName::Plain(ident) => ident,
71 ParamName::Fresh(_) | ParamName::Error => {
72 Ident::with_dummy_span(kw::UnderscoreLifetime)
77 pub fn normalize_to_macros_2_0(&self) -> ParamName {
79 ParamName::Plain(ident) => ParamName::Plain(ident.normalize_to_macros_2_0()),
80 param_name => param_name,
85 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
86 #[derive(HashStable_Generic)]
87 pub enum LifetimeName {
88 /// User-given names or fresh (synthetic) names.
91 /// User wrote nothing (e.g., the lifetime in `&u32`).
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 specifies `'_`.
114 /// User wrote `'static`.
119 pub fn ident(&self) -> Ident {
121 LifetimeName::ImplicitObjectLifetimeDefault
122 | LifetimeName::Implicit
123 | LifetimeName::Error => Ident::invalid(),
124 LifetimeName::Underscore => Ident::with_dummy_span(kw::UnderscoreLifetime),
125 LifetimeName::Static => Ident::with_dummy_span(kw::StaticLifetime),
126 LifetimeName::Param(param_name) => param_name.ident(),
130 pub fn is_elided(&self) -> bool {
132 LifetimeName::ImplicitObjectLifetimeDefault
133 | LifetimeName::Implicit
134 | LifetimeName::Underscore => true,
136 // It might seem surprising that `Fresh(_)` counts as
137 // *not* elided -- but this is because, as far as the code
138 // in the compiler is concerned -- `Fresh(_)` variants act
139 // equivalently to "some fresh name". They correspond to
140 // early-bound regions on an impl, in other words.
141 LifetimeName::Error | LifetimeName::Param(_) | LifetimeName::Static => false,
145 fn is_static(&self) -> bool {
146 self == &LifetimeName::Static
149 pub fn normalize_to_macros_2_0(&self) -> LifetimeName {
151 LifetimeName::Param(param_name) => {
152 LifetimeName::Param(param_name.normalize_to_macros_2_0())
154 lifetime_name => lifetime_name,
159 impl fmt::Display for Lifetime {
160 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
161 self.name.ident().fmt(f)
165 impl fmt::Debug for Lifetime {
166 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167 write!(f, "lifetime({}: {})", self.hir_id, self.name.ident())
172 pub fn is_elided(&self) -> bool {
173 self.name.is_elided()
176 pub fn is_static(&self) -> bool {
177 self.name.is_static()
181 /// A `Path` is essentially Rust's notion of a name; for instance,
182 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
183 /// along with a bunch of supporting information.
184 #[derive(Debug, HashStable_Generic)]
185 pub struct Path<'hir> {
187 /// The resolution for the path.
189 /// The segments in the path: the things separated by `::`.
190 pub segments: &'hir [PathSegment<'hir>],
194 pub fn is_global(&self) -> bool {
195 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
199 /// A segment of a path: an identifier, an optional lifetime, and a set of
201 #[derive(Debug, HashStable_Generic)]
202 pub struct PathSegment<'hir> {
203 /// The identifier portion of this path segment.
204 #[stable_hasher(project(name))]
206 // `id` and `res` are optional. We currently only use these in save-analysis,
207 // any path segments without these will not have save-analysis info and
208 // therefore will not have 'jump to def' in IDEs, but otherwise will not be
209 // affected. (In general, we don't bother to get the defs for synthesized
210 // segments, only for segments which have come from the AST).
211 pub hir_id: Option<HirId>,
212 pub res: Option<Res>,
214 /// Type/lifetime parameters attached to this path. They come in
215 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
216 /// this is more than just simple syntactic sugar; the use of
217 /// parens affects the region binding rules, so we preserve the
219 pub args: Option<&'hir GenericArgs<'hir>>,
221 /// Whether to infer remaining type parameters, if any.
222 /// This only applies to expression and pattern paths, and
223 /// out of those only the segments with no type parameters
224 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
225 pub infer_args: bool,
228 impl<'hir> PathSegment<'hir> {
229 /// Converts an identifier to the corresponding segment.
230 pub fn from_ident(ident: Ident) -> PathSegment<'hir> {
231 PathSegment { ident, hir_id: None, res: None, infer_args: true, args: None }
234 pub fn generic_args(&self) -> &GenericArgs<'hir> {
235 if let Some(ref args) = self.args {
238 const DUMMY: &GenericArgs<'_> = &GenericArgs::none();
244 #[derive(Encodable, Debug, HashStable_Generic)]
245 pub struct ConstArg {
246 pub value: AnonConst,
250 #[derive(Debug, HashStable_Generic)]
251 pub enum GenericArg<'hir> {
257 impl GenericArg<'_> {
258 pub fn span(&self) -> Span {
260 GenericArg::Lifetime(l) => l.span,
261 GenericArg::Type(t) => t.span,
262 GenericArg::Const(c) => c.span,
266 pub fn id(&self) -> HirId {
268 GenericArg::Lifetime(l) => l.hir_id,
269 GenericArg::Type(t) => t.hir_id,
270 GenericArg::Const(c) => c.value.hir_id,
274 pub fn is_const(&self) -> bool {
275 matches!(self, GenericArg::Const(_))
278 pub fn descr(&self) -> &'static str {
280 GenericArg::Lifetime(_) => "lifetime",
281 GenericArg::Type(_) => "type",
282 GenericArg::Const(_) => "constant",
286 pub fn short_descr(&self) -> &'static str {
288 GenericArg::Lifetime(_) => "lifetime",
289 GenericArg::Type(_) => "type",
290 GenericArg::Const(_) => "const",
295 #[derive(Debug, HashStable_Generic)]
296 pub struct GenericArgs<'hir> {
297 /// The generic arguments for this path segment.
298 pub args: &'hir [GenericArg<'hir>],
299 /// Bindings (equality constraints) on associated types, if present.
300 /// E.g., `Foo<A = Bar>`.
301 pub bindings: &'hir [TypeBinding<'hir>],
302 /// Were arguments written in parenthesized form `Fn(T) -> U`?
303 /// This is required mostly for pretty-printing and diagnostics,
304 /// but also for changing lifetime elision rules to be "function-like".
305 pub parenthesized: bool,
308 impl GenericArgs<'_> {
309 pub const fn none() -> Self {
310 Self { args: &[], bindings: &[], parenthesized: false }
313 pub fn inputs(&self) -> &[Ty<'_>] {
314 if self.parenthesized {
315 for arg in self.args {
317 GenericArg::Lifetime(_) => {}
318 GenericArg::Type(ref ty) => {
319 if let TyKind::Tup(ref tys) = ty.kind {
324 GenericArg::Const(_) => {}
328 panic!("GenericArgs::inputs: not a `Fn(T) -> U`");
331 pub fn own_counts(&self) -> GenericParamCount {
332 // We could cache this as a property of `GenericParamCount`, but
333 // the aim is to refactor this away entirely eventually and the
334 // presence of this method will be a constant reminder.
335 let mut own_counts: GenericParamCount = Default::default();
337 for arg in self.args {
339 GenericArg::Lifetime(_) => own_counts.lifetimes += 1,
340 GenericArg::Type(_) => own_counts.types += 1,
341 GenericArg::Const(_) => own_counts.consts += 1,
349 /// A modifier on a bound, currently this is only used for `?Sized`, where the
350 /// modifier is `Maybe`. Negative bounds should also be handled here.
351 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
352 #[derive(HashStable_Generic)]
353 pub enum TraitBoundModifier {
359 /// The AST represents all type param bounds as types.
360 /// `typeck::collect::compute_bounds` matches these against
361 /// the "special" built-in traits (see `middle::lang_items`) and
362 /// detects `Copy`, `Send` and `Sync`.
363 #[derive(Debug, HashStable_Generic)]
364 pub enum GenericBound<'hir> {
365 Trait(PolyTraitRef<'hir>, TraitBoundModifier),
366 // FIXME(davidtwco): Introduce `PolyTraitRef::LangItem`
367 LangItemTrait(LangItem, Span, HirId, &'hir GenericArgs<'hir>),
371 impl GenericBound<'_> {
372 pub fn trait_ref(&self) -> Option<&TraitRef<'_>> {
374 GenericBound::Trait(data, _) => Some(&data.trait_ref),
379 pub fn span(&self) -> Span {
381 &GenericBound::Trait(ref t, ..) => t.span,
382 &GenericBound::LangItemTrait(_, span, ..) => span,
383 &GenericBound::Outlives(ref l) => l.span,
388 pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
390 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
391 pub enum LifetimeParamKind {
392 // Indicates that the lifetime definition was explicitly declared (e.g., in
393 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
396 // Indicates that the lifetime definition was synthetically added
397 // as a result of an in-band lifetime usage (e.g., in
398 // `fn foo(x: &'a u8) -> &'a u8 { x }`).
401 // Indication that the lifetime was elided (e.g., in both cases in
402 // `fn foo(x: &u8) -> &'_ u8 { x }`).
405 // Indication that the lifetime name was somehow in error.
409 #[derive(Debug, HashStable_Generic)]
410 pub enum GenericParamKind<'hir> {
411 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
413 kind: LifetimeParamKind,
416 default: Option<&'hir Ty<'hir>>,
417 synthetic: Option<SyntheticTyParamKind>,
424 #[derive(Debug, HashStable_Generic)]
425 pub struct GenericParam<'hir> {
428 pub attrs: &'hir [Attribute],
429 pub bounds: GenericBounds<'hir>,
431 pub pure_wrt_drop: bool,
432 pub kind: GenericParamKind<'hir>,
435 impl GenericParam<'hir> {
436 pub fn bounds_span(&self) -> Option<Span> {
437 self.bounds.iter().fold(None, |span, bound| {
438 let span = span.map(|s| s.to(bound.span())).unwrap_or_else(|| bound.span());
446 pub struct GenericParamCount {
447 pub lifetimes: usize,
452 /// Represents lifetimes and type parameters attached to a declaration
453 /// of a function, enum, trait, etc.
454 #[derive(Debug, HashStable_Generic)]
455 pub struct Generics<'hir> {
456 pub params: &'hir [GenericParam<'hir>],
457 pub where_clause: WhereClause<'hir>,
461 impl Generics<'hir> {
462 pub const fn empty() -> Generics<'hir> {
465 where_clause: WhereClause { predicates: &[], span: DUMMY_SP },
470 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'_>> {
471 for param in self.params {
472 if name == param.name.ident().name {
479 pub fn spans(&self) -> MultiSpan {
480 if self.params.is_empty() {
483 self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
488 /// Synthetic type parameters are converted to another form during lowering; this allows
489 /// us to track the original form they had, and is useful for error messages.
490 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
491 #[derive(HashStable_Generic)]
492 pub enum SyntheticTyParamKind {
494 // Created by the `#[rustc_synthetic]` attribute.
498 /// A where-clause in a definition.
499 #[derive(Debug, HashStable_Generic)]
500 pub struct WhereClause<'hir> {
501 pub predicates: &'hir [WherePredicate<'hir>],
502 // Only valid if predicates aren't empty.
506 impl WhereClause<'_> {
507 pub fn span(&self) -> Option<Span> {
508 if self.predicates.is_empty() { None } else { Some(self.span) }
511 /// The `WhereClause` under normal circumstances points at either the predicates or the empty
512 /// space where the `where` clause should be. Only of use for diagnostic suggestions.
513 pub fn span_for_predicates_or_empty_place(&self) -> Span {
517 /// `Span` where further predicates would be suggested, accounting for trailing commas, like
518 /// in `fn foo<T>(t: T) where T: Foo,` so we don't suggest two trailing commas.
519 pub fn tail_span_for_suggestion(&self) -> Span {
520 let end = self.span_for_predicates_or_empty_place().shrink_to_hi();
521 self.predicates.last().map(|p| p.span()).unwrap_or(end).shrink_to_hi().to(end)
525 /// A single predicate in a where-clause.
526 #[derive(Debug, HashStable_Generic)]
527 pub enum WherePredicate<'hir> {
528 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
529 BoundPredicate(WhereBoundPredicate<'hir>),
530 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
531 RegionPredicate(WhereRegionPredicate<'hir>),
532 /// An equality predicate (unsupported).
533 EqPredicate(WhereEqPredicate<'hir>),
536 impl WherePredicate<'_> {
537 pub fn span(&self) -> Span {
539 &WherePredicate::BoundPredicate(ref p) => p.span,
540 &WherePredicate::RegionPredicate(ref p) => p.span,
541 &WherePredicate::EqPredicate(ref p) => p.span,
546 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
547 #[derive(Debug, HashStable_Generic)]
548 pub struct WhereBoundPredicate<'hir> {
550 /// Any generics from a `for` binding.
551 pub bound_generic_params: &'hir [GenericParam<'hir>],
552 /// The type being bounded.
553 pub bounded_ty: &'hir Ty<'hir>,
554 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
555 pub bounds: GenericBounds<'hir>,
558 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
559 #[derive(Debug, HashStable_Generic)]
560 pub struct WhereRegionPredicate<'hir> {
562 pub lifetime: Lifetime,
563 pub bounds: GenericBounds<'hir>,
566 /// An equality predicate (e.g., `T = int`); currently unsupported.
567 #[derive(Debug, HashStable_Generic)]
568 pub struct WhereEqPredicate<'hir> {
571 pub lhs_ty: &'hir Ty<'hir>,
572 pub rhs_ty: &'hir Ty<'hir>,
575 #[derive(Encodable, Debug, HashStable_Generic)]
576 pub struct ModuleItems {
577 // Use BTreeSets here so items are in the same order as in the
578 // list of all items in Crate
579 pub items: BTreeSet<HirId>,
580 pub trait_items: BTreeSet<TraitItemId>,
581 pub impl_items: BTreeSet<ImplItemId>,
582 pub foreign_items: BTreeSet<ForeignItemId>,
585 /// A type representing only the top-level module.
586 #[derive(Encodable, Debug, HashStable_Generic)]
587 pub struct CrateItem<'hir> {
588 pub module: Mod<'hir>,
589 pub attrs: &'hir [Attribute],
593 /// The top-level data structure that stores the entire contents of
594 /// the crate currently being compiled.
596 /// For more details, see the [rustc dev guide].
598 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
600 pub struct Crate<'hir> {
601 pub item: CrateItem<'hir>,
602 pub exported_macros: &'hir [MacroDef<'hir>],
603 // Attributes from non-exported macros, kept only for collecting the library feature list.
604 pub non_exported_macro_attrs: &'hir [Attribute],
606 // N.B., we use a `BTreeMap` here so that `visit_all_items` iterates
607 // over the ids in increasing order. In principle it should not
608 // matter what order we visit things in, but in *practice* it
609 // does, because it can affect the order in which errors are
610 // detected, which in turn can make compile-fail tests yield
611 // slightly different results.
612 pub items: BTreeMap<HirId, Item<'hir>>,
614 pub trait_items: BTreeMap<TraitItemId, TraitItem<'hir>>,
615 pub impl_items: BTreeMap<ImplItemId, ImplItem<'hir>>,
616 pub foreign_items: BTreeMap<ForeignItemId, ForeignItem<'hir>>,
617 pub bodies: BTreeMap<BodyId, Body<'hir>>,
618 pub trait_impls: BTreeMap<DefId, Vec<HirId>>,
620 /// A list of the body ids written out in the order in which they
621 /// appear in the crate. If you're going to process all the bodies
622 /// in the crate, you should iterate over this list rather than the keys
624 pub body_ids: Vec<BodyId>,
626 /// A list of modules written out in the order in which they
627 /// appear in the crate. This includes the main crate module.
628 pub modules: BTreeMap<HirId, ModuleItems>,
629 /// A list of proc macro HirIds, written out in the order in which
630 /// they are declared in the static array generated by proc_macro_harness.
631 pub proc_macros: Vec<HirId>,
633 pub trait_map: BTreeMap<HirId, Vec<TraitCandidate>>,
637 pub fn item(&self, id: HirId) -> &Item<'hir> {
641 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem<'hir> {
642 &self.trait_items[&id]
645 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem<'hir> {
646 &self.impl_items[&id]
649 pub fn foreign_item(&self, id: ForeignItemId) -> &ForeignItem<'hir> {
650 &self.foreign_items[&id]
653 pub fn body(&self, id: BodyId) -> &Body<'hir> {
659 /// Visits all items in the crate in some deterministic (but
660 /// unspecified) order. If you just need to process every item,
661 /// but don't care about nesting, this method is the best choice.
663 /// If you do care about nesting -- usually because your algorithm
664 /// follows lexical scoping rules -- then you want a different
665 /// approach. You should override `visit_nested_item` in your
666 /// visitor and then call `intravisit::walk_crate` instead.
667 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
669 V: itemlikevisit::ItemLikeVisitor<'hir>,
671 for item in self.items.values() {
672 visitor.visit_item(item);
675 for trait_item in self.trait_items.values() {
676 visitor.visit_trait_item(trait_item);
679 for impl_item in self.impl_items.values() {
680 visitor.visit_impl_item(impl_item);
683 for foreign_item in self.foreign_items.values() {
684 visitor.visit_foreign_item(foreign_item);
688 /// A parallel version of `visit_all_item_likes`.
689 pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
691 V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send,
695 par_for_each_in(&self.items, |(_, item)| {
696 visitor.visit_item(item);
700 par_for_each_in(&self.trait_items, |(_, trait_item)| {
701 visitor.visit_trait_item(trait_item);
705 par_for_each_in(&self.impl_items, |(_, impl_item)| {
706 visitor.visit_impl_item(impl_item);
710 par_for_each_in(&self.foreign_items, |(_, foreign_item)| {
711 visitor.visit_foreign_item(foreign_item);
718 /// A macro definition, in this crate or imported from another.
720 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
721 #[derive(Debug, HashStable_Generic)]
722 pub struct MacroDef<'hir> {
724 pub vis: Visibility<'hir>,
725 pub attrs: &'hir [Attribute],
728 pub ast: ast::MacroDef,
731 /// A block of statements `{ .. }`, which may have a label (in this case the
732 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
733 /// the `rules` being anything but `DefaultBlock`.
734 #[derive(Debug, HashStable_Generic)]
735 pub struct Block<'hir> {
736 /// Statements in a block.
737 pub stmts: &'hir [Stmt<'hir>],
738 /// An expression at the end of the block
739 /// without a semicolon, if any.
740 pub expr: Option<&'hir Expr<'hir>>,
741 #[stable_hasher(ignore)]
743 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
744 pub rules: BlockCheckMode,
746 /// If true, then there may exist `break 'a` values that aim to
747 /// break out of this block early.
748 /// Used by `'label: {}` blocks and by `try {}` blocks.
749 pub targeted_by_break: bool,
752 #[derive(Debug, HashStable_Generic)]
753 pub struct Pat<'hir> {
754 #[stable_hasher(ignore)]
756 pub kind: PatKind<'hir>,
758 // Whether to use default binding modes.
759 // At present, this is false only for destructuring assignment.
760 pub default_binding_modes: bool,
764 // FIXME(#19596) this is a workaround, but there should be a better way
765 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'_>) -> bool) -> bool {
772 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
773 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
774 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
775 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
776 Slice(before, slice, after) => {
777 before.iter().chain(slice.iter()).chain(after.iter()).all(|p| p.walk_short_(it))
782 /// Walk the pattern in left-to-right order,
783 /// short circuiting (with `.all(..)`) if `false` is returned.
785 /// Note that when visiting e.g. `Tuple(ps)`,
786 /// if visiting `ps[0]` returns `false`,
787 /// then `ps[1]` will not be visited.
788 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'_>) -> bool) -> bool {
789 self.walk_short_(&mut it)
792 // FIXME(#19596) this is a workaround, but there should be a better way
793 fn walk_(&self, it: &mut impl FnMut(&Pat<'_>) -> bool) {
800 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
801 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
802 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
803 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
804 Slice(before, slice, after) => {
805 before.iter().chain(slice.iter()).chain(after.iter()).for_each(|p| p.walk_(it))
810 /// Walk the pattern in left-to-right order.
812 /// If `it(pat)` returns `false`, the children are not visited.
813 pub fn walk(&self, mut it: impl FnMut(&Pat<'_>) -> bool) {
817 /// Walk the pattern in left-to-right order.
819 /// If you always want to recurse, prefer this method over `walk`.
820 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
828 /// A single field in a struct pattern.
830 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
831 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
832 /// except `is_shorthand` is true.
833 #[derive(Debug, HashStable_Generic)]
834 pub struct FieldPat<'hir> {
835 #[stable_hasher(ignore)]
837 /// The identifier for the field.
838 #[stable_hasher(project(name))]
840 /// The pattern the field is destructured to.
841 pub pat: &'hir Pat<'hir>,
842 pub is_shorthand: bool,
846 /// Explicit binding annotations given in the HIR for a binding. Note
847 /// that this is not the final binding *mode* that we infer after type
849 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
850 pub enum BindingAnnotation {
851 /// No binding annotation given: this means that the final binding mode
852 /// will depend on whether we have skipped through a `&` reference
853 /// when matching. For example, the `x` in `Some(x)` will have binding
854 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
855 /// ultimately be inferred to be by-reference.
857 /// Note that implicit reference skipping is not implemented yet (#42640).
860 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
863 /// Annotated as `ref`, like `ref x`
866 /// Annotated as `ref mut x`.
870 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
876 impl fmt::Display for RangeEnd {
877 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
878 f.write_str(match self {
879 RangeEnd::Included => "..=",
880 RangeEnd::Excluded => "..",
885 #[derive(Debug, HashStable_Generic)]
886 pub enum PatKind<'hir> {
887 /// Represents a wildcard pattern (i.e., `_`).
890 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
891 /// The `HirId` is the canonical ID for the variable being bound,
892 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
893 /// which is the pattern ID of the first `x`.
894 Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
896 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
897 /// The `bool` is `true` in the presence of a `..`.
898 Struct(QPath<'hir>, &'hir [FieldPat<'hir>], bool),
900 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
901 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
902 /// `0 <= position <= subpats.len()`
903 TupleStruct(QPath<'hir>, &'hir [&'hir Pat<'hir>], Option<usize>),
905 /// An or-pattern `A | B | C`.
906 /// Invariant: `pats.len() >= 2`.
907 Or(&'hir [&'hir Pat<'hir>]),
909 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
912 /// A tuple pattern (e.g., `(a, b)`).
913 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
914 /// `0 <= position <= subpats.len()`
915 Tuple(&'hir [&'hir Pat<'hir>], Option<usize>),
918 Box(&'hir Pat<'hir>),
920 /// A reference pattern (e.g., `&mut (a, b)`).
921 Ref(&'hir Pat<'hir>, Mutability),
924 Lit(&'hir Expr<'hir>),
926 /// A range pattern (e.g., `1..=2` or `1..2`).
927 Range(Option<&'hir Expr<'hir>>, Option<&'hir Expr<'hir>>, RangeEnd),
929 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
931 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
932 /// If `slice` exists, then `after` can be non-empty.
934 /// The representation for e.g., `[a, b, .., c, d]` is:
936 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
938 Slice(&'hir [&'hir Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [&'hir Pat<'hir>]),
941 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
943 /// The `+` operator (addition).
945 /// The `-` operator (subtraction).
947 /// The `*` operator (multiplication).
949 /// The `/` operator (division).
951 /// The `%` operator (modulus).
953 /// The `&&` operator (logical and).
955 /// The `||` operator (logical or).
957 /// The `^` operator (bitwise xor).
959 /// The `&` operator (bitwise and).
961 /// The `|` operator (bitwise or).
963 /// The `<<` operator (shift left).
965 /// The `>>` operator (shift right).
967 /// The `==` operator (equality).
969 /// The `<` operator (less than).
971 /// The `<=` operator (less than or equal to).
973 /// The `!=` operator (not equal to).
975 /// The `>=` operator (greater than or equal to).
977 /// The `>` operator (greater than).
982 pub fn as_str(self) -> &'static str {
984 BinOpKind::Add => "+",
985 BinOpKind::Sub => "-",
986 BinOpKind::Mul => "*",
987 BinOpKind::Div => "/",
988 BinOpKind::Rem => "%",
989 BinOpKind::And => "&&",
990 BinOpKind::Or => "||",
991 BinOpKind::BitXor => "^",
992 BinOpKind::BitAnd => "&",
993 BinOpKind::BitOr => "|",
994 BinOpKind::Shl => "<<",
995 BinOpKind::Shr => ">>",
996 BinOpKind::Eq => "==",
997 BinOpKind::Lt => "<",
998 BinOpKind::Le => "<=",
999 BinOpKind::Ne => "!=",
1000 BinOpKind::Ge => ">=",
1001 BinOpKind::Gt => ">",
1005 pub fn is_lazy(self) -> bool {
1006 matches!(self, BinOpKind::And | BinOpKind::Or)
1009 pub fn is_shift(self) -> bool {
1010 matches!(self, BinOpKind::Shl | BinOpKind::Shr)
1013 pub fn is_comparison(self) -> bool {
1020 | BinOpKind::Ge => true,
1032 | BinOpKind::Shr => false,
1036 /// Returns `true` if the binary operator takes its arguments by value.
1037 pub fn is_by_value(self) -> bool {
1038 !self.is_comparison()
1042 impl Into<ast::BinOpKind> for BinOpKind {
1043 fn into(self) -> ast::BinOpKind {
1045 BinOpKind::Add => ast::BinOpKind::Add,
1046 BinOpKind::Sub => ast::BinOpKind::Sub,
1047 BinOpKind::Mul => ast::BinOpKind::Mul,
1048 BinOpKind::Div => ast::BinOpKind::Div,
1049 BinOpKind::Rem => ast::BinOpKind::Rem,
1050 BinOpKind::And => ast::BinOpKind::And,
1051 BinOpKind::Or => ast::BinOpKind::Or,
1052 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1053 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1054 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1055 BinOpKind::Shl => ast::BinOpKind::Shl,
1056 BinOpKind::Shr => ast::BinOpKind::Shr,
1057 BinOpKind::Eq => ast::BinOpKind::Eq,
1058 BinOpKind::Lt => ast::BinOpKind::Lt,
1059 BinOpKind::Le => ast::BinOpKind::Le,
1060 BinOpKind::Ne => ast::BinOpKind::Ne,
1061 BinOpKind::Ge => ast::BinOpKind::Ge,
1062 BinOpKind::Gt => ast::BinOpKind::Gt,
1067 pub type BinOp = Spanned<BinOpKind>;
1069 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1071 /// The `*` operator (deferencing).
1073 /// The `!` operator (logical negation).
1075 /// The `-` operator (negation).
1080 pub fn as_str(self) -> &'static str {
1082 Self::UnDeref => "*",
1088 /// Returns `true` if the unary operator takes its argument by value.
1089 pub fn is_by_value(self) -> bool {
1090 matches!(self, Self::UnNeg | Self::UnNot)
1095 #[derive(Debug, HashStable_Generic)]
1096 pub struct Stmt<'hir> {
1098 pub kind: StmtKind<'hir>,
1102 /// The contents of a statement.
1103 #[derive(Debug, HashStable_Generic)]
1104 pub enum StmtKind<'hir> {
1105 /// A local (`let`) binding.
1106 Local(&'hir Local<'hir>),
1108 /// An item binding.
1111 /// An expression without a trailing semi-colon (must have unit type).
1112 Expr(&'hir Expr<'hir>),
1114 /// An expression with a trailing semi-colon (may have any type).
1115 Semi(&'hir Expr<'hir>),
1118 impl<'hir> StmtKind<'hir> {
1119 pub fn attrs(&self, get_item: impl FnOnce(ItemId) -> &'hir Item<'hir>) -> &'hir [Attribute] {
1121 StmtKind::Local(ref l) => &l.attrs,
1122 StmtKind::Item(ref item_id) => &get_item(*item_id).attrs,
1123 StmtKind::Expr(ref e) | StmtKind::Semi(ref e) => &e.attrs,
1128 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1129 #[derive(Debug, HashStable_Generic)]
1130 pub struct Local<'hir> {
1131 pub pat: &'hir Pat<'hir>,
1132 /// Type annotation, if any (otherwise the type will be inferred).
1133 pub ty: Option<&'hir Ty<'hir>>,
1134 /// Initializer expression to set the value, if any.
1135 pub init: Option<&'hir Expr<'hir>>,
1139 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1140 /// desugaring. Otherwise will be `Normal`.
1141 pub source: LocalSource,
1144 /// Represents a single arm of a `match` expression, e.g.
1145 /// `<pat> (if <guard>) => <body>`.
1146 #[derive(Debug, HashStable_Generic)]
1147 pub struct Arm<'hir> {
1148 #[stable_hasher(ignore)]
1151 pub attrs: &'hir [Attribute],
1152 /// If this pattern and the optional guard matches, then `body` is evaluated.
1153 pub pat: &'hir Pat<'hir>,
1154 /// Optional guard clause.
1155 pub guard: Option<Guard<'hir>>,
1156 /// The expression the arm evaluates to if this arm matches.
1157 pub body: &'hir Expr<'hir>,
1160 #[derive(Debug, HashStable_Generic)]
1161 pub enum Guard<'hir> {
1162 If(&'hir Expr<'hir>),
1165 #[derive(Debug, HashStable_Generic)]
1166 pub struct Field<'hir> {
1167 #[stable_hasher(ignore)]
1170 pub expr: &'hir Expr<'hir>,
1172 pub is_shorthand: bool,
1175 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1176 pub enum BlockCheckMode {
1178 UnsafeBlock(UnsafeSource),
1179 PushUnsafeBlock(UnsafeSource),
1180 PopUnsafeBlock(UnsafeSource),
1183 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1184 pub enum UnsafeSource {
1189 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Hash, Debug)]
1194 /// The body of a function, closure, or constant value. In the case of
1195 /// a function, the body contains not only the function body itself
1196 /// (which is an expression), but also the argument patterns, since
1197 /// those are something that the caller doesn't really care about.
1202 /// fn foo((x, y): (u32, u32)) -> u32 {
1207 /// Here, the `Body` associated with `foo()` would contain:
1209 /// - an `params` array containing the `(x, y)` pattern
1210 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1211 /// - `generator_kind` would be `None`
1213 /// All bodies have an **owner**, which can be accessed via the HIR
1214 /// map using `body_owner_def_id()`.
1216 pub struct Body<'hir> {
1217 pub params: &'hir [Param<'hir>],
1218 pub value: Expr<'hir>,
1219 pub generator_kind: Option<GeneratorKind>,
1223 pub fn id(&self) -> BodyId {
1224 BodyId { hir_id: self.value.hir_id }
1227 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1232 /// The type of source expression that caused this generator to be created.
1233 #[derive(Clone, PartialEq, Eq, HashStable_Generic, Encodable, Decodable, Debug, Copy)]
1234 pub enum GeneratorKind {
1235 /// An explicit `async` block or the body of an async function.
1236 Async(AsyncGeneratorKind),
1238 /// A generator literal created via a `yield` inside a closure.
1242 impl fmt::Display for GeneratorKind {
1243 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1245 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1246 GeneratorKind::Gen => f.write_str("generator"),
1251 /// In the case of a generator created as part of an async construct,
1252 /// which kind of async construct caused it to be created?
1254 /// This helps error messages but is also used to drive coercions in
1255 /// type-checking (see #60424).
1256 #[derive(Clone, PartialEq, Eq, HashStable_Generic, Encodable, Decodable, Debug, Copy)]
1257 pub enum AsyncGeneratorKind {
1258 /// An explicit `async` block written by the user.
1261 /// An explicit `async` block written by the user.
1264 /// The `async` block generated as the body of an async function.
1268 impl fmt::Display for AsyncGeneratorKind {
1269 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1270 f.write_str(match self {
1271 AsyncGeneratorKind::Block => "`async` block",
1272 AsyncGeneratorKind::Closure => "`async` closure body",
1273 AsyncGeneratorKind::Fn => "`async fn` body",
1278 #[derive(Copy, Clone, Debug)]
1279 pub enum BodyOwnerKind {
1280 /// Functions and methods.
1286 /// Constants and associated constants.
1289 /// Initializer of a `static` item.
1293 impl BodyOwnerKind {
1294 pub fn is_fn_or_closure(self) -> bool {
1296 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1297 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1302 /// The kind of an item that requires const-checking.
1303 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1304 pub enum ConstContext {
1308 /// A `static` or `static mut`.
1311 /// A `const`, associated `const`, or other const context.
1313 /// Other contexts include:
1314 /// - Array length expressions
1315 /// - Enum discriminants
1316 /// - Const generics
1318 /// For the most part, other contexts are treated just like a regular `const`, so they are
1319 /// lumped into the same category.
1324 /// A description of this const context that can appear between backticks in an error message.
1326 /// E.g. `const` or `static mut`.
1327 pub fn keyword_name(self) -> &'static str {
1329 Self::Const => "const",
1330 Self::Static(Mutability::Not) => "static",
1331 Self::Static(Mutability::Mut) => "static mut",
1332 Self::ConstFn => "const fn",
1337 /// A colloquial, trivially pluralizable description of this const context for use in error
1339 impl fmt::Display for ConstContext {
1340 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1342 Self::Const => write!(f, "constant"),
1343 Self::Static(_) => write!(f, "static"),
1344 Self::ConstFn => write!(f, "constant function"),
1350 pub type Lit = Spanned<LitKind>;
1352 /// A constant (expression) that's not an item or associated item,
1353 /// but needs its own `DefId` for type-checking, const-eval, etc.
1354 /// These are usually found nested inside types (e.g., array lengths)
1355 /// or expressions (e.g., repeat counts), and also used to define
1356 /// explicit discriminant values for enum variants.
1357 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1358 pub struct AnonConst {
1365 pub struct Expr<'hir> {
1367 pub kind: ExprKind<'hir>,
1372 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1373 #[cfg(target_arch = "x86_64")]
1374 rustc_data_structures::static_assert_size!(Expr<'static>, 72);
1377 pub fn precedence(&self) -> ExprPrecedence {
1379 ExprKind::Box(_) => ExprPrecedence::Box,
1380 ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1381 ExprKind::Array(_) => ExprPrecedence::Array,
1382 ExprKind::Call(..) => ExprPrecedence::Call,
1383 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1384 ExprKind::Tup(_) => ExprPrecedence::Tup,
1385 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1386 ExprKind::Unary(..) => ExprPrecedence::Unary,
1387 ExprKind::Lit(_) => ExprPrecedence::Lit,
1388 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1389 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1390 ExprKind::Loop(..) => ExprPrecedence::Loop,
1391 ExprKind::Match(..) => ExprPrecedence::Match,
1392 ExprKind::Closure(..) => ExprPrecedence::Closure,
1393 ExprKind::Block(..) => ExprPrecedence::Block,
1394 ExprKind::Assign(..) => ExprPrecedence::Assign,
1395 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1396 ExprKind::Field(..) => ExprPrecedence::Field,
1397 ExprKind::Index(..) => ExprPrecedence::Index,
1398 ExprKind::Path(..) => ExprPrecedence::Path,
1399 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1400 ExprKind::Break(..) => ExprPrecedence::Break,
1401 ExprKind::Continue(..) => ExprPrecedence::Continue,
1402 ExprKind::Ret(..) => ExprPrecedence::Ret,
1403 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1404 ExprKind::LlvmInlineAsm(..) => ExprPrecedence::InlineAsm,
1405 ExprKind::Struct(..) => ExprPrecedence::Struct,
1406 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1407 ExprKind::Yield(..) => ExprPrecedence::Yield,
1408 ExprKind::Err => ExprPrecedence::Err,
1412 // Whether this looks like a place expr, without checking for deref
1414 // This will return `true` in some potentially surprising cases such as
1415 // `CONSTANT.field`.
1416 pub fn is_syntactic_place_expr(&self) -> bool {
1417 self.is_place_expr(|_| true)
1420 /// Whether this is a place expression.
1422 /// `allow_projections_from` should return `true` if indexing a field or index expression based
1423 /// on the given expression should be considered a place expression.
1424 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1426 ExprKind::Path(QPath::Resolved(_, ref path)) => {
1427 matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static, _) | Res::Err)
1430 // Type ascription inherits its place expression kind from its
1432 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1433 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1435 ExprKind::Unary(UnOp::UnDeref, _) => true,
1437 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1438 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1441 // Lang item paths cannot currently be local variables or statics.
1442 ExprKind::Path(QPath::LangItem(..)) => false,
1444 // Partially qualified paths in expressions can only legally
1445 // refer to associated items which are always rvalues.
1446 ExprKind::Path(QPath::TypeRelative(..))
1447 | ExprKind::Call(..)
1448 | ExprKind::MethodCall(..)
1449 | ExprKind::Struct(..)
1451 | ExprKind::Match(..)
1452 | ExprKind::Closure(..)
1453 | ExprKind::Block(..)
1454 | ExprKind::Repeat(..)
1455 | ExprKind::Array(..)
1456 | ExprKind::Break(..)
1457 | ExprKind::Continue(..)
1459 | ExprKind::Loop(..)
1460 | ExprKind::Assign(..)
1461 | ExprKind::InlineAsm(..)
1462 | ExprKind::LlvmInlineAsm(..)
1463 | ExprKind::AssignOp(..)
1465 | ExprKind::ConstBlock(..)
1466 | ExprKind::Unary(..)
1468 | ExprKind::AddrOf(..)
1469 | ExprKind::Binary(..)
1470 | ExprKind::Yield(..)
1471 | ExprKind::Cast(..)
1472 | ExprKind::DropTemps(..)
1473 | ExprKind::Err => false,
1477 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1478 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1479 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1480 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1481 /// beyond remembering to call this function before doing analysis on it.
1482 pub fn peel_drop_temps(&self) -> &Self {
1483 let mut expr = self;
1484 while let ExprKind::DropTemps(inner) = &expr.kind {
1491 /// Checks if the specified expression is a built-in range literal.
1492 /// (See: `LoweringContext::lower_expr()`).
1493 pub fn is_range_literal(expr: &Expr<'_>) -> bool {
1495 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1496 ExprKind::Struct(ref qpath, _, _) => matches!(
1501 | LangItem::RangeFrom
1502 | LangItem::RangeFull
1503 | LangItem::RangeToInclusive,
1508 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1509 ExprKind::Call(ref func, _) => {
1510 matches!(func.kind, ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, _)))
1517 #[derive(Debug, HashStable_Generic)]
1518 pub enum ExprKind<'hir> {
1519 /// A `box x` expression.
1520 Box(&'hir Expr<'hir>),
1521 /// Allow anonymous constants from an inline `const` block
1522 ConstBlock(AnonConst),
1523 /// An array (e.g., `[a, b, c, d]`).
1524 Array(&'hir [Expr<'hir>]),
1525 /// A function call.
1527 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1528 /// and the second field is the list of arguments.
1529 /// This also represents calling the constructor of
1530 /// tuple-like ADTs such as tuple structs and enum variants.
1531 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1532 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1534 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1535 /// (within the angle brackets).
1536 /// The first element of the vector of `Expr`s is the expression that evaluates
1537 /// to the object on which the method is being called on (the receiver),
1538 /// and the remaining elements are the rest of the arguments.
1539 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1540 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1541 /// The final `Span` represents the span of the function and arguments
1542 /// (e.g. `foo::<Bar, Baz>(a, b, c, d)` in `x.foo::<Bar, Baz>(a, b, c, d)`
1544 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1545 /// the `hir_id` of the `MethodCall` node itself.
1547 /// [`type_dependent_def_id`]: ../ty/struct.TypeckResults.html#method.type_dependent_def_id
1548 MethodCall(&'hir PathSegment<'hir>, Span, &'hir [Expr<'hir>], Span),
1549 /// A tuple (e.g., `(a, b, c, d)`).
1550 Tup(&'hir [Expr<'hir>]),
1551 /// A binary operation (e.g., `a + b`, `a * b`).
1552 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1553 /// A unary operation (e.g., `!x`, `*x`).
1554 Unary(UnOp, &'hir Expr<'hir>),
1555 /// A literal (e.g., `1`, `"foo"`).
1557 /// A cast (e.g., `foo as f64`).
1558 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1559 /// A type reference (e.g., `Foo`).
1560 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1561 /// Wraps the expression in a terminating scope.
1562 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1564 /// This construct only exists to tweak the drop order in HIR lowering.
1565 /// An example of that is the desugaring of `for` loops.
1566 DropTemps(&'hir Expr<'hir>),
1567 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1569 /// I.e., `'label: loop { <block> }`.
1570 Loop(&'hir Block<'hir>, Option<Label>, LoopSource),
1571 /// A `match` block, with a source that indicates whether or not it is
1572 /// the result of a desugaring, and if so, which kind.
1573 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1574 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1576 /// The `Span` is the argument block `|...|`.
1578 /// This may also be a generator literal or an `async block` as indicated by the
1579 /// `Option<Movability>`.
1580 Closure(CaptureBy, &'hir FnDecl<'hir>, BodyId, Span, Option<Movability>),
1581 /// A block (e.g., `'label: { ... }`).
1582 Block(&'hir Block<'hir>, Option<Label>),
1584 /// An assignment (e.g., `a = foo()`).
1585 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1586 /// An assignment with an operator.
1589 AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1590 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1591 Field(&'hir Expr<'hir>, Ident),
1592 /// An indexing operation (`foo[2]`).
1593 Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1595 /// Path to a definition, possibly containing lifetime or type parameters.
1598 /// A referencing operation (i.e., `&a` or `&mut a`).
1599 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1600 /// A `break`, with an optional label to break.
1601 Break(Destination, Option<&'hir Expr<'hir>>),
1602 /// A `continue`, with an optional label.
1603 Continue(Destination),
1604 /// A `return`, with an optional value to be returned.
1605 Ret(Option<&'hir Expr<'hir>>),
1607 /// Inline assembly (from `asm!`), with its outputs and inputs.
1608 InlineAsm(&'hir InlineAsm<'hir>),
1609 /// Inline assembly (from `llvm_asm!`), with its outputs and inputs.
1610 LlvmInlineAsm(&'hir LlvmInlineAsm<'hir>),
1612 /// A struct or struct-like variant literal expression.
1614 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1615 /// where `base` is the `Option<Expr>`.
1616 Struct(&'hir QPath<'hir>, &'hir [Field<'hir>], Option<&'hir Expr<'hir>>),
1618 /// An array literal constructed from one repeated element.
1620 /// E.g., `[1; 5]`. The first expression is the element
1621 /// to be repeated; the second is the number of times to repeat it.
1622 Repeat(&'hir Expr<'hir>, AnonConst),
1624 /// A suspension point for generators (i.e., `yield <expr>`).
1625 Yield(&'hir Expr<'hir>, YieldSource),
1627 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1631 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1633 /// To resolve the path to a `DefId`, call [`qpath_res`].
1635 /// [`qpath_res`]: ../rustc_middle/ty/struct.TypeckResults.html#method.qpath_res
1636 #[derive(Debug, HashStable_Generic)]
1637 pub enum QPath<'hir> {
1638 /// Path to a definition, optionally "fully-qualified" with a `Self`
1639 /// type, if the path points to an associated item in a trait.
1641 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1642 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1643 /// even though they both have the same two-segment `Clone::clone` `Path`.
1644 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
1646 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1647 /// Will be resolved by type-checking to an associated item.
1649 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1650 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1651 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1652 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
1654 /// Reference to a `#[lang = "foo"]` item.
1655 LangItem(LangItem, Span),
1658 impl<'hir> QPath<'hir> {
1659 /// Returns the span of this `QPath`.
1660 pub fn span(&self) -> Span {
1662 QPath::Resolved(_, path) => path.span,
1663 QPath::TypeRelative(_, ps) => ps.ident.span,
1664 QPath::LangItem(_, span) => span,
1668 /// Returns the span of the qself of this `QPath`. For example, `()` in
1669 /// `<() as Trait>::method`.
1670 pub fn qself_span(&self) -> Span {
1672 QPath::Resolved(_, path) => path.span,
1673 QPath::TypeRelative(qself, _) => qself.span,
1674 QPath::LangItem(_, span) => span,
1678 /// Returns the span of the last segment of this `QPath`. For example, `method` in
1679 /// `<() as Trait>::method`.
1680 pub fn last_segment_span(&self) -> Span {
1682 QPath::Resolved(_, path) => path.segments.last().unwrap().ident.span,
1683 QPath::TypeRelative(_, segment) => segment.ident.span,
1684 QPath::LangItem(_, span) => span,
1689 /// Hints at the original code for a let statement.
1690 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1691 pub enum LocalSource {
1692 /// A `match _ { .. }`.
1694 /// A desugared `for _ in _ { .. }` loop.
1696 /// When lowering async functions, we create locals within the `async move` so that
1697 /// all parameters are dropped after the future is polled.
1699 /// ```ignore (pseudo-Rust)
1700 /// async fn foo(<pattern> @ x: Type) {
1702 /// let <pattern> = x;
1707 /// A desugared `<expr>.await`.
1709 /// A desugared `expr = expr`, where the LHS is a tuple, struct or array.
1710 /// The span is that of the `=` sign.
1711 AssignDesugar(Span),
1714 /// Hints at the original code for a `match _ { .. }`.
1715 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
1716 #[derive(HashStable_Generic)]
1717 pub enum MatchSource {
1718 /// A `match _ { .. }`.
1720 /// An `if _ { .. }` (optionally with `else { .. }`).
1721 IfDesugar { contains_else_clause: bool },
1722 /// An `if let _ = _ { .. }` (optionally with `else { .. }`).
1723 IfLetDesugar { contains_else_clause: bool },
1724 /// A `while _ { .. }` (which was desugared to a `loop { match _ { .. } }`).
1726 /// A `while let _ = _ { .. }` (which was desugared to a
1727 /// `loop { match _ { .. } }`).
1729 /// A desugared `for _ in _ { .. }` loop.
1731 /// A desugared `?` operator.
1733 /// A desugared `<expr>.await`.
1738 pub fn name(self) -> &'static str {
1742 IfDesugar { .. } | IfLetDesugar { .. } => "if",
1743 WhileDesugar | WhileLetDesugar => "while",
1744 ForLoopDesugar => "for",
1746 AwaitDesugar => ".await",
1751 /// The loop type that yielded an `ExprKind::Loop`.
1752 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1753 pub enum LoopSource {
1754 /// A `loop { .. }` loop.
1756 /// A `while _ { .. }` loop.
1758 /// A `while let _ = _ { .. }` loop.
1760 /// A `for _ in _ { .. }` loop.
1765 pub fn name(self) -> &'static str {
1767 LoopSource::Loop => "loop",
1768 LoopSource::While | LoopSource::WhileLet => "while",
1769 LoopSource::ForLoop => "for",
1774 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1775 pub enum LoopIdError {
1777 UnlabeledCfInWhileCondition,
1781 impl fmt::Display for LoopIdError {
1782 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1783 f.write_str(match self {
1784 LoopIdError::OutsideLoopScope => "not inside loop scope",
1785 LoopIdError::UnlabeledCfInWhileCondition => {
1786 "unlabeled control flow (break or continue) in while condition"
1788 LoopIdError::UnresolvedLabel => "label not found",
1793 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1794 pub struct Destination {
1795 // This is `Some(_)` iff there is an explicit user-specified `label
1796 pub label: Option<Label>,
1798 // These errors are caught and then reported during the diagnostics pass in
1799 // librustc_passes/loops.rs
1800 pub target_id: Result<HirId, LoopIdError>,
1803 /// The yield kind that caused an `ExprKind::Yield`.
1804 #[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
1805 pub enum YieldSource {
1806 /// An `<expr>.await`.
1807 Await { expr: Option<HirId> },
1808 /// A plain `yield`.
1813 pub fn is_await(&self) -> bool {
1815 YieldSource::Await { .. } => true,
1816 YieldSource::Yield => false,
1821 impl fmt::Display for YieldSource {
1822 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1823 f.write_str(match self {
1824 YieldSource::Await { .. } => "`await`",
1825 YieldSource::Yield => "`yield`",
1830 impl From<GeneratorKind> for YieldSource {
1831 fn from(kind: GeneratorKind) -> Self {
1833 // Guess based on the kind of the current generator.
1834 GeneratorKind::Gen => Self::Yield,
1835 GeneratorKind::Async(_) => Self::Await { expr: None },
1840 // N.B., if you change this, you'll probably want to change the corresponding
1841 // type structure in middle/ty.rs as well.
1842 #[derive(Debug, HashStable_Generic)]
1843 pub struct MutTy<'hir> {
1844 pub ty: &'hir Ty<'hir>,
1845 pub mutbl: Mutability,
1848 /// Represents a function's signature in a trait declaration,
1849 /// trait implementation, or a free function.
1850 #[derive(Debug, HashStable_Generic)]
1851 pub struct FnSig<'hir> {
1852 pub header: FnHeader,
1853 pub decl: &'hir FnDecl<'hir>,
1857 // The bodies for items are stored "out of line", in a separate
1858 // hashmap in the `Crate`. Here we just record the hir-id of the item
1859 // so it can fetched later.
1860 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
1861 pub struct TraitItemId {
1865 /// Represents an item declaration within a trait declaration,
1866 /// possibly including a default implementation. A trait item is
1867 /// either required (meaning it doesn't have an implementation, just a
1868 /// signature) or provided (meaning it has a default implementation).
1870 pub struct TraitItem<'hir> {
1873 pub attrs: &'hir [Attribute],
1874 pub generics: Generics<'hir>,
1875 pub kind: TraitItemKind<'hir>,
1879 /// Represents a trait method's body (or just argument names).
1880 #[derive(Encodable, Debug, HashStable_Generic)]
1881 pub enum TraitFn<'hir> {
1882 /// No default body in the trait, just a signature.
1883 Required(&'hir [Ident]),
1885 /// Both signature and body are provided in the trait.
1889 /// Represents a trait method or associated constant or type
1890 #[derive(Debug, HashStable_Generic)]
1891 pub enum TraitItemKind<'hir> {
1892 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
1893 Const(&'hir Ty<'hir>, Option<BodyId>),
1894 /// An associated function with an optional body.
1895 Fn(FnSig<'hir>, TraitFn<'hir>),
1896 /// An associated type with (possibly empty) bounds and optional concrete
1898 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
1901 // The bodies for items are stored "out of line", in a separate
1902 // hashmap in the `Crate`. Here we just record the hir-id of the item
1903 // so it can fetched later.
1904 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
1905 pub struct ImplItemId {
1909 /// Represents anything within an `impl` block.
1911 pub struct ImplItem<'hir> {
1914 pub vis: Visibility<'hir>,
1915 pub defaultness: Defaultness,
1916 pub attrs: &'hir [Attribute],
1917 pub generics: Generics<'hir>,
1918 pub kind: ImplItemKind<'hir>,
1922 /// Represents various kinds of content within an `impl`.
1923 #[derive(Debug, HashStable_Generic)]
1924 pub enum ImplItemKind<'hir> {
1925 /// An associated constant of the given type, set to the constant result
1926 /// of the expression.
1927 Const(&'hir Ty<'hir>, BodyId),
1928 /// An associated function implementation with the given signature and body.
1929 Fn(FnSig<'hir>, BodyId),
1930 /// An associated type.
1931 TyAlias(&'hir Ty<'hir>),
1934 impl ImplItemKind<'_> {
1935 pub fn namespace(&self) -> Namespace {
1937 ImplItemKind::TyAlias(..) => Namespace::TypeNS,
1938 ImplItemKind::Const(..) | ImplItemKind::Fn(..) => Namespace::ValueNS,
1943 // The name of the associated type for `Fn` return types.
1944 pub const FN_OUTPUT_NAME: Symbol = sym::Output;
1946 /// Bind a type to an associated type (i.e., `A = Foo`).
1948 /// Bindings like `A: Debug` are represented as a special type `A =
1949 /// $::Debug` that is understood by the astconv code.
1951 /// FIXME(alexreg): why have a separate type for the binding case,
1952 /// wouldn't it be better to make the `ty` field an enum like the
1956 /// enum TypeBindingKind {
1961 #[derive(Debug, HashStable_Generic)]
1962 pub struct TypeBinding<'hir> {
1964 #[stable_hasher(project(name))]
1966 pub kind: TypeBindingKind<'hir>,
1970 // Represents the two kinds of type bindings.
1971 #[derive(Debug, HashStable_Generic)]
1972 pub enum TypeBindingKind<'hir> {
1973 /// E.g., `Foo<Bar: Send>`.
1974 Constraint { bounds: &'hir [GenericBound<'hir>] },
1975 /// E.g., `Foo<Bar = ()>`.
1976 Equality { ty: &'hir Ty<'hir> },
1979 impl TypeBinding<'_> {
1980 pub fn ty(&self) -> &Ty<'_> {
1982 TypeBindingKind::Equality { ref ty } => ty,
1983 _ => panic!("expected equality type binding for parenthesized generic args"),
1989 pub struct Ty<'hir> {
1991 pub kind: TyKind<'hir>,
1995 /// Not represented directly in the AST; referred to by name through a `ty_path`.
1996 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
1997 #[derive(HashStable_Generic)]
2008 pub fn name_str(self) -> &'static str {
2010 PrimTy::Int(i) => i.name_str(),
2011 PrimTy::Uint(u) => u.name_str(),
2012 PrimTy::Float(f) => f.name_str(),
2013 PrimTy::Str => "str",
2014 PrimTy::Bool => "bool",
2015 PrimTy::Char => "char",
2019 pub fn name(self) -> Symbol {
2021 PrimTy::Int(i) => i.name(),
2022 PrimTy::Uint(u) => u.name(),
2023 PrimTy::Float(f) => f.name(),
2024 PrimTy::Str => sym::str,
2025 PrimTy::Bool => sym::bool,
2026 PrimTy::Char => sym::char,
2031 #[derive(Debug, HashStable_Generic)]
2032 pub struct BareFnTy<'hir> {
2033 pub unsafety: Unsafety,
2035 pub generic_params: &'hir [GenericParam<'hir>],
2036 pub decl: &'hir FnDecl<'hir>,
2037 pub param_names: &'hir [Ident],
2040 #[derive(Debug, HashStable_Generic)]
2041 pub struct OpaqueTy<'hir> {
2042 pub generics: Generics<'hir>,
2043 pub bounds: GenericBounds<'hir>,
2044 pub impl_trait_fn: Option<DefId>,
2045 pub origin: OpaqueTyOrigin,
2048 /// From whence the opaque type came.
2049 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2050 pub enum OpaqueTyOrigin {
2055 /// `let _: impl Trait = ...`
2057 /// Impl trait in type aliases, consts, statics, bounds.
2061 /// The various kinds of types recognized by the compiler.
2062 #[derive(Debug, HashStable_Generic)]
2063 pub enum TyKind<'hir> {
2064 /// A variable length slice (i.e., `[T]`).
2065 Slice(&'hir Ty<'hir>),
2066 /// A fixed length array (i.e., `[T; n]`).
2067 Array(&'hir Ty<'hir>, AnonConst),
2068 /// A raw pointer (i.e., `*const T` or `*mut T`).
2070 /// A reference (i.e., `&'a T` or `&'a mut T`).
2071 Rptr(Lifetime, MutTy<'hir>),
2072 /// A bare function (e.g., `fn(usize) -> bool`).
2073 BareFn(&'hir BareFnTy<'hir>),
2074 /// The never type (`!`).
2076 /// A tuple (`(A, B, C, D, ...)`).
2077 Tup(&'hir [Ty<'hir>]),
2078 /// A path to a type definition (`module::module::...::Type`), or an
2079 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2081 /// Type parameters may be stored in each `PathSegment`.
2083 /// A opaque type definition itself. This is currently only used for the
2084 /// `opaque type Foo: Trait` item that `impl Trait` in desugars to.
2086 /// The generic argument list contains the lifetimes (and in the future
2087 /// possibly parameters) that are actually bound on the `impl Trait`.
2088 OpaqueDef(ItemId, &'hir [GenericArg<'hir>]),
2089 /// A trait object type `Bound1 + Bound2 + Bound3`
2090 /// where `Bound` is a trait or a lifetime.
2091 TraitObject(&'hir [PolyTraitRef<'hir>], Lifetime),
2094 /// `TyKind::Infer` means the type should be inferred instead of it having been
2095 /// specified. This can appear anywhere in a type.
2097 /// Placeholder for a type that has failed to be defined.
2101 #[derive(Debug, HashStable_Generic)]
2102 pub enum InlineAsmOperand<'hir> {
2104 reg: InlineAsmRegOrRegClass,
2108 reg: InlineAsmRegOrRegClass,
2110 expr: Option<Expr<'hir>>,
2113 reg: InlineAsmRegOrRegClass,
2118 reg: InlineAsmRegOrRegClass,
2120 in_expr: Expr<'hir>,
2121 out_expr: Option<Expr<'hir>>,
2131 impl<'hir> InlineAsmOperand<'hir> {
2132 pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
2134 Self::In { reg, .. }
2135 | Self::Out { reg, .. }
2136 | Self::InOut { reg, .. }
2137 | Self::SplitInOut { reg, .. } => Some(reg),
2138 Self::Const { .. } | Self::Sym { .. } => None,
2143 #[derive(Debug, HashStable_Generic)]
2144 pub struct InlineAsm<'hir> {
2145 pub template: &'hir [InlineAsmTemplatePiece],
2146 pub operands: &'hir [InlineAsmOperand<'hir>],
2147 pub options: InlineAsmOptions,
2148 pub line_spans: &'hir [Span],
2151 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic, PartialEq)]
2152 pub struct LlvmInlineAsmOutput {
2153 pub constraint: Symbol,
2155 pub is_indirect: bool,
2159 // NOTE(eddyb) This is used within MIR as well, so unlike the rest of the HIR,
2160 // it needs to be `Clone` and `Decodable` and use plain `Vec<T>` instead of
2161 // arena-allocated slice.
2162 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic, PartialEq)]
2163 pub struct LlvmInlineAsmInner {
2165 pub asm_str_style: StrStyle,
2166 pub outputs: Vec<LlvmInlineAsmOutput>,
2167 pub inputs: Vec<Symbol>,
2168 pub clobbers: Vec<Symbol>,
2170 pub alignstack: bool,
2171 pub dialect: LlvmAsmDialect,
2174 #[derive(Debug, HashStable_Generic)]
2175 pub struct LlvmInlineAsm<'hir> {
2176 pub inner: LlvmInlineAsmInner,
2177 pub outputs_exprs: &'hir [Expr<'hir>],
2178 pub inputs_exprs: &'hir [Expr<'hir>],
2181 /// Represents a parameter in a function header.
2182 #[derive(Debug, HashStable_Generic)]
2183 pub struct Param<'hir> {
2184 pub attrs: &'hir [Attribute],
2186 pub pat: &'hir Pat<'hir>,
2191 /// Represents the header (not the body) of a function declaration.
2192 #[derive(Debug, HashStable_Generic)]
2193 pub struct FnDecl<'hir> {
2194 /// The types of the function's parameters.
2196 /// Additional argument data is stored in the function's [body](Body::params).
2197 pub inputs: &'hir [Ty<'hir>],
2198 pub output: FnRetTy<'hir>,
2199 pub c_variadic: bool,
2200 /// Does the function have an implicit self?
2201 pub implicit_self: ImplicitSelfKind,
2204 /// Represents what type of implicit self a function has, if any.
2205 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2206 pub enum ImplicitSelfKind {
2207 /// Represents a `fn x(self);`.
2209 /// Represents a `fn x(mut self);`.
2211 /// Represents a `fn x(&self);`.
2213 /// Represents a `fn x(&mut self);`.
2215 /// Represents when a function does not have a self argument or
2216 /// when a function has a `self: X` argument.
2220 impl ImplicitSelfKind {
2221 /// Does this represent an implicit self?
2222 pub fn has_implicit_self(&self) -> bool {
2223 !matches!(*self, ImplicitSelfKind::None)
2227 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable, Debug)]
2228 #[derive(HashStable_Generic)]
2234 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable, HashStable_Generic)]
2235 pub enum Defaultness {
2236 Default { has_value: bool },
2241 pub fn has_value(&self) -> bool {
2243 Defaultness::Default { has_value } => has_value,
2244 Defaultness::Final => true,
2248 pub fn is_final(&self) -> bool {
2249 *self == Defaultness::Final
2252 pub fn is_default(&self) -> bool {
2253 matches!(*self, Defaultness::Default { .. })
2257 #[derive(Debug, HashStable_Generic)]
2258 pub enum FnRetTy<'hir> {
2259 /// Return type is not specified.
2261 /// Functions default to `()` and
2262 /// closures default to inference. Span points to where return
2263 /// type would be inserted.
2264 DefaultReturn(Span),
2265 /// Everything else.
2266 Return(&'hir Ty<'hir>),
2270 pub fn span(&self) -> Span {
2272 Self::DefaultReturn(span) => span,
2273 Self::Return(ref ty) => ty.span,
2278 #[derive(Encodable, Debug)]
2279 pub struct Mod<'hir> {
2280 /// A span from the first token past `{` to the last token until `}`.
2281 /// For `mod foo;`, the inner span ranges from the first token
2282 /// to the last token in the external file.
2284 pub item_ids: &'hir [ItemId],
2287 #[derive(Encodable, Debug, HashStable_Generic)]
2288 pub struct GlobalAsm {
2292 #[derive(Debug, HashStable_Generic)]
2293 pub struct EnumDef<'hir> {
2294 pub variants: &'hir [Variant<'hir>],
2297 #[derive(Debug, HashStable_Generic)]
2298 pub struct Variant<'hir> {
2299 /// Name of the variant.
2300 #[stable_hasher(project(name))]
2302 /// Attributes of the variant.
2303 pub attrs: &'hir [Attribute],
2304 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2306 /// Fields and constructor id of the variant.
2307 pub data: VariantData<'hir>,
2308 /// Explicit discriminant (e.g., `Foo = 1`).
2309 pub disr_expr: Option<AnonConst>,
2314 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2316 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2317 /// Also produced for each element of a list `use`, e.g.
2318 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2321 /// Glob import, e.g., `use foo::*`.
2324 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2325 /// an additional `use foo::{}` for performing checks such as
2326 /// unstable feature gating. May be removed in the future.
2330 /// References to traits in impls.
2332 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2333 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2334 /// trait being referred to but just a unique `HirId` that serves as a key
2335 /// within the resolution map.
2336 #[derive(Debug, HashStable_Generic)]
2337 pub struct TraitRef<'hir> {
2338 pub path: &'hir Path<'hir>,
2339 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2340 #[stable_hasher(ignore)]
2341 pub hir_ref_id: HirId,
2345 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2346 pub fn trait_def_id(&self) -> Option<DefId> {
2347 match self.path.res {
2348 Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
2350 _ => unreachable!(),
2355 #[derive(Debug, HashStable_Generic)]
2356 pub struct PolyTraitRef<'hir> {
2357 /// The `'a` in `for<'a> Foo<&'a T>`.
2358 pub bound_generic_params: &'hir [GenericParam<'hir>],
2360 /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
2361 pub trait_ref: TraitRef<'hir>,
2366 pub type Visibility<'hir> = Spanned<VisibilityKind<'hir>>;
2369 pub enum VisibilityKind<'hir> {
2372 Restricted { path: &'hir Path<'hir>, hir_id: HirId },
2376 impl VisibilityKind<'_> {
2377 pub fn is_pub(&self) -> bool {
2378 matches!(*self, VisibilityKind::Public)
2381 pub fn is_pub_restricted(&self) -> bool {
2383 VisibilityKind::Public | VisibilityKind::Inherited => false,
2384 VisibilityKind::Crate(..) | VisibilityKind::Restricted { .. } => true,
2389 #[derive(Debug, HashStable_Generic)]
2390 pub struct StructField<'hir> {
2392 #[stable_hasher(project(name))]
2394 pub vis: Visibility<'hir>,
2396 pub ty: &'hir Ty<'hir>,
2397 pub attrs: &'hir [Attribute],
2400 impl StructField<'_> {
2401 // Still necessary in couple of places
2402 pub fn is_positional(&self) -> bool {
2403 let first = self.ident.as_str().as_bytes()[0];
2404 (b'0'..=b'9').contains(&first)
2408 /// Fields and constructor IDs of enum variants and structs.
2409 #[derive(Debug, HashStable_Generic)]
2410 pub enum VariantData<'hir> {
2411 /// A struct variant.
2413 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2414 Struct(&'hir [StructField<'hir>], /* recovered */ bool),
2415 /// A tuple variant.
2417 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2418 Tuple(&'hir [StructField<'hir>], HirId),
2421 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2425 impl VariantData<'hir> {
2426 /// Return the fields of this variant.
2427 pub fn fields(&self) -> &'hir [StructField<'hir>] {
2429 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2434 /// Return the `HirId` of this variant's constructor, if it has one.
2435 pub fn ctor_hir_id(&self) -> Option<HirId> {
2437 VariantData::Struct(_, _) => None,
2438 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2443 // The bodies for items are stored "out of line", in a separate
2444 // hashmap in the `Crate`. Here we just record the hir-id of the item
2445 // so it can fetched later.
2446 #[derive(Copy, Clone, Encodable, Debug)]
2453 /// The name might be a dummy name in case of anonymous items
2455 pub struct Item<'hir> {
2458 pub attrs: &'hir [Attribute],
2459 pub kind: ItemKind<'hir>,
2460 pub vis: Visibility<'hir>,
2464 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2465 #[derive(Encodable, Decodable, HashStable_Generic)]
2472 pub fn prefix_str(&self) -> &'static str {
2474 Self::Unsafe => "unsafe ",
2480 impl fmt::Display for Unsafety {
2481 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2482 f.write_str(match *self {
2483 Self::Unsafe => "unsafe",
2484 Self::Normal => "normal",
2489 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2490 #[derive(Encodable, Decodable, HashStable_Generic)]
2491 pub enum Constness {
2496 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2497 pub struct FnHeader {
2498 pub unsafety: Unsafety,
2499 pub constness: Constness,
2500 pub asyncness: IsAsync,
2505 pub fn is_const(&self) -> bool {
2506 matches!(&self.constness, Constness::Const)
2510 #[derive(Debug, HashStable_Generic)]
2511 pub enum ItemKind<'hir> {
2512 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2514 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2515 ExternCrate(Option<Symbol>),
2517 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2521 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2522 Use(&'hir Path<'hir>, UseKind),
2524 /// A `static` item.
2525 Static(&'hir Ty<'hir>, Mutability, BodyId),
2527 Const(&'hir Ty<'hir>, BodyId),
2528 /// A function declaration.
2529 Fn(FnSig<'hir>, Generics<'hir>, BodyId),
2532 /// An external module, e.g. `extern { .. }`.
2533 ForeignMod { abi: Abi, items: &'hir [ForeignItemRef<'hir>] },
2534 /// Module-level inline assembly (from `global_asm!`).
2535 GlobalAsm(&'hir GlobalAsm),
2536 /// A type alias, e.g., `type Foo = Bar<u8>`.
2537 TyAlias(&'hir Ty<'hir>, Generics<'hir>),
2538 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2539 OpaqueTy(OpaqueTy<'hir>),
2540 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2541 Enum(EnumDef<'hir>, Generics<'hir>),
2542 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2543 Struct(VariantData<'hir>, Generics<'hir>),
2544 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2545 Union(VariantData<'hir>, Generics<'hir>),
2546 /// A trait definition.
2547 Trait(IsAuto, Unsafety, Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
2549 TraitAlias(Generics<'hir>, GenericBounds<'hir>),
2551 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2554 polarity: ImplPolarity,
2555 defaultness: Defaultness,
2556 // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata
2557 // decoding as `Span`s cannot be decoded when a `Session` is not available.
2558 defaultness_span: Option<Span>,
2559 constness: Constness,
2560 generics: Generics<'hir>,
2562 /// The trait being implemented, if any.
2563 of_trait: Option<TraitRef<'hir>>,
2565 self_ty: &'hir Ty<'hir>,
2566 items: &'hir [ImplItemRef<'hir>],
2571 pub fn generics(&self) -> Option<&Generics<'_>> {
2573 ItemKind::Fn(_, ref generics, _)
2574 | ItemKind::TyAlias(_, ref generics)
2575 | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
2576 | ItemKind::Enum(_, ref generics)
2577 | ItemKind::Struct(_, ref generics)
2578 | ItemKind::Union(_, ref generics)
2579 | ItemKind::Trait(_, _, ref generics, _, _)
2580 | ItemKind::Impl { ref generics, .. } => generics,
2586 /// A reference from an trait to one of its associated items. This
2587 /// contains the item's id, naturally, but also the item's name and
2588 /// some other high-level details (like whether it is an associated
2589 /// type or method, and whether it is public). This allows other
2590 /// passes to find the impl they want without loading the ID (which
2591 /// means fewer edges in the incremental compilation graph).
2592 #[derive(Encodable, Debug, HashStable_Generic)]
2593 pub struct TraitItemRef {
2594 pub id: TraitItemId,
2595 #[stable_hasher(project(name))]
2597 pub kind: AssocItemKind,
2599 pub defaultness: Defaultness,
2602 /// A reference from an impl to one of its associated items. This
2603 /// contains the item's ID, naturally, but also the item's name and
2604 /// some other high-level details (like whether it is an associated
2605 /// type or method, and whether it is public). This allows other
2606 /// passes to find the impl they want without loading the ID (which
2607 /// means fewer edges in the incremental compilation graph).
2608 #[derive(Debug, HashStable_Generic)]
2609 pub struct ImplItemRef<'hir> {
2611 #[stable_hasher(project(name))]
2613 pub kind: AssocItemKind,
2615 pub vis: Visibility<'hir>,
2616 pub defaultness: Defaultness,
2619 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2620 pub enum AssocItemKind {
2622 Fn { has_self: bool },
2626 // The bodies for items are stored "out of line", in a separate
2627 // hashmap in the `Crate`. Here we just record the hir-id of the item
2628 // so it can fetched later.
2629 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
2630 pub struct ForeignItemId {
2634 /// A reference from a foreign block to one of its items. This
2635 /// contains the item's ID, naturally, but also the item's name and
2636 /// some other high-level details (like whether it is an associated
2637 /// type or method, and whether it is public). This allows other
2638 /// passes to find the impl they want without loading the ID (which
2639 /// means fewer edges in the incremental compilation graph).
2640 #[derive(Debug, HashStable_Generic)]
2641 pub struct ForeignItemRef<'hir> {
2642 pub id: ForeignItemId,
2643 #[stable_hasher(project(name))]
2646 pub vis: Visibility<'hir>,
2649 #[derive(Debug, HashStable_Generic)]
2650 pub struct ForeignItem<'hir> {
2651 #[stable_hasher(project(name))]
2653 pub attrs: &'hir [Attribute],
2654 pub kind: ForeignItemKind<'hir>,
2657 pub vis: Visibility<'hir>,
2660 /// An item within an `extern` block.
2661 #[derive(Debug, HashStable_Generic)]
2662 pub enum ForeignItemKind<'hir> {
2663 /// A foreign function.
2664 Fn(&'hir FnDecl<'hir>, &'hir [Ident], Generics<'hir>),
2665 /// A foreign static item (`static ext: u8`).
2666 Static(&'hir Ty<'hir>, Mutability),
2671 /// A variable captured by a closure.
2672 #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)]
2674 // First span where it is accessed (there can be multiple).
2678 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2679 // has length > 0 if the trait is found through an chain of imports, starting with the
2680 // import/use statement in the scope where the trait is used.
2681 #[derive(Encodable, Decodable, Clone, Debug)]
2682 pub struct TraitCandidate {
2684 pub import_ids: SmallVec<[LocalDefId; 1]>,
2687 #[derive(Copy, Clone, Debug, HashStable_Generic)]
2688 pub enum Node<'hir> {
2689 Param(&'hir Param<'hir>),
2690 Item(&'hir Item<'hir>),
2691 ForeignItem(&'hir ForeignItem<'hir>),
2692 TraitItem(&'hir TraitItem<'hir>),
2693 ImplItem(&'hir ImplItem<'hir>),
2694 Variant(&'hir Variant<'hir>),
2695 Field(&'hir StructField<'hir>),
2696 AnonConst(&'hir AnonConst),
2697 Expr(&'hir Expr<'hir>),
2698 Stmt(&'hir Stmt<'hir>),
2699 PathSegment(&'hir PathSegment<'hir>),
2701 TraitRef(&'hir TraitRef<'hir>),
2702 Binding(&'hir Pat<'hir>),
2703 Pat(&'hir Pat<'hir>),
2704 Arm(&'hir Arm<'hir>),
2705 Block(&'hir Block<'hir>),
2706 Local(&'hir Local<'hir>),
2707 MacroDef(&'hir MacroDef<'hir>),
2709 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
2710 /// with synthesized constructors.
2711 Ctor(&'hir VariantData<'hir>),
2713 Lifetime(&'hir Lifetime),
2714 GenericParam(&'hir GenericParam<'hir>),
2715 Visibility(&'hir Visibility<'hir>),
2717 Crate(&'hir CrateItem<'hir>),
2720 impl<'hir> Node<'hir> {
2721 pub fn ident(&self) -> Option<Ident> {
2723 Node::TraitItem(TraitItem { ident, .. })
2724 | Node::ImplItem(ImplItem { ident, .. })
2725 | Node::ForeignItem(ForeignItem { ident, .. })
2726 | Node::Field(StructField { ident, .. })
2727 | Node::Variant(Variant { ident, .. })
2728 | Node::MacroDef(MacroDef { ident, .. })
2729 | Node::Item(Item { ident, .. }) => Some(*ident),
2734 pub fn fn_decl(&self) -> Option<&FnDecl<'hir>> {
2736 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
2737 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
2738 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
2739 Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
2746 pub fn body_id(&self) -> Option<BodyId> {
2748 Node::TraitItem(TraitItem {
2749 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
2752 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
2753 | Node::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
2758 pub fn generics(&self) -> Option<&'hir Generics<'hir>> {
2760 Node::TraitItem(TraitItem { generics, .. })
2761 | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
2762 Node::Item(item) => item.kind.generics(),
2767 pub fn hir_id(&self) -> Option<HirId> {
2769 Node::Item(Item { hir_id, .. })
2770 | Node::ForeignItem(ForeignItem { hir_id, .. })
2771 | Node::TraitItem(TraitItem { hir_id, .. })
2772 | Node::ImplItem(ImplItem { hir_id, .. })
2773 | Node::Field(StructField { hir_id, .. })
2774 | Node::AnonConst(AnonConst { hir_id, .. })
2775 | Node::Expr(Expr { hir_id, .. })
2776 | Node::Stmt(Stmt { hir_id, .. })
2777 | Node::Ty(Ty { hir_id, .. })
2778 | Node::Binding(Pat { hir_id, .. })
2779 | Node::Pat(Pat { hir_id, .. })
2780 | Node::Arm(Arm { hir_id, .. })
2781 | Node::Block(Block { hir_id, .. })
2782 | Node::Local(Local { hir_id, .. })
2783 | Node::MacroDef(MacroDef { hir_id, .. })
2784 | Node::Lifetime(Lifetime { hir_id, .. })
2785 | Node::Param(Param { hir_id, .. })
2786 | Node::GenericParam(GenericParam { hir_id, .. }) => Some(*hir_id),
2787 Node::TraitRef(TraitRef { hir_ref_id, .. }) => Some(*hir_ref_id),
2788 Node::PathSegment(PathSegment { hir_id, .. }) => *hir_id,
2789 Node::Variant(Variant { id, .. }) => Some(*id),
2790 Node::Ctor(variant) => variant.ctor_hir_id(),
2791 Node::Crate(_) | Node::Visibility(_) => None,