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::node_id::NodeMap;
7 use rustc_ast::util::parser::ExprPrecedence;
8 use rustc_ast::{self as ast, CrateSugar, LlvmAsmDialect};
9 use rustc_ast::{AttrVec, Attribute, FloatTy, IntTy, Label, LitKind, StrStyle, UintTy};
10 pub use rustc_ast::{BorrowKind, ImplPolarity, IsAuto};
11 pub use rustc_ast::{CaptureBy, Movability, Mutability};
12 use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
13 use rustc_data_structures::sync::{par_for_each_in, Send, Sync};
14 use rustc_macros::HashStable_Generic;
15 use rustc_span::def_id::LocalDefId;
16 use rustc_span::source_map::Spanned;
17 use rustc_span::symbol::{kw, sym, Ident, Symbol};
18 use rustc_span::{MultiSpan, Span, DUMMY_SP};
19 use rustc_target::asm::InlineAsmRegOrRegClass;
20 use rustc_target::spec::abi::Abi;
22 use smallvec::SmallVec;
23 use std::collections::{BTreeMap, BTreeSet};
26 #[derive(Copy, Clone, Encodable, HashStable_Generic)]
31 /// Either "`'a`", referring to a named lifetime definition,
32 /// or "``" (i.e., `kw::Invalid`), for elision placeholders.
34 /// HIR lowering inserts these placeholders in type paths that
35 /// refer to type definitions needing lifetime parameters,
36 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
37 pub name: LifetimeName,
40 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
41 #[derive(HashStable_Generic)]
43 /// Some user-given name like `T` or `'x`.
46 /// Synthetic name generated when user elided a lifetime in an impl header.
48 /// E.g., the lifetimes in cases like these:
51 /// impl Foo<'_> for u32
53 /// in that case, we rewrite to
55 /// impl<'f> Foo for &'f u32
56 /// impl<'f> Foo<'f> for u32
58 /// where `'f` is something like `Fresh(0)`. The indices are
59 /// unique per impl, but not necessarily continuous.
62 /// Indicates an illegal name was given and an error has been
63 /// reported (so we should squelch other derived errors). Occurs
64 /// when, e.g., `'_` is used in the wrong place.
69 pub fn ident(&self) -> Ident {
71 ParamName::Plain(ident) => ident,
72 ParamName::Fresh(_) | ParamName::Error => {
73 Ident::with_dummy_span(kw::UnderscoreLifetime)
78 pub fn normalize_to_macros_2_0(&self) -> ParamName {
80 ParamName::Plain(ident) => ParamName::Plain(ident.normalize_to_macros_2_0()),
81 param_name => param_name,
86 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
87 #[derive(HashStable_Generic)]
88 pub enum LifetimeName {
89 /// User-given names or fresh (synthetic) names.
92 /// User wrote nothing (e.g., the lifetime in `&u32`).
95 /// Implicit lifetime in a context like `dyn Foo`. This is
96 /// distinguished from implicit lifetimes elsewhere because the
97 /// lifetime that they default to must appear elsewhere within the
98 /// enclosing type. This means that, in an `impl Trait` context, we
99 /// don't have to create a parameter for them. That is, `impl
100 /// Trait<Item = &u32>` expands to an opaque type like `type
101 /// Foo<'a> = impl Trait<Item = &'a u32>`, but `impl Trait<item =
102 /// dyn Bar>` expands to `type Foo = impl Trait<Item = dyn Bar +
103 /// 'static>`. The latter uses `ImplicitObjectLifetimeDefault` so
104 /// that surrounding code knows not to create a lifetime
106 ImplicitObjectLifetimeDefault,
108 /// Indicates an error during lowering (usually `'_` in wrong place)
109 /// that was already reported.
112 /// User wrote specifies `'_`.
115 /// User wrote `'static`.
120 pub fn ident(&self) -> Ident {
122 LifetimeName::ImplicitObjectLifetimeDefault
123 | LifetimeName::Implicit
124 | LifetimeName::Error => Ident::invalid(),
125 LifetimeName::Underscore => Ident::with_dummy_span(kw::UnderscoreLifetime),
126 LifetimeName::Static => Ident::with_dummy_span(kw::StaticLifetime),
127 LifetimeName::Param(param_name) => param_name.ident(),
131 pub fn is_elided(&self) -> bool {
133 LifetimeName::ImplicitObjectLifetimeDefault
134 | LifetimeName::Implicit
135 | LifetimeName::Underscore => true,
137 // It might seem surprising that `Fresh(_)` counts as
138 // *not* elided -- but this is because, as far as the code
139 // in the compiler is concerned -- `Fresh(_)` variants act
140 // equivalently to "some fresh name". They correspond to
141 // early-bound regions on an impl, in other words.
142 LifetimeName::Error | LifetimeName::Param(_) | LifetimeName::Static => false,
146 fn is_static(&self) -> bool {
147 self == &LifetimeName::Static
150 pub fn normalize_to_macros_2_0(&self) -> LifetimeName {
152 LifetimeName::Param(param_name) => {
153 LifetimeName::Param(param_name.normalize_to_macros_2_0())
155 lifetime_name => lifetime_name,
160 impl fmt::Display for Lifetime {
161 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162 self.name.ident().fmt(f)
166 impl fmt::Debug for Lifetime {
167 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168 write!(f, "lifetime({}: {})", self.hir_id, self.name.ident())
173 pub fn is_elided(&self) -> bool {
174 self.name.is_elided()
177 pub fn is_static(&self) -> bool {
178 self.name.is_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.
205 #[stable_hasher(project(name))]
207 // `id` and `res` are optional. We currently only use these in save-analysis,
208 // any path segments without these will not have save-analysis info and
209 // therefore will not have 'jump to def' in IDEs, but otherwise will not be
210 // affected. (In general, we don't bother to get the defs for synthesized
211 // segments, only for segments which have come from the AST).
212 pub hir_id: Option<HirId>,
213 pub res: Option<Res>,
215 /// Type/lifetime parameters attached to this path. They come in
216 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
217 /// this is more than just simple syntactic sugar; the use of
218 /// parens affects the region binding rules, so we preserve the
220 pub args: Option<&'hir GenericArgs<'hir>>,
222 /// Whether to infer remaining type parameters, if any.
223 /// This only applies to expression and pattern paths, and
224 /// out of those only the segments with no type parameters
225 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
226 pub infer_args: bool,
229 impl<'hir> PathSegment<'hir> {
230 /// Converts an identifier to the corresponding segment.
231 pub fn from_ident(ident: Ident) -> PathSegment<'hir> {
232 PathSegment { ident, hir_id: None, res: None, infer_args: true, args: None }
235 pub fn generic_args(&self) -> &GenericArgs<'hir> {
236 if let Some(ref args) = self.args {
239 const DUMMY: &GenericArgs<'_> = &GenericArgs::none();
245 #[derive(Encodable, Debug, HashStable_Generic)]
246 pub struct ConstArg {
247 pub value: AnonConst,
251 #[derive(Debug, HashStable_Generic)]
252 pub enum GenericArg<'hir> {
258 impl GenericArg<'_> {
259 pub fn span(&self) -> Span {
261 GenericArg::Lifetime(l) => l.span,
262 GenericArg::Type(t) => t.span,
263 GenericArg::Const(c) => c.span,
267 pub fn id(&self) -> HirId {
269 GenericArg::Lifetime(l) => l.hir_id,
270 GenericArg::Type(t) => t.hir_id,
271 GenericArg::Const(c) => c.value.hir_id,
275 pub fn is_const(&self) -> bool {
277 GenericArg::Const(_) => true,
282 pub fn descr(&self) -> &'static str {
284 GenericArg::Lifetime(_) => "lifetime",
285 GenericArg::Type(_) => "type",
286 GenericArg::Const(_) => "constant",
291 #[derive(Debug, HashStable_Generic)]
292 pub struct GenericArgs<'hir> {
293 /// The generic arguments for this path segment.
294 pub args: &'hir [GenericArg<'hir>],
295 /// Bindings (equality constraints) on associated types, if present.
296 /// E.g., `Foo<A = Bar>`.
297 pub bindings: &'hir [TypeBinding<'hir>],
298 /// Were arguments written in parenthesized form `Fn(T) -> U`?
299 /// This is required mostly for pretty-printing and diagnostics,
300 /// but also for changing lifetime elision rules to be "function-like".
301 pub parenthesized: bool,
304 impl GenericArgs<'_> {
305 pub const fn none() -> Self {
306 Self { args: &[], bindings: &[], parenthesized: false }
309 pub fn is_empty(&self) -> bool {
310 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
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 own_counts(&self) -> GenericParamCount {
471 // We could cache this as a property of `GenericParamCount`, but
472 // the aim is to refactor this away entirely eventually and the
473 // presence of this method will be a constant reminder.
474 let mut own_counts: GenericParamCount = Default::default();
476 for param in self.params {
478 GenericParamKind::Lifetime { .. } => own_counts.lifetimes += 1,
479 GenericParamKind::Type { .. } => own_counts.types += 1,
480 GenericParamKind::Const { .. } => own_counts.consts += 1,
487 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'_>> {
488 for param in self.params {
489 if name == param.name.ident().name {
496 pub fn spans(&self) -> MultiSpan {
497 if self.params.is_empty() {
500 self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
505 /// Synthetic type parameters are converted to another form during lowering; this allows
506 /// us to track the original form they had, and is useful for error messages.
507 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
508 #[derive(HashStable_Generic)]
509 pub enum SyntheticTyParamKind {
513 /// A where-clause in a definition.
514 #[derive(Debug, HashStable_Generic)]
515 pub struct WhereClause<'hir> {
516 pub predicates: &'hir [WherePredicate<'hir>],
517 // Only valid if predicates aren't empty.
521 impl WhereClause<'_> {
522 pub fn span(&self) -> Option<Span> {
523 if self.predicates.is_empty() { None } else { Some(self.span) }
526 /// The `WhereClause` under normal circumstances points at either the predicates or the empty
527 /// space where the `where` clause should be. Only of use for diagnostic suggestions.
528 pub fn span_for_predicates_or_empty_place(&self) -> Span {
532 /// `Span` where further predicates would be suggested, accounting for trailing commas, like
533 /// in `fn foo<T>(t: T) where T: Foo,` so we don't suggest two trailing commas.
534 pub fn tail_span_for_suggestion(&self) -> Span {
535 let end = self.span_for_predicates_or_empty_place().shrink_to_hi();
536 self.predicates.last().map(|p| p.span()).unwrap_or(end).shrink_to_hi().to(end)
540 /// A single predicate in a where-clause.
541 #[derive(Debug, HashStable_Generic)]
542 pub enum WherePredicate<'hir> {
543 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
544 BoundPredicate(WhereBoundPredicate<'hir>),
545 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
546 RegionPredicate(WhereRegionPredicate<'hir>),
547 /// An equality predicate (unsupported).
548 EqPredicate(WhereEqPredicate<'hir>),
551 impl WherePredicate<'_> {
552 pub fn span(&self) -> Span {
554 &WherePredicate::BoundPredicate(ref p) => p.span,
555 &WherePredicate::RegionPredicate(ref p) => p.span,
556 &WherePredicate::EqPredicate(ref p) => p.span,
561 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
562 #[derive(Debug, HashStable_Generic)]
563 pub struct WhereBoundPredicate<'hir> {
565 /// Any generics from a `for` binding.
566 pub bound_generic_params: &'hir [GenericParam<'hir>],
567 /// The type being bounded.
568 pub bounded_ty: &'hir Ty<'hir>,
569 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
570 pub bounds: GenericBounds<'hir>,
573 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
574 #[derive(Debug, HashStable_Generic)]
575 pub struct WhereRegionPredicate<'hir> {
577 pub lifetime: Lifetime,
578 pub bounds: GenericBounds<'hir>,
581 /// An equality predicate (e.g., `T = int`); currently unsupported.
582 #[derive(Debug, HashStable_Generic)]
583 pub struct WhereEqPredicate<'hir> {
586 pub lhs_ty: &'hir Ty<'hir>,
587 pub rhs_ty: &'hir Ty<'hir>,
590 #[derive(Encodable, Debug, HashStable_Generic)]
591 pub struct ModuleItems {
592 // Use BTreeSets here so items are in the same order as in the
593 // list of all items in Crate
594 pub items: BTreeSet<HirId>,
595 pub trait_items: BTreeSet<TraitItemId>,
596 pub impl_items: BTreeSet<ImplItemId>,
599 /// A type representing only the top-level module.
600 #[derive(Encodable, Debug, HashStable_Generic)]
601 pub struct CrateItem<'hir> {
602 pub module: Mod<'hir>,
603 pub attrs: &'hir [Attribute],
607 /// The top-level data structure that stores the entire contents of
608 /// the crate currently being compiled.
610 /// For more details, see the [rustc dev guide].
612 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
614 pub struct Crate<'hir> {
615 pub item: CrateItem<'hir>,
616 pub exported_macros: &'hir [MacroDef<'hir>],
617 // Attributes from non-exported macros, kept only for collecting the library feature list.
618 pub non_exported_macro_attrs: &'hir [Attribute],
620 // N.B., we use a `BTreeMap` here so that `visit_all_items` iterates
621 // over the ids in increasing order. In principle it should not
622 // matter what order we visit things in, but in *practice* it
623 // does, because it can affect the order in which errors are
624 // detected, which in turn can make compile-fail tests yield
625 // slightly different results.
626 pub items: BTreeMap<HirId, Item<'hir>>,
628 pub trait_items: BTreeMap<TraitItemId, TraitItem<'hir>>,
629 pub impl_items: BTreeMap<ImplItemId, ImplItem<'hir>>,
630 pub bodies: BTreeMap<BodyId, Body<'hir>>,
631 pub trait_impls: BTreeMap<DefId, Vec<HirId>>,
633 /// A list of the body ids written out in the order in which they
634 /// appear in the crate. If you're going to process all the bodies
635 /// in the crate, you should iterate over this list rather than the keys
637 pub body_ids: Vec<BodyId>,
639 /// A list of modules written out in the order in which they
640 /// appear in the crate. This includes the main crate module.
641 pub modules: BTreeMap<HirId, ModuleItems>,
642 /// A list of proc macro HirIds, written out in the order in which
643 /// they are declared in the static array generated by proc_macro_harness.
644 pub proc_macros: Vec<HirId>,
646 pub trait_map: BTreeMap<HirId, Vec<TraitCandidate>>,
650 pub fn item(&self, id: HirId) -> &Item<'hir> {
654 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem<'hir> {
655 &self.trait_items[&id]
658 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem<'hir> {
659 &self.impl_items[&id]
662 pub fn body(&self, id: BodyId) -> &Body<'hir> {
668 /// Visits all items in the crate in some deterministic (but
669 /// unspecified) order. If you just need to process every item,
670 /// but don't care about nesting, this method is the best choice.
672 /// If you do care about nesting -- usually because your algorithm
673 /// follows lexical scoping rules -- then you want a different
674 /// approach. You should override `visit_nested_item` in your
675 /// visitor and then call `intravisit::walk_crate` instead.
676 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
678 V: itemlikevisit::ItemLikeVisitor<'hir>,
680 for item in self.items.values() {
681 visitor.visit_item(item);
684 for trait_item in self.trait_items.values() {
685 visitor.visit_trait_item(trait_item);
688 for impl_item in self.impl_items.values() {
689 visitor.visit_impl_item(impl_item);
693 /// A parallel version of `visit_all_item_likes`.
694 pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
696 V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send,
700 par_for_each_in(&self.items, |(_, item)| {
701 visitor.visit_item(item);
705 par_for_each_in(&self.trait_items, |(_, trait_item)| {
706 visitor.visit_trait_item(trait_item);
710 par_for_each_in(&self.impl_items, |(_, impl_item)| {
711 visitor.visit_impl_item(impl_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>,
761 // FIXME(#19596) this is a workaround, but there should be a better way
762 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'_>) -> bool) -> bool {
769 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
770 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
771 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
772 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
773 Slice(before, slice, after) => {
774 before.iter().chain(slice.iter()).chain(after.iter()).all(|p| p.walk_short_(it))
779 /// Walk the pattern in left-to-right order,
780 /// short circuiting (with `.all(..)`) if `false` is returned.
782 /// Note that when visiting e.g. `Tuple(ps)`,
783 /// if visiting `ps[0]` returns `false`,
784 /// then `ps[1]` will not be visited.
785 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'_>) -> bool) -> bool {
786 self.walk_short_(&mut it)
789 // FIXME(#19596) this is a workaround, but there should be a better way
790 fn walk_(&self, it: &mut impl FnMut(&Pat<'_>) -> bool) {
797 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
798 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
799 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
800 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
801 Slice(before, slice, after) => {
802 before.iter().chain(slice.iter()).chain(after.iter()).for_each(|p| p.walk_(it))
807 /// Walk the pattern in left-to-right order.
809 /// If `it(pat)` returns `false`, the children are not visited.
810 pub fn walk(&self, mut it: impl FnMut(&Pat<'_>) -> bool) {
814 /// Walk the pattern in left-to-right order.
816 /// If you always want to recurse, prefer this method over `walk`.
817 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
825 /// A single field in a struct pattern.
827 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
828 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
829 /// except `is_shorthand` is true.
830 #[derive(Debug, HashStable_Generic)]
831 pub struct FieldPat<'hir> {
832 #[stable_hasher(ignore)]
834 /// The identifier for the field.
835 #[stable_hasher(project(name))]
837 /// The pattern the field is destructured to.
838 pub pat: &'hir Pat<'hir>,
839 pub is_shorthand: bool,
843 /// Explicit binding annotations given in the HIR for a binding. Note
844 /// that this is not the final binding *mode* that we infer after type
846 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
847 pub enum BindingAnnotation {
848 /// No binding annotation given: this means that the final binding mode
849 /// will depend on whether we have skipped through a `&` reference
850 /// when matching. For example, the `x` in `Some(x)` will have binding
851 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
852 /// ultimately be inferred to be by-reference.
854 /// Note that implicit reference skipping is not implemented yet (#42640).
857 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
860 /// Annotated as `ref`, like `ref x`
863 /// Annotated as `ref mut x`.
867 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
873 impl fmt::Display for RangeEnd {
874 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
875 f.write_str(match self {
876 RangeEnd::Included => "..=",
877 RangeEnd::Excluded => "..",
882 #[derive(Debug, HashStable_Generic)]
883 pub enum PatKind<'hir> {
884 /// Represents a wildcard pattern (i.e., `_`).
887 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
888 /// The `HirId` is the canonical ID for the variable being bound,
889 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
890 /// which is the pattern ID of the first `x`.
891 Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
893 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
894 /// The `bool` is `true` in the presence of a `..`.
895 Struct(QPath<'hir>, &'hir [FieldPat<'hir>], bool),
897 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
898 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
899 /// `0 <= position <= subpats.len()`
900 TupleStruct(QPath<'hir>, &'hir [&'hir Pat<'hir>], Option<usize>),
902 /// An or-pattern `A | B | C`.
903 /// Invariant: `pats.len() >= 2`.
904 Or(&'hir [&'hir Pat<'hir>]),
906 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
909 /// A tuple pattern (e.g., `(a, b)`).
910 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
911 /// `0 <= position <= subpats.len()`
912 Tuple(&'hir [&'hir Pat<'hir>], Option<usize>),
915 Box(&'hir Pat<'hir>),
917 /// A reference pattern (e.g., `&mut (a, b)`).
918 Ref(&'hir Pat<'hir>, Mutability),
921 Lit(&'hir Expr<'hir>),
923 /// A range pattern (e.g., `1..=2` or `1..2`).
924 Range(Option<&'hir Expr<'hir>>, Option<&'hir Expr<'hir>>, RangeEnd),
926 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
928 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
929 /// If `slice` exists, then `after` can be non-empty.
931 /// The representation for e.g., `[a, b, .., c, d]` is:
933 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
935 Slice(&'hir [&'hir Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [&'hir Pat<'hir>]),
938 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
940 /// The `+` operator (addition).
942 /// The `-` operator (subtraction).
944 /// The `*` operator (multiplication).
946 /// The `/` operator (division).
948 /// The `%` operator (modulus).
950 /// The `&&` operator (logical and).
952 /// The `||` operator (logical or).
954 /// The `^` operator (bitwise xor).
956 /// The `&` operator (bitwise and).
958 /// The `|` operator (bitwise or).
960 /// The `<<` operator (shift left).
962 /// The `>>` operator (shift right).
964 /// The `==` operator (equality).
966 /// The `<` operator (less than).
968 /// The `<=` operator (less than or equal to).
970 /// The `!=` operator (not equal to).
972 /// The `>=` operator (greater than or equal to).
974 /// The `>` operator (greater than).
979 pub fn as_str(self) -> &'static str {
981 BinOpKind::Add => "+",
982 BinOpKind::Sub => "-",
983 BinOpKind::Mul => "*",
984 BinOpKind::Div => "/",
985 BinOpKind::Rem => "%",
986 BinOpKind::And => "&&",
987 BinOpKind::Or => "||",
988 BinOpKind::BitXor => "^",
989 BinOpKind::BitAnd => "&",
990 BinOpKind::BitOr => "|",
991 BinOpKind::Shl => "<<",
992 BinOpKind::Shr => ">>",
993 BinOpKind::Eq => "==",
994 BinOpKind::Lt => "<",
995 BinOpKind::Le => "<=",
996 BinOpKind::Ne => "!=",
997 BinOpKind::Ge => ">=",
998 BinOpKind::Gt => ">",
1002 pub fn is_lazy(self) -> bool {
1004 BinOpKind::And | BinOpKind::Or => true,
1009 pub fn is_shift(self) -> bool {
1011 BinOpKind::Shl | BinOpKind::Shr => true,
1016 pub fn is_comparison(self) -> bool {
1023 | BinOpKind::Ge => true,
1035 | BinOpKind::Shr => false,
1039 /// Returns `true` if the binary operator takes its arguments by value.
1040 pub fn is_by_value(self) -> bool {
1041 !self.is_comparison()
1045 impl Into<ast::BinOpKind> for BinOpKind {
1046 fn into(self) -> ast::BinOpKind {
1048 BinOpKind::Add => ast::BinOpKind::Add,
1049 BinOpKind::Sub => ast::BinOpKind::Sub,
1050 BinOpKind::Mul => ast::BinOpKind::Mul,
1051 BinOpKind::Div => ast::BinOpKind::Div,
1052 BinOpKind::Rem => ast::BinOpKind::Rem,
1053 BinOpKind::And => ast::BinOpKind::And,
1054 BinOpKind::Or => ast::BinOpKind::Or,
1055 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1056 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1057 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1058 BinOpKind::Shl => ast::BinOpKind::Shl,
1059 BinOpKind::Shr => ast::BinOpKind::Shr,
1060 BinOpKind::Eq => ast::BinOpKind::Eq,
1061 BinOpKind::Lt => ast::BinOpKind::Lt,
1062 BinOpKind::Le => ast::BinOpKind::Le,
1063 BinOpKind::Ne => ast::BinOpKind::Ne,
1064 BinOpKind::Ge => ast::BinOpKind::Ge,
1065 BinOpKind::Gt => ast::BinOpKind::Gt,
1070 pub type BinOp = Spanned<BinOpKind>;
1072 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1074 /// The `*` operator (deferencing).
1076 /// The `!` operator (logical negation).
1078 /// The `-` operator (negation).
1083 pub fn as_str(self) -> &'static str {
1085 Self::UnDeref => "*",
1091 /// Returns `true` if the unary operator takes its argument by value.
1092 pub fn is_by_value(self) -> bool {
1094 Self::UnNeg | Self::UnNot => true,
1101 #[derive(Debug, HashStable_Generic)]
1102 pub struct Stmt<'hir> {
1104 pub kind: StmtKind<'hir>,
1108 /// The contents of a statement.
1109 #[derive(Debug, HashStable_Generic)]
1110 pub enum StmtKind<'hir> {
1111 /// A local (`let`) binding.
1112 Local(&'hir Local<'hir>),
1114 /// An item binding.
1117 /// An expression without a trailing semi-colon (must have unit type).
1118 Expr(&'hir Expr<'hir>),
1120 /// An expression with a trailing semi-colon (may have any type).
1121 Semi(&'hir Expr<'hir>),
1124 impl StmtKind<'hir> {
1125 pub fn attrs(&self) -> &'hir [Attribute] {
1127 StmtKind::Local(ref l) => &l.attrs,
1128 StmtKind::Item(_) => &[],
1129 StmtKind::Expr(ref e) | StmtKind::Semi(ref e) => &e.attrs,
1134 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1135 #[derive(Debug, HashStable_Generic)]
1136 pub struct Local<'hir> {
1137 pub pat: &'hir Pat<'hir>,
1138 /// Type annotation, if any (otherwise the type will be inferred).
1139 pub ty: Option<&'hir Ty<'hir>>,
1140 /// Initializer expression to set the value, if any.
1141 pub init: Option<&'hir Expr<'hir>>,
1145 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1146 /// desugaring. Otherwise will be `Normal`.
1147 pub source: LocalSource,
1150 /// Represents a single arm of a `match` expression, e.g.
1151 /// `<pat> (if <guard>) => <body>`.
1152 #[derive(Debug, HashStable_Generic)]
1153 pub struct Arm<'hir> {
1154 #[stable_hasher(ignore)]
1157 pub attrs: &'hir [Attribute],
1158 /// If this pattern and the optional guard matches, then `body` is evaluated.
1159 pub pat: &'hir Pat<'hir>,
1160 /// Optional guard clause.
1161 pub guard: Option<Guard<'hir>>,
1162 /// The expression the arm evaluates to if this arm matches.
1163 pub body: &'hir Expr<'hir>,
1166 #[derive(Debug, HashStable_Generic)]
1167 pub enum Guard<'hir> {
1168 If(&'hir Expr<'hir>),
1171 #[derive(Debug, HashStable_Generic)]
1172 pub struct Field<'hir> {
1173 #[stable_hasher(ignore)]
1176 pub expr: &'hir Expr<'hir>,
1178 pub is_shorthand: bool,
1181 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1182 pub enum BlockCheckMode {
1184 UnsafeBlock(UnsafeSource),
1185 PushUnsafeBlock(UnsafeSource),
1186 PopUnsafeBlock(UnsafeSource),
1189 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1190 pub enum UnsafeSource {
1195 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Hash, Debug)]
1200 /// The body of a function, closure, or constant value. In the case of
1201 /// a function, the body contains not only the function body itself
1202 /// (which is an expression), but also the argument patterns, since
1203 /// those are something that the caller doesn't really care about.
1208 /// fn foo((x, y): (u32, u32)) -> u32 {
1213 /// Here, the `Body` associated with `foo()` would contain:
1215 /// - an `params` array containing the `(x, y)` pattern
1216 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1217 /// - `generator_kind` would be `None`
1219 /// All bodies have an **owner**, which can be accessed via the HIR
1220 /// map using `body_owner_def_id()`.
1222 pub struct Body<'hir> {
1223 pub params: &'hir [Param<'hir>],
1224 pub value: Expr<'hir>,
1225 pub generator_kind: Option<GeneratorKind>,
1229 pub fn id(&self) -> BodyId {
1230 BodyId { hir_id: self.value.hir_id }
1233 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1238 /// The type of source expression that caused this generator to be created.
1239 #[derive(Clone, PartialEq, Eq, HashStable_Generic, Encodable, Decodable, Debug, Copy)]
1240 pub enum GeneratorKind {
1241 /// An explicit `async` block or the body of an async function.
1242 Async(AsyncGeneratorKind),
1244 /// A generator literal created via a `yield` inside a closure.
1248 impl fmt::Display for GeneratorKind {
1249 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1251 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1252 GeneratorKind::Gen => f.write_str("generator"),
1257 /// In the case of a generator created as part of an async construct,
1258 /// which kind of async construct caused it to be created?
1260 /// This helps error messages but is also used to drive coercions in
1261 /// type-checking (see #60424).
1262 #[derive(Clone, PartialEq, Eq, HashStable_Generic, Encodable, Decodable, Debug, Copy)]
1263 pub enum AsyncGeneratorKind {
1264 /// An explicit `async` block written by the user.
1267 /// An explicit `async` block written by the user.
1270 /// The `async` block generated as the body of an async function.
1274 impl fmt::Display for AsyncGeneratorKind {
1275 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1276 f.write_str(match self {
1277 AsyncGeneratorKind::Block => "`async` block",
1278 AsyncGeneratorKind::Closure => "`async` closure body",
1279 AsyncGeneratorKind::Fn => "`async fn` body",
1284 #[derive(Copy, Clone, Debug)]
1285 pub enum BodyOwnerKind {
1286 /// Functions and methods.
1292 /// Constants and associated constants.
1295 /// Initializer of a `static` item.
1299 impl BodyOwnerKind {
1300 pub fn is_fn_or_closure(self) -> bool {
1302 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1303 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1308 /// The kind of an item that requires const-checking.
1309 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1310 pub enum ConstContext {
1314 /// A `static` or `static mut`.
1317 /// A `const`, associated `const`, or other const context.
1319 /// Other contexts include:
1320 /// - Array length expressions
1321 /// - Enum discriminants
1322 /// - Const generics
1324 /// For the most part, other contexts are treated just like a regular `const`, so they are
1325 /// lumped into the same category.
1330 /// A description of this const context that can appear between backticks in an error message.
1332 /// E.g. `const` or `static mut`.
1333 pub fn keyword_name(self) -> &'static str {
1335 Self::Const => "const",
1336 Self::Static(Mutability::Not) => "static",
1337 Self::Static(Mutability::Mut) => "static mut",
1338 Self::ConstFn => "const fn",
1343 /// A colloquial, trivially pluralizable description of this const context for use in error
1345 impl fmt::Display for ConstContext {
1346 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1348 Self::Const => write!(f, "constant"),
1349 Self::Static(_) => write!(f, "static"),
1350 Self::ConstFn => write!(f, "constant function"),
1356 pub type Lit = Spanned<LitKind>;
1358 /// A constant (expression) that's not an item or associated item,
1359 /// but needs its own `DefId` for type-checking, const-eval, etc.
1360 /// These are usually found nested inside types (e.g., array lengths)
1361 /// or expressions (e.g., repeat counts), and also used to define
1362 /// explicit discriminant values for enum variants.
1363 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1364 pub struct AnonConst {
1371 pub struct Expr<'hir> {
1373 pub kind: ExprKind<'hir>,
1378 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1379 #[cfg(target_arch = "x86_64")]
1380 rustc_data_structures::static_assert_size!(Expr<'static>, 72);
1383 pub fn precedence(&self) -> ExprPrecedence {
1385 ExprKind::Box(_) => ExprPrecedence::Box,
1386 ExprKind::Array(_) => ExprPrecedence::Array,
1387 ExprKind::Call(..) => ExprPrecedence::Call,
1388 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1389 ExprKind::Tup(_) => ExprPrecedence::Tup,
1390 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1391 ExprKind::Unary(..) => ExprPrecedence::Unary,
1392 ExprKind::Lit(_) => ExprPrecedence::Lit,
1393 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1394 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1395 ExprKind::Loop(..) => ExprPrecedence::Loop,
1396 ExprKind::Match(..) => ExprPrecedence::Match,
1397 ExprKind::Closure(..) => ExprPrecedence::Closure,
1398 ExprKind::Block(..) => ExprPrecedence::Block,
1399 ExprKind::Assign(..) => ExprPrecedence::Assign,
1400 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1401 ExprKind::Field(..) => ExprPrecedence::Field,
1402 ExprKind::Index(..) => ExprPrecedence::Index,
1403 ExprKind::Path(..) => ExprPrecedence::Path,
1404 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1405 ExprKind::Break(..) => ExprPrecedence::Break,
1406 ExprKind::Continue(..) => ExprPrecedence::Continue,
1407 ExprKind::Ret(..) => ExprPrecedence::Ret,
1408 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1409 ExprKind::LlvmInlineAsm(..) => ExprPrecedence::InlineAsm,
1410 ExprKind::Struct(..) => ExprPrecedence::Struct,
1411 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1412 ExprKind::Yield(..) => ExprPrecedence::Yield,
1413 ExprKind::Err => ExprPrecedence::Err,
1417 // Whether this looks like a place expr, without checking for deref
1419 // This will return `true` in some potentially surprising cases such as
1420 // `CONSTANT.field`.
1421 pub fn is_syntactic_place_expr(&self) -> bool {
1422 self.is_place_expr(|_| true)
1425 /// Whether this is a place expression.
1427 /// `allow_projections_from` should return `true` if indexing a field or index expression based
1428 /// on the given expression should be considered a place expression.
1429 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1431 ExprKind::Path(QPath::Resolved(_, ref path)) => match path.res {
1432 Res::Local(..) | Res::Def(DefKind::Static, _) | Res::Err => true,
1436 // Type ascription inherits its place expression kind from its
1438 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1439 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1441 ExprKind::Unary(UnOp::UnDeref, _) => true,
1443 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1444 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1447 // Lang item paths cannot currently be local variables or statics.
1448 ExprKind::Path(QPath::LangItem(..)) => false,
1450 // Partially qualified paths in expressions can only legally
1451 // refer to associated items which are always rvalues.
1452 ExprKind::Path(QPath::TypeRelative(..))
1453 | ExprKind::Call(..)
1454 | ExprKind::MethodCall(..)
1455 | ExprKind::Struct(..)
1457 | ExprKind::Match(..)
1458 | ExprKind::Closure(..)
1459 | ExprKind::Block(..)
1460 | ExprKind::Repeat(..)
1461 | ExprKind::Array(..)
1462 | ExprKind::Break(..)
1463 | ExprKind::Continue(..)
1465 | ExprKind::Loop(..)
1466 | ExprKind::Assign(..)
1467 | ExprKind::InlineAsm(..)
1468 | ExprKind::LlvmInlineAsm(..)
1469 | ExprKind::AssignOp(..)
1471 | ExprKind::Unary(..)
1473 | ExprKind::AddrOf(..)
1474 | ExprKind::Binary(..)
1475 | ExprKind::Yield(..)
1476 | ExprKind::Cast(..)
1477 | ExprKind::DropTemps(..)
1478 | ExprKind::Err => false,
1482 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1483 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1484 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1485 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1486 /// beyond remembering to call this function before doing analysis on it.
1487 pub fn peel_drop_temps(&self) -> &Self {
1488 let mut expr = self;
1489 while let ExprKind::DropTemps(inner) = &expr.kind {
1496 /// Checks if the specified expression is a built-in range literal.
1497 /// (See: `LoweringContext::lower_expr()`).
1498 pub fn is_range_literal(expr: &Expr<'_>) -> bool {
1500 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1501 ExprKind::Struct(ref qpath, _, _) => matches!(
1506 | LangItem::RangeFrom
1507 | LangItem::RangeFull
1508 | LangItem::RangeToInclusive,
1513 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1514 ExprKind::Call(ref func, _) => {
1515 matches!(func.kind, ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, _)))
1522 #[derive(Debug, HashStable_Generic)]
1523 pub enum ExprKind<'hir> {
1524 /// A `box x` expression.
1525 Box(&'hir Expr<'hir>),
1526 /// An array (e.g., `[a, b, c, d]`).
1527 Array(&'hir [Expr<'hir>]),
1528 /// A function call.
1530 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1531 /// and the second field is the list of arguments.
1532 /// This also represents calling the constructor of
1533 /// tuple-like ADTs such as tuple structs and enum variants.
1534 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1535 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1537 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1538 /// (within the angle brackets).
1539 /// The first element of the vector of `Expr`s is the expression that evaluates
1540 /// to the object on which the method is being called on (the receiver),
1541 /// and the remaining elements are the rest of the arguments.
1542 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1543 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1544 /// The final `Span` represents the span of the function and arguments
1545 /// (e.g. `foo::<Bar, Baz>(a, b, c, d)` in `x.foo::<Bar, Baz>(a, b, c, d)`
1547 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1548 /// the `hir_id` of the `MethodCall` node itself.
1550 /// [`type_dependent_def_id`]: ../ty/struct.TypeckResults.html#method.type_dependent_def_id
1551 MethodCall(&'hir PathSegment<'hir>, Span, &'hir [Expr<'hir>], Span),
1552 /// A tuple (e.g., `(a, b, c, d)`).
1553 Tup(&'hir [Expr<'hir>]),
1554 /// A binary operation (e.g., `a + b`, `a * b`).
1555 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1556 /// A unary operation (e.g., `!x`, `*x`).
1557 Unary(UnOp, &'hir Expr<'hir>),
1558 /// A literal (e.g., `1`, `"foo"`).
1560 /// A cast (e.g., `foo as f64`).
1561 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1562 /// A type reference (e.g., `Foo`).
1563 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1564 /// Wraps the expression in a terminating scope.
1565 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1567 /// This construct only exists to tweak the drop order in HIR lowering.
1568 /// An example of that is the desugaring of `for` loops.
1569 DropTemps(&'hir Expr<'hir>),
1570 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1572 /// I.e., `'label: loop { <block> }`.
1573 Loop(&'hir Block<'hir>, Option<Label>, LoopSource),
1574 /// A `match` block, with a source that indicates whether or not it is
1575 /// the result of a desugaring, and if so, which kind.
1576 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1577 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1579 /// The `Span` is the argument block `|...|`.
1581 /// This may also be a generator literal or an `async block` as indicated by the
1582 /// `Option<Movability>`.
1583 Closure(CaptureBy, &'hir FnDecl<'hir>, BodyId, Span, Option<Movability>),
1584 /// A block (e.g., `'label: { ... }`).
1585 Block(&'hir Block<'hir>, Option<Label>),
1587 /// An assignment (e.g., `a = foo()`).
1588 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1589 /// An assignment with an operator.
1592 AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1593 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1594 Field(&'hir Expr<'hir>, Ident),
1595 /// An indexing operation (`foo[2]`).
1596 Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1598 /// Path to a definition, possibly containing lifetime or type parameters.
1601 /// A referencing operation (i.e., `&a` or `&mut a`).
1602 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1603 /// A `break`, with an optional label to break.
1604 Break(Destination, Option<&'hir Expr<'hir>>),
1605 /// A `continue`, with an optional label.
1606 Continue(Destination),
1607 /// A `return`, with an optional value to be returned.
1608 Ret(Option<&'hir Expr<'hir>>),
1610 /// Inline assembly (from `asm!`), with its outputs and inputs.
1611 InlineAsm(&'hir InlineAsm<'hir>),
1612 /// Inline assembly (from `llvm_asm!`), with its outputs and inputs.
1613 LlvmInlineAsm(&'hir LlvmInlineAsm<'hir>),
1615 /// A struct or struct-like variant literal expression.
1617 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1618 /// where `base` is the `Option<Expr>`.
1619 Struct(&'hir QPath<'hir>, &'hir [Field<'hir>], Option<&'hir Expr<'hir>>),
1621 /// An array literal constructed from one repeated element.
1623 /// E.g., `[1; 5]`. The first expression is the element
1624 /// to be repeated; the second is the number of times to repeat it.
1625 Repeat(&'hir Expr<'hir>, AnonConst),
1627 /// A suspension point for generators (i.e., `yield <expr>`).
1628 Yield(&'hir Expr<'hir>, YieldSource),
1630 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1634 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1636 /// To resolve the path to a `DefId`, call [`qpath_res`].
1638 /// [`qpath_res`]: ../rustc_middle/ty/struct.TypeckResults.html#method.qpath_res
1639 #[derive(Debug, HashStable_Generic)]
1640 pub enum QPath<'hir> {
1641 /// Path to a definition, optionally "fully-qualified" with a `Self`
1642 /// type, if the path points to an associated item in a trait.
1644 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1645 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1646 /// even though they both have the same two-segment `Clone::clone` `Path`.
1647 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
1649 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1650 /// Will be resolved by type-checking to an associated item.
1652 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1653 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1654 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1655 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
1657 /// Reference to a `#[lang = "foo"]` item.
1658 LangItem(LangItem, Span),
1661 impl<'hir> QPath<'hir> {
1662 /// Returns the span of this `QPath`.
1663 pub fn span(&self) -> Span {
1665 QPath::Resolved(_, path) => path.span,
1666 QPath::TypeRelative(_, ps) => ps.ident.span,
1667 QPath::LangItem(_, span) => span,
1671 /// Returns the span of the qself of this `QPath`. For example, `()` in
1672 /// `<() as Trait>::method`.
1673 pub fn qself_span(&self) -> Span {
1675 QPath::Resolved(_, path) => path.span,
1676 QPath::TypeRelative(qself, _) => qself.span,
1677 QPath::LangItem(_, span) => span,
1681 /// Returns the span of the last segment of this `QPath`. For example, `method` in
1682 /// `<() as Trait>::method`.
1683 pub fn last_segment_span(&self) -> Span {
1685 QPath::Resolved(_, path) => path.segments.last().unwrap().ident.span,
1686 QPath::TypeRelative(_, segment) => segment.ident.span,
1687 QPath::LangItem(_, span) => span,
1692 /// Hints at the original code for a let statement.
1693 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1694 pub enum LocalSource {
1695 /// A `match _ { .. }`.
1697 /// A desugared `for _ in _ { .. }` loop.
1699 /// When lowering async functions, we create locals within the `async move` so that
1700 /// all parameters are dropped after the future is polled.
1702 /// ```ignore (pseudo-Rust)
1703 /// async fn foo(<pattern> @ x: Type) {
1705 /// let <pattern> = x;
1710 /// A desugared `<expr>.await`.
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>,
1856 // The bodies for items are stored "out of line", in a separate
1857 // hashmap in the `Crate`. Here we just record the node-id of the item
1858 // so it can fetched later.
1859 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
1860 pub struct TraitItemId {
1864 /// Represents an item declaration within a trait declaration,
1865 /// possibly including a default implementation. A trait item is
1866 /// either required (meaning it doesn't have an implementation, just a
1867 /// signature) or provided (meaning it has a default implementation).
1869 pub struct TraitItem<'hir> {
1872 pub attrs: &'hir [Attribute],
1873 pub generics: Generics<'hir>,
1874 pub kind: TraitItemKind<'hir>,
1878 /// Represents a trait method's body (or just argument names).
1879 #[derive(Encodable, Debug, HashStable_Generic)]
1880 pub enum TraitFn<'hir> {
1881 /// No default body in the trait, just a signature.
1882 Required(&'hir [Ident]),
1884 /// Both signature and body are provided in the trait.
1888 /// Represents a trait method or associated constant or type
1889 #[derive(Debug, HashStable_Generic)]
1890 pub enum TraitItemKind<'hir> {
1891 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
1892 Const(&'hir Ty<'hir>, Option<BodyId>),
1893 /// An associated function with an optional body.
1894 Fn(FnSig<'hir>, TraitFn<'hir>),
1895 /// An associated type with (possibly empty) bounds and optional concrete
1897 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
1900 // The bodies for items are stored "out of line", in a separate
1901 // hashmap in the `Crate`. Here we just record the node-id of the item
1902 // so it can fetched later.
1903 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
1904 pub struct ImplItemId {
1908 /// Represents anything within an `impl` block.
1910 pub struct ImplItem<'hir> {
1913 pub vis: Visibility<'hir>,
1914 pub defaultness: Defaultness,
1915 pub attrs: &'hir [Attribute],
1916 pub generics: Generics<'hir>,
1917 pub kind: ImplItemKind<'hir>,
1921 /// Represents various kinds of content within an `impl`.
1922 #[derive(Debug, HashStable_Generic)]
1923 pub enum ImplItemKind<'hir> {
1924 /// An associated constant of the given type, set to the constant result
1925 /// of the expression.
1926 Const(&'hir Ty<'hir>, BodyId),
1927 /// An associated function implementation with the given signature and body.
1928 Fn(FnSig<'hir>, BodyId),
1929 /// An associated type.
1930 TyAlias(&'hir Ty<'hir>),
1933 impl ImplItemKind<'_> {
1934 pub fn namespace(&self) -> Namespace {
1936 ImplItemKind::TyAlias(..) => Namespace::TypeNS,
1937 ImplItemKind::Const(..) | ImplItemKind::Fn(..) => Namespace::ValueNS,
1942 // The name of the associated type for `Fn` return types.
1943 pub const FN_OUTPUT_NAME: Symbol = sym::Output;
1945 /// Bind a type to an associated type (i.e., `A = Foo`).
1947 /// Bindings like `A: Debug` are represented as a special type `A =
1948 /// $::Debug` that is understood by the astconv code.
1950 /// FIXME(alexreg): why have a separate type for the binding case,
1951 /// wouldn't it be better to make the `ty` field an enum like the
1955 /// enum TypeBindingKind {
1960 #[derive(Debug, HashStable_Generic)]
1961 pub struct TypeBinding<'hir> {
1963 #[stable_hasher(project(name))]
1965 pub kind: TypeBindingKind<'hir>,
1969 // Represents the two kinds of type bindings.
1970 #[derive(Debug, HashStable_Generic)]
1971 pub enum TypeBindingKind<'hir> {
1972 /// E.g., `Foo<Bar: Send>`.
1973 Constraint { bounds: &'hir [GenericBound<'hir>] },
1974 /// E.g., `Foo<Bar = ()>`.
1975 Equality { ty: &'hir Ty<'hir> },
1978 impl TypeBinding<'_> {
1979 pub fn ty(&self) -> &Ty<'_> {
1981 TypeBindingKind::Equality { ref ty } => ty,
1982 _ => panic!("expected equality type binding for parenthesized generic args"),
1988 pub struct Ty<'hir> {
1990 pub kind: TyKind<'hir>,
1994 /// Not represented directly in the AST; referred to by name through a `ty_path`.
1995 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
1996 #[derive(HashStable_Generic)]
2006 #[derive(Debug, HashStable_Generic)]
2007 pub struct BareFnTy<'hir> {
2008 pub unsafety: Unsafety,
2010 pub generic_params: &'hir [GenericParam<'hir>],
2011 pub decl: &'hir FnDecl<'hir>,
2012 pub param_names: &'hir [Ident],
2015 #[derive(Debug, HashStable_Generic)]
2016 pub struct OpaqueTy<'hir> {
2017 pub generics: Generics<'hir>,
2018 pub bounds: GenericBounds<'hir>,
2019 pub impl_trait_fn: Option<DefId>,
2020 pub origin: OpaqueTyOrigin,
2023 /// From whence the opaque type came.
2024 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2025 pub enum OpaqueTyOrigin {
2030 /// `let _: impl Trait = ...`
2032 /// Impl trait in type aliases, consts, statics, bounds.
2036 /// The various kinds of types recognized by the compiler.
2037 #[derive(Debug, HashStable_Generic)]
2038 pub enum TyKind<'hir> {
2039 /// A variable length slice (i.e., `[T]`).
2040 Slice(&'hir Ty<'hir>),
2041 /// A fixed length array (i.e., `[T; n]`).
2042 Array(&'hir Ty<'hir>, AnonConst),
2043 /// A raw pointer (i.e., `*const T` or `*mut T`).
2045 /// A reference (i.e., `&'a T` or `&'a mut T`).
2046 Rptr(Lifetime, MutTy<'hir>),
2047 /// A bare function (e.g., `fn(usize) -> bool`).
2048 BareFn(&'hir BareFnTy<'hir>),
2049 /// The never type (`!`).
2051 /// A tuple (`(A, B, C, D, ...)`).
2052 Tup(&'hir [Ty<'hir>]),
2053 /// A path to a type definition (`module::module::...::Type`), or an
2054 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2056 /// Type parameters may be stored in each `PathSegment`.
2058 /// A opaque type definition itself. This is currently only used for the
2059 /// `opaque type Foo: Trait` item that `impl Trait` in desugars to.
2061 /// The generic argument list contains the lifetimes (and in the future
2062 /// possibly parameters) that are actually bound on the `impl Trait`.
2063 OpaqueDef(ItemId, &'hir [GenericArg<'hir>]),
2064 /// A trait object type `Bound1 + Bound2 + Bound3`
2065 /// where `Bound` is a trait or a lifetime.
2066 TraitObject(&'hir [PolyTraitRef<'hir>], Lifetime),
2069 /// `TyKind::Infer` means the type should be inferred instead of it having been
2070 /// specified. This can appear anywhere in a type.
2072 /// Placeholder for a type that has failed to be defined.
2076 #[derive(Debug, HashStable_Generic)]
2077 pub enum InlineAsmOperand<'hir> {
2079 reg: InlineAsmRegOrRegClass,
2083 reg: InlineAsmRegOrRegClass,
2085 expr: Option<Expr<'hir>>,
2088 reg: InlineAsmRegOrRegClass,
2093 reg: InlineAsmRegOrRegClass,
2095 in_expr: Expr<'hir>,
2096 out_expr: Option<Expr<'hir>>,
2106 impl<'hir> InlineAsmOperand<'hir> {
2107 pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
2109 Self::In { reg, .. }
2110 | Self::Out { reg, .. }
2111 | Self::InOut { reg, .. }
2112 | Self::SplitInOut { reg, .. } => Some(reg),
2113 Self::Const { .. } | Self::Sym { .. } => None,
2118 #[derive(Debug, HashStable_Generic)]
2119 pub struct InlineAsm<'hir> {
2120 pub template: &'hir [InlineAsmTemplatePiece],
2121 pub operands: &'hir [InlineAsmOperand<'hir>],
2122 pub options: InlineAsmOptions,
2123 pub line_spans: &'hir [Span],
2126 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic, PartialEq)]
2127 pub struct LlvmInlineAsmOutput {
2128 pub constraint: Symbol,
2130 pub is_indirect: bool,
2134 // NOTE(eddyb) This is used within MIR as well, so unlike the rest of the HIR,
2135 // it needs to be `Clone` and `Decodable` and use plain `Vec<T>` instead of
2136 // arena-allocated slice.
2137 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic, PartialEq)]
2138 pub struct LlvmInlineAsmInner {
2140 pub asm_str_style: StrStyle,
2141 pub outputs: Vec<LlvmInlineAsmOutput>,
2142 pub inputs: Vec<Symbol>,
2143 pub clobbers: Vec<Symbol>,
2145 pub alignstack: bool,
2146 pub dialect: LlvmAsmDialect,
2149 #[derive(Debug, HashStable_Generic)]
2150 pub struct LlvmInlineAsm<'hir> {
2151 pub inner: LlvmInlineAsmInner,
2152 pub outputs_exprs: &'hir [Expr<'hir>],
2153 pub inputs_exprs: &'hir [Expr<'hir>],
2156 /// Represents a parameter in a function header.
2157 #[derive(Debug, HashStable_Generic)]
2158 pub struct Param<'hir> {
2159 pub attrs: &'hir [Attribute],
2161 pub pat: &'hir Pat<'hir>,
2166 /// Represents the header (not the body) of a function declaration.
2167 #[derive(Debug, HashStable_Generic)]
2168 pub struct FnDecl<'hir> {
2169 /// The types of the function's parameters.
2171 /// Additional argument data is stored in the function's [body](Body::params).
2172 pub inputs: &'hir [Ty<'hir>],
2173 pub output: FnRetTy<'hir>,
2174 pub c_variadic: bool,
2175 /// Does the function have an implicit self?
2176 pub implicit_self: ImplicitSelfKind,
2179 /// Represents what type of implicit self a function has, if any.
2180 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2181 pub enum ImplicitSelfKind {
2182 /// Represents a `fn x(self);`.
2184 /// Represents a `fn x(mut self);`.
2186 /// Represents a `fn x(&self);`.
2188 /// Represents a `fn x(&mut self);`.
2190 /// Represents when a function does not have a self argument or
2191 /// when a function has a `self: X` argument.
2195 impl ImplicitSelfKind {
2196 /// Does this represent an implicit self?
2197 pub fn has_implicit_self(&self) -> bool {
2199 ImplicitSelfKind::None => false,
2205 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable, Debug)]
2206 #[derive(HashStable_Generic)]
2212 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable, HashStable_Generic)]
2213 pub enum Defaultness {
2214 Default { has_value: bool },
2219 pub fn has_value(&self) -> bool {
2221 Defaultness::Default { has_value } => has_value,
2222 Defaultness::Final => true,
2226 pub fn is_final(&self) -> bool {
2227 *self == Defaultness::Final
2230 pub fn is_default(&self) -> bool {
2232 Defaultness::Default { .. } => true,
2238 #[derive(Debug, HashStable_Generic)]
2239 pub enum FnRetTy<'hir> {
2240 /// Return type is not specified.
2242 /// Functions default to `()` and
2243 /// closures default to inference. Span points to where return
2244 /// type would be inserted.
2245 DefaultReturn(Span),
2246 /// Everything else.
2247 Return(&'hir Ty<'hir>),
2251 pub fn span(&self) -> Span {
2253 Self::DefaultReturn(span) => span,
2254 Self::Return(ref ty) => ty.span,
2259 #[derive(Encodable, Debug)]
2260 pub struct Mod<'hir> {
2261 /// A span from the first token past `{` to the last token until `}`.
2262 /// For `mod foo;`, the inner span ranges from the first token
2263 /// to the last token in the external file.
2265 pub item_ids: &'hir [ItemId],
2268 #[derive(Debug, HashStable_Generic)]
2269 pub struct ForeignMod<'hir> {
2271 pub items: &'hir [ForeignItem<'hir>],
2274 #[derive(Encodable, Debug, HashStable_Generic)]
2275 pub struct GlobalAsm {
2279 #[derive(Debug, HashStable_Generic)]
2280 pub struct EnumDef<'hir> {
2281 pub variants: &'hir [Variant<'hir>],
2284 #[derive(Debug, HashStable_Generic)]
2285 pub struct Variant<'hir> {
2286 /// Name of the variant.
2287 #[stable_hasher(project(name))]
2289 /// Attributes of the variant.
2290 pub attrs: &'hir [Attribute],
2291 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2293 /// Fields and constructor id of the variant.
2294 pub data: VariantData<'hir>,
2295 /// Explicit discriminant (e.g., `Foo = 1`).
2296 pub disr_expr: Option<AnonConst>,
2301 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2303 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2304 /// Also produced for each element of a list `use`, e.g.
2305 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2308 /// Glob import, e.g., `use foo::*`.
2311 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2312 /// an additional `use foo::{}` for performing checks such as
2313 /// unstable feature gating. May be removed in the future.
2317 /// References to traits in impls.
2319 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2320 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2321 /// trait being referred to but just a unique `HirId` that serves as a key
2322 /// within the resolution map.
2323 #[derive(Debug, HashStable_Generic)]
2324 pub struct TraitRef<'hir> {
2325 pub path: &'hir Path<'hir>,
2326 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2327 #[stable_hasher(ignore)]
2328 pub hir_ref_id: HirId,
2332 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2333 pub fn trait_def_id(&self) -> Option<DefId> {
2334 match self.path.res {
2335 Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
2337 _ => unreachable!(),
2342 #[derive(Debug, HashStable_Generic)]
2343 pub struct PolyTraitRef<'hir> {
2344 /// The `'a` in `for<'a> Foo<&'a T>`.
2345 pub bound_generic_params: &'hir [GenericParam<'hir>],
2347 /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
2348 pub trait_ref: TraitRef<'hir>,
2353 pub type Visibility<'hir> = Spanned<VisibilityKind<'hir>>;
2356 pub enum VisibilityKind<'hir> {
2359 Restricted { path: &'hir Path<'hir>, hir_id: HirId },
2363 impl VisibilityKind<'_> {
2364 pub fn is_pub(&self) -> bool {
2366 VisibilityKind::Public => true,
2371 pub fn is_pub_restricted(&self) -> bool {
2373 VisibilityKind::Public | VisibilityKind::Inherited => false,
2374 VisibilityKind::Crate(..) | VisibilityKind::Restricted { .. } => true,
2378 pub fn descr(&self) -> &'static str {
2380 VisibilityKind::Public => "public",
2381 VisibilityKind::Inherited => "private",
2382 VisibilityKind::Crate(..) => "crate-visible",
2383 VisibilityKind::Restricted { .. } => "restricted",
2388 #[derive(Debug, HashStable_Generic)]
2389 pub struct StructField<'hir> {
2391 #[stable_hasher(project(name))]
2393 pub vis: Visibility<'hir>,
2395 pub ty: &'hir Ty<'hir>,
2396 pub attrs: &'hir [Attribute],
2399 impl StructField<'_> {
2400 // Still necessary in couple of places
2401 pub fn is_positional(&self) -> bool {
2402 let first = self.ident.as_str().as_bytes()[0];
2403 first >= b'0' && first <= b'9'
2407 /// Fields and constructor IDs of enum variants and structs.
2408 #[derive(Debug, HashStable_Generic)]
2409 pub enum VariantData<'hir> {
2410 /// A struct variant.
2412 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2413 Struct(&'hir [StructField<'hir>], /* recovered */ bool),
2414 /// A tuple variant.
2416 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2417 Tuple(&'hir [StructField<'hir>], HirId),
2420 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2424 impl VariantData<'hir> {
2425 /// Return the fields of this variant.
2426 pub fn fields(&self) -> &'hir [StructField<'hir>] {
2428 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2433 /// Return the `HirId` of this variant's constructor, if it has one.
2434 pub fn ctor_hir_id(&self) -> Option<HirId> {
2436 VariantData::Struct(_, _) => None,
2437 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2442 // The bodies for items are stored "out of line", in a separate
2443 // hashmap in the `Crate`. Here we just record the node-id of the item
2444 // so it can fetched later.
2445 #[derive(Copy, Clone, Encodable, Debug)]
2452 /// The name might be a dummy name in case of anonymous items
2454 pub struct Item<'hir> {
2457 pub attrs: &'hir [Attribute],
2458 pub kind: ItemKind<'hir>,
2459 pub vis: Visibility<'hir>,
2463 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2464 #[derive(Encodable, Decodable, HashStable_Generic)]
2471 pub fn prefix_str(&self) -> &'static str {
2473 Self::Unsafe => "unsafe ",
2479 impl fmt::Display for Unsafety {
2480 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2481 f.write_str(match *self {
2482 Self::Unsafe => "unsafe",
2483 Self::Normal => "normal",
2488 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2489 #[derive(Encodable, Decodable, HashStable_Generic)]
2490 pub enum Constness {
2495 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2496 pub struct FnHeader {
2497 pub unsafety: Unsafety,
2498 pub constness: Constness,
2499 pub asyncness: IsAsync,
2504 pub fn is_const(&self) -> bool {
2505 match &self.constness {
2506 Constness::Const => true,
2512 #[derive(Debug, HashStable_Generic)]
2513 pub enum ItemKind<'hir> {
2514 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2516 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2517 ExternCrate(Option<Symbol>),
2519 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2523 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2524 Use(&'hir Path<'hir>, UseKind),
2526 /// A `static` item.
2527 Static(&'hir Ty<'hir>, Mutability, BodyId),
2529 Const(&'hir Ty<'hir>, BodyId),
2530 /// A function declaration.
2531 Fn(FnSig<'hir>, Generics<'hir>, BodyId),
2534 /// An external module, e.g. `extern { .. }`.
2535 ForeignMod(ForeignMod<'hir>),
2536 /// Module-level inline assembly (from `global_asm!`).
2537 GlobalAsm(&'hir GlobalAsm),
2538 /// A type alias, e.g., `type Foo = Bar<u8>`.
2539 TyAlias(&'hir Ty<'hir>, Generics<'hir>),
2540 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2541 OpaqueTy(OpaqueTy<'hir>),
2542 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2543 Enum(EnumDef<'hir>, Generics<'hir>),
2544 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2545 Struct(VariantData<'hir>, Generics<'hir>),
2546 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2547 Union(VariantData<'hir>, Generics<'hir>),
2548 /// A trait definition.
2549 Trait(IsAuto, Unsafety, Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
2551 TraitAlias(Generics<'hir>, GenericBounds<'hir>),
2553 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2556 polarity: ImplPolarity,
2557 defaultness: Defaultness,
2558 // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata
2559 // decoding as `Span`s cannot be decoded when a `Session` is not available.
2560 defaultness_span: Option<Span>,
2561 constness: Constness,
2562 generics: Generics<'hir>,
2564 /// The trait being implemented, if any.
2565 of_trait: Option<TraitRef<'hir>>,
2567 self_ty: &'hir Ty<'hir>,
2568 items: &'hir [ImplItemRef<'hir>],
2573 pub fn generics(&self) -> Option<&Generics<'_>> {
2575 ItemKind::Fn(_, ref generics, _)
2576 | ItemKind::TyAlias(_, ref generics)
2577 | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
2578 | ItemKind::Enum(_, ref generics)
2579 | ItemKind::Struct(_, ref generics)
2580 | ItemKind::Union(_, ref generics)
2581 | ItemKind::Trait(_, _, ref generics, _, _)
2582 | ItemKind::Impl { ref generics, .. } => generics,
2588 /// A reference from an trait to one of its associated items. This
2589 /// contains the item's id, naturally, but also the item's name and
2590 /// some other high-level details (like whether it is an associated
2591 /// type or method, and whether it is public). This allows other
2592 /// passes to find the impl they want without loading the ID (which
2593 /// means fewer edges in the incremental compilation graph).
2594 #[derive(Encodable, Debug, HashStable_Generic)]
2595 pub struct TraitItemRef {
2596 pub id: TraitItemId,
2597 #[stable_hasher(project(name))]
2599 pub kind: AssocItemKind,
2601 pub defaultness: Defaultness,
2604 /// A reference from an impl to one of its associated items. This
2605 /// contains the item's ID, naturally, but also the item's name and
2606 /// some other high-level details (like whether it is an associated
2607 /// type or method, and whether it is public). This allows other
2608 /// passes to find the impl they want without loading the ID (which
2609 /// means fewer edges in the incremental compilation graph).
2610 #[derive(Debug, HashStable_Generic)]
2611 pub struct ImplItemRef<'hir> {
2613 #[stable_hasher(project(name))]
2615 pub kind: AssocItemKind,
2617 pub vis: Visibility<'hir>,
2618 pub defaultness: Defaultness,
2621 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2622 pub enum AssocItemKind {
2624 Fn { has_self: bool },
2628 #[derive(Debug, HashStable_Generic)]
2629 pub struct ForeignItem<'hir> {
2630 #[stable_hasher(project(name))]
2632 pub attrs: &'hir [Attribute],
2633 pub kind: ForeignItemKind<'hir>,
2636 pub vis: Visibility<'hir>,
2639 /// An item within an `extern` block.
2640 #[derive(Debug, HashStable_Generic)]
2641 pub enum ForeignItemKind<'hir> {
2642 /// A foreign function.
2643 Fn(&'hir FnDecl<'hir>, &'hir [Ident], Generics<'hir>),
2644 /// A foreign static item (`static ext: u8`).
2645 Static(&'hir Ty<'hir>, Mutability),
2650 /// A variable captured by a closure.
2651 #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)]
2653 // First span where it is accessed (there can be multiple).
2657 pub type CaptureModeMap = NodeMap<CaptureBy>;
2659 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2660 // has length > 0 if the trait is found through an chain of imports, starting with the
2661 // import/use statement in the scope where the trait is used.
2662 #[derive(Encodable, Decodable, Clone, Debug)]
2663 pub struct TraitCandidate {
2665 pub import_ids: SmallVec<[LocalDefId; 1]>,
2668 #[derive(Copy, Clone, Debug, HashStable_Generic)]
2669 pub enum Node<'hir> {
2670 Param(&'hir Param<'hir>),
2671 Item(&'hir Item<'hir>),
2672 ForeignItem(&'hir ForeignItem<'hir>),
2673 TraitItem(&'hir TraitItem<'hir>),
2674 ImplItem(&'hir ImplItem<'hir>),
2675 Variant(&'hir Variant<'hir>),
2676 Field(&'hir StructField<'hir>),
2677 AnonConst(&'hir AnonConst),
2678 Expr(&'hir Expr<'hir>),
2679 Stmt(&'hir Stmt<'hir>),
2680 PathSegment(&'hir PathSegment<'hir>),
2682 TraitRef(&'hir TraitRef<'hir>),
2683 Binding(&'hir Pat<'hir>),
2684 Pat(&'hir Pat<'hir>),
2685 Arm(&'hir Arm<'hir>),
2686 Block(&'hir Block<'hir>),
2687 Local(&'hir Local<'hir>),
2688 MacroDef(&'hir MacroDef<'hir>),
2690 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
2691 /// with synthesized constructors.
2692 Ctor(&'hir VariantData<'hir>),
2694 Lifetime(&'hir Lifetime),
2695 GenericParam(&'hir GenericParam<'hir>),
2696 Visibility(&'hir Visibility<'hir>),
2698 Crate(&'hir CrateItem<'hir>),
2701 impl<'hir> Node<'hir> {
2702 pub fn ident(&self) -> Option<Ident> {
2704 Node::TraitItem(TraitItem { ident, .. })
2705 | Node::ImplItem(ImplItem { ident, .. })
2706 | Node::ForeignItem(ForeignItem { ident, .. })
2707 | Node::Item(Item { ident, .. }) => Some(*ident),
2712 pub fn fn_decl(&self) -> Option<&FnDecl<'hir>> {
2714 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
2715 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
2716 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
2717 Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
2724 pub fn body_id(&self) -> Option<BodyId> {
2726 Node::TraitItem(TraitItem {
2727 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
2730 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
2731 | Node::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
2736 pub fn generics(&self) -> Option<&'hir Generics<'hir>> {
2738 Node::TraitItem(TraitItem { generics, .. })
2739 | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
2740 Node::Item(item) => item.kind.generics(),
2745 pub fn hir_id(&self) -> Option<HirId> {
2747 Node::Item(Item { hir_id, .. })
2748 | Node::ForeignItem(ForeignItem { hir_id, .. })
2749 | Node::TraitItem(TraitItem { hir_id, .. })
2750 | Node::ImplItem(ImplItem { hir_id, .. })
2751 | Node::Field(StructField { hir_id, .. })
2752 | Node::AnonConst(AnonConst { hir_id, .. })
2753 | Node::Expr(Expr { hir_id, .. })
2754 | Node::Stmt(Stmt { hir_id, .. })
2755 | Node::Ty(Ty { hir_id, .. })
2756 | Node::Binding(Pat { hir_id, .. })
2757 | Node::Pat(Pat { hir_id, .. })
2758 | Node::Arm(Arm { hir_id, .. })
2759 | Node::Block(Block { hir_id, .. })
2760 | Node::Local(Local { hir_id, .. })
2761 | Node::MacroDef(MacroDef { hir_id, .. })
2762 | Node::Lifetime(Lifetime { hir_id, .. })
2763 | Node::Param(Param { hir_id, .. })
2764 | Node::GenericParam(GenericParam { hir_id, .. }) => Some(*hir_id),
2765 Node::TraitRef(TraitRef { hir_ref_id, .. }) => Some(*hir_ref_id),
2766 Node::PathSegment(PathSegment { hir_id, .. }) => *hir_id,
2767 Node::Variant(Variant { id, .. }) => Some(*id),
2768 Node::Ctor(variant) => variant.ctor_hir_id(),
2769 Node::Crate(_) | Node::Visibility(_) => None,