1 use crate::def::{DefKind, Namespace, Res};
2 use crate::def_id::DefId;
3 crate use crate::hir_id::HirId;
4 use crate::itemlikevisit;
6 use rustc_ast::ast::{self, CrateSugar, LlvmAsmDialect};
7 use rustc_ast::ast::{AttrVec, Attribute, FloatTy, IntTy, Label, LitKind, StrStyle, UintTy};
8 pub use rustc_ast::ast::{BorrowKind, ImplPolarity, IsAuto};
9 pub use rustc_ast::ast::{CaptureBy, Movability, Mutability};
10 use rustc_ast::ast::{InlineAsmOptions, InlineAsmTemplatePiece};
11 use rustc_ast::node_id::NodeMap;
12 use rustc_ast::util::parser::ExprPrecedence;
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::{SourceMap, 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),
369 impl GenericBound<'_> {
370 pub fn trait_ref(&self) -> Option<&TraitRef<'_>> {
372 GenericBound::Trait(data, _) => Some(&data.trait_ref),
377 pub fn span(&self) -> Span {
379 &GenericBound::Trait(ref t, ..) => t.span,
380 &GenericBound::Outlives(ref l) => l.span,
385 pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
387 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
388 pub enum LifetimeParamKind {
389 // Indicates that the lifetime definition was explicitly declared (e.g., in
390 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
393 // Indicates that the lifetime definition was synthetically added
394 // as a result of an in-band lifetime usage (e.g., in
395 // `fn foo(x: &'a u8) -> &'a u8 { x }`).
398 // Indication that the lifetime was elided (e.g., in both cases in
399 // `fn foo(x: &u8) -> &'_ u8 { x }`).
402 // Indication that the lifetime name was somehow in error.
406 #[derive(Debug, HashStable_Generic)]
407 pub enum GenericParamKind<'hir> {
408 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
410 kind: LifetimeParamKind,
413 default: Option<&'hir Ty<'hir>>,
414 synthetic: Option<SyntheticTyParamKind>,
421 #[derive(Debug, HashStable_Generic)]
422 pub struct GenericParam<'hir> {
425 pub attrs: &'hir [Attribute],
426 pub bounds: GenericBounds<'hir>,
428 pub pure_wrt_drop: bool,
429 pub kind: GenericParamKind<'hir>,
432 impl GenericParam<'hir> {
433 pub fn bounds_span(&self) -> Option<Span> {
434 self.bounds.iter().fold(None, |span, bound| {
435 let span = span.map(|s| s.to(bound.span())).unwrap_or_else(|| bound.span());
443 pub struct GenericParamCount {
444 pub lifetimes: usize,
449 /// Represents lifetimes and type parameters attached to a declaration
450 /// of a function, enum, trait, etc.
451 #[derive(Debug, HashStable_Generic)]
452 pub struct Generics<'hir> {
453 pub params: &'hir [GenericParam<'hir>],
454 pub where_clause: WhereClause<'hir>,
458 impl Generics<'hir> {
459 pub const fn empty() -> Generics<'hir> {
462 where_clause: WhereClause { predicates: &[], span: DUMMY_SP },
467 pub fn own_counts(&self) -> GenericParamCount {
468 // We could cache this as a property of `GenericParamCount`, but
469 // the aim is to refactor this away entirely eventually and the
470 // presence of this method will be a constant reminder.
471 let mut own_counts: GenericParamCount = Default::default();
473 for param in self.params {
475 GenericParamKind::Lifetime { .. } => own_counts.lifetimes += 1,
476 GenericParamKind::Type { .. } => own_counts.types += 1,
477 GenericParamKind::Const { .. } => own_counts.consts += 1,
484 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'_>> {
485 for param in self.params {
486 if name == param.name.ident().name {
493 pub fn spans(&self) -> MultiSpan {
494 if self.params.is_empty() {
497 self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
502 /// Synthetic type parameters are converted to another form during lowering; this allows
503 /// us to track the original form they had, and is useful for error messages.
504 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
505 #[derive(HashStable_Generic)]
506 pub enum SyntheticTyParamKind {
510 /// A where-clause in a definition.
511 #[derive(Debug, HashStable_Generic)]
512 pub struct WhereClause<'hir> {
513 pub predicates: &'hir [WherePredicate<'hir>],
514 // Only valid if predicates aren't empty.
518 impl WhereClause<'_> {
519 pub fn span(&self) -> Option<Span> {
520 if self.predicates.is_empty() { None } else { Some(self.span) }
523 /// The `WhereClause` under normal circumstances points at either the predicates or the empty
524 /// space where the `where` clause should be. Only of use for diagnostic suggestions.
525 pub fn span_for_predicates_or_empty_place(&self) -> Span {
529 /// `Span` where further predicates would be suggested, accounting for trailing commas, like
530 /// in `fn foo<T>(t: T) where T: Foo,` so we don't suggest two trailing commas.
531 pub fn tail_span_for_suggestion(&self) -> Span {
532 let end = self.span_for_predicates_or_empty_place().shrink_to_hi();
533 self.predicates.last().map(|p| p.span()).unwrap_or(end).shrink_to_hi().to(end)
537 /// A single predicate in a where-clause.
538 #[derive(Debug, HashStable_Generic)]
539 pub enum WherePredicate<'hir> {
540 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
541 BoundPredicate(WhereBoundPredicate<'hir>),
542 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
543 RegionPredicate(WhereRegionPredicate<'hir>),
544 /// An equality predicate (unsupported).
545 EqPredicate(WhereEqPredicate<'hir>),
548 impl WherePredicate<'_> {
549 pub fn span(&self) -> Span {
551 &WherePredicate::BoundPredicate(ref p) => p.span,
552 &WherePredicate::RegionPredicate(ref p) => p.span,
553 &WherePredicate::EqPredicate(ref p) => p.span,
558 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
559 #[derive(Debug, HashStable_Generic)]
560 pub struct WhereBoundPredicate<'hir> {
562 /// Any generics from a `for` binding.
563 pub bound_generic_params: &'hir [GenericParam<'hir>],
564 /// The type being bounded.
565 pub bounded_ty: &'hir Ty<'hir>,
566 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
567 pub bounds: GenericBounds<'hir>,
570 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
571 #[derive(Debug, HashStable_Generic)]
572 pub struct WhereRegionPredicate<'hir> {
574 pub lifetime: Lifetime,
575 pub bounds: GenericBounds<'hir>,
578 /// An equality predicate (e.g., `T = int`); currently unsupported.
579 #[derive(Debug, HashStable_Generic)]
580 pub struct WhereEqPredicate<'hir> {
583 pub lhs_ty: &'hir Ty<'hir>,
584 pub rhs_ty: &'hir Ty<'hir>,
587 #[derive(Encodable, Debug, HashStable_Generic)]
588 pub struct ModuleItems {
589 // Use BTreeSets here so items are in the same order as in the
590 // list of all items in Crate
591 pub items: BTreeSet<HirId>,
592 pub trait_items: BTreeSet<TraitItemId>,
593 pub impl_items: BTreeSet<ImplItemId>,
596 /// A type representing only the top-level module.
597 #[derive(Encodable, Debug, HashStable_Generic)]
598 pub struct CrateItem<'hir> {
599 pub module: Mod<'hir>,
600 pub attrs: &'hir [Attribute],
604 /// The top-level data structure that stores the entire contents of
605 /// the crate currently being compiled.
607 /// For more details, see the [rustc dev guide].
609 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
611 pub struct Crate<'hir> {
612 pub item: CrateItem<'hir>,
613 pub exported_macros: &'hir [MacroDef<'hir>],
614 // Attributes from non-exported macros, kept only for collecting the library feature list.
615 pub non_exported_macro_attrs: &'hir [Attribute],
617 // N.B., we use a `BTreeMap` here so that `visit_all_items` iterates
618 // over the ids in increasing order. In principle it should not
619 // matter what order we visit things in, but in *practice* it
620 // does, because it can affect the order in which errors are
621 // detected, which in turn can make compile-fail tests yield
622 // slightly different results.
623 pub items: BTreeMap<HirId, Item<'hir>>,
625 pub trait_items: BTreeMap<TraitItemId, TraitItem<'hir>>,
626 pub impl_items: BTreeMap<ImplItemId, ImplItem<'hir>>,
627 pub bodies: BTreeMap<BodyId, Body<'hir>>,
628 pub trait_impls: BTreeMap<DefId, Vec<HirId>>,
630 /// A list of the body ids written out in the order in which they
631 /// appear in the crate. If you're going to process all the bodies
632 /// in the crate, you should iterate over this list rather than the keys
634 pub body_ids: Vec<BodyId>,
636 /// A list of modules written out in the order in which they
637 /// appear in the crate. This includes the main crate module.
638 pub modules: BTreeMap<HirId, ModuleItems>,
639 /// A list of proc macro HirIds, written out in the order in which
640 /// they are declared in the static array generated by proc_macro_harness.
641 pub proc_macros: Vec<HirId>,
643 pub trait_map: BTreeMap<HirId, Vec<TraitCandidate>>,
647 pub fn item(&self, id: HirId) -> &Item<'hir> {
651 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem<'hir> {
652 &self.trait_items[&id]
655 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem<'hir> {
656 &self.impl_items[&id]
659 pub fn body(&self, id: BodyId) -> &Body<'hir> {
665 /// Visits all items in the crate in some deterministic (but
666 /// unspecified) order. If you just need to process every item,
667 /// but don't care about nesting, this method is the best choice.
669 /// If you do care about nesting -- usually because your algorithm
670 /// follows lexical scoping rules -- then you want a different
671 /// approach. You should override `visit_nested_item` in your
672 /// visitor and then call `intravisit::walk_crate` instead.
673 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
675 V: itemlikevisit::ItemLikeVisitor<'hir>,
677 for item in self.items.values() {
678 visitor.visit_item(item);
681 for trait_item in self.trait_items.values() {
682 visitor.visit_trait_item(trait_item);
685 for impl_item in self.impl_items.values() {
686 visitor.visit_impl_item(impl_item);
690 /// A parallel version of `visit_all_item_likes`.
691 pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
693 V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send,
697 par_for_each_in(&self.items, |(_, item)| {
698 visitor.visit_item(item);
702 par_for_each_in(&self.trait_items, |(_, trait_item)| {
703 visitor.visit_trait_item(trait_item);
707 par_for_each_in(&self.impl_items, |(_, impl_item)| {
708 visitor.visit_impl_item(impl_item);
715 /// A macro definition, in this crate or imported from another.
717 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
718 #[derive(Debug, HashStable_Generic)]
719 pub struct MacroDef<'hir> {
721 pub vis: Visibility<'hir>,
722 pub attrs: &'hir [Attribute],
725 pub ast: ast::MacroDef,
728 /// A block of statements `{ .. }`, which may have a label (in this case the
729 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
730 /// the `rules` being anything but `DefaultBlock`.
731 #[derive(Debug, HashStable_Generic)]
732 pub struct Block<'hir> {
733 /// Statements in a block.
734 pub stmts: &'hir [Stmt<'hir>],
735 /// An expression at the end of the block
736 /// without a semicolon, if any.
737 pub expr: Option<&'hir Expr<'hir>>,
738 #[stable_hasher(ignore)]
740 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
741 pub rules: BlockCheckMode,
743 /// If true, then there may exist `break 'a` values that aim to
744 /// break out of this block early.
745 /// Used by `'label: {}` blocks and by `try {}` blocks.
746 pub targeted_by_break: bool,
749 #[derive(Debug, HashStable_Generic)]
750 pub struct Pat<'hir> {
751 #[stable_hasher(ignore)]
753 pub kind: PatKind<'hir>,
758 // FIXME(#19596) this is a workaround, but there should be a better way
759 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'_>) -> bool) -> bool {
766 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
767 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
768 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
769 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
770 Slice(before, slice, after) => {
771 before.iter().chain(slice.iter()).chain(after.iter()).all(|p| p.walk_short_(it))
776 /// Walk the pattern in left-to-right order,
777 /// short circuiting (with `.all(..)`) if `false` is returned.
779 /// Note that when visiting e.g. `Tuple(ps)`,
780 /// if visiting `ps[0]` returns `false`,
781 /// then `ps[1]` will not be visited.
782 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'_>) -> bool) -> bool {
783 self.walk_short_(&mut it)
786 // FIXME(#19596) this is a workaround, but there should be a better way
787 fn walk_(&self, it: &mut impl FnMut(&Pat<'_>) -> bool) {
794 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
795 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
796 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
797 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
798 Slice(before, slice, after) => {
799 before.iter().chain(slice.iter()).chain(after.iter()).for_each(|p| p.walk_(it))
804 /// Walk the pattern in left-to-right order.
806 /// If `it(pat)` returns `false`, the children are not visited.
807 pub fn walk(&self, mut it: impl FnMut(&Pat<'_>) -> bool) {
811 /// Walk the pattern in left-to-right order.
813 /// If you always want to recurse, prefer this method over `walk`.
814 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
822 /// A single field in a struct pattern.
824 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
825 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
826 /// except `is_shorthand` is true.
827 #[derive(Debug, HashStable_Generic)]
828 pub struct FieldPat<'hir> {
829 #[stable_hasher(ignore)]
831 /// The identifier for the field.
832 #[stable_hasher(project(name))]
834 /// The pattern the field is destructured to.
835 pub pat: &'hir Pat<'hir>,
836 pub is_shorthand: bool,
840 /// Explicit binding annotations given in the HIR for a binding. Note
841 /// that this is not the final binding *mode* that we infer after type
843 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
844 pub enum BindingAnnotation {
845 /// No binding annotation given: this means that the final binding mode
846 /// will depend on whether we have skipped through a `&` reference
847 /// when matching. For example, the `x` in `Some(x)` will have binding
848 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
849 /// ultimately be inferred to be by-reference.
851 /// Note that implicit reference skipping is not implemented yet (#42640).
854 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
857 /// Annotated as `ref`, like `ref x`
860 /// Annotated as `ref mut x`.
864 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
870 impl fmt::Display for RangeEnd {
871 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
872 f.write_str(match self {
873 RangeEnd::Included => "..=",
874 RangeEnd::Excluded => "..",
879 #[derive(Debug, HashStable_Generic)]
880 pub enum PatKind<'hir> {
881 /// Represents a wildcard pattern (i.e., `_`).
884 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
885 /// The `HirId` is the canonical ID for the variable being bound,
886 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
887 /// which is the pattern ID of the first `x`.
888 Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
890 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
891 /// The `bool` is `true` in the presence of a `..`.
892 Struct(QPath<'hir>, &'hir [FieldPat<'hir>], bool),
894 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
895 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
896 /// `0 <= position <= subpats.len()`
897 TupleStruct(QPath<'hir>, &'hir [&'hir Pat<'hir>], Option<usize>),
899 /// An or-pattern `A | B | C`.
900 /// Invariant: `pats.len() >= 2`.
901 Or(&'hir [&'hir Pat<'hir>]),
903 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
906 /// A tuple pattern (e.g., `(a, b)`).
907 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
908 /// `0 <= position <= subpats.len()`
909 Tuple(&'hir [&'hir Pat<'hir>], Option<usize>),
912 Box(&'hir Pat<'hir>),
914 /// A reference pattern (e.g., `&mut (a, b)`).
915 Ref(&'hir Pat<'hir>, Mutability),
918 Lit(&'hir Expr<'hir>),
920 /// A range pattern (e.g., `1..=2` or `1..2`).
921 Range(Option<&'hir Expr<'hir>>, Option<&'hir Expr<'hir>>, RangeEnd),
923 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
925 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
926 /// If `slice` exists, then `after` can be non-empty.
928 /// The representation for e.g., `[a, b, .., c, d]` is:
930 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
932 Slice(&'hir [&'hir Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [&'hir Pat<'hir>]),
935 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
937 /// The `+` operator (addition).
939 /// The `-` operator (subtraction).
941 /// The `*` operator (multiplication).
943 /// The `/` operator (division).
945 /// The `%` operator (modulus).
947 /// The `&&` operator (logical and).
949 /// The `||` operator (logical or).
951 /// The `^` operator (bitwise xor).
953 /// The `&` operator (bitwise and).
955 /// The `|` operator (bitwise or).
957 /// The `<<` operator (shift left).
959 /// The `>>` operator (shift right).
961 /// The `==` operator (equality).
963 /// The `<` operator (less than).
965 /// The `<=` operator (less than or equal to).
967 /// The `!=` operator (not equal to).
969 /// The `>=` operator (greater than or equal to).
971 /// The `>` operator (greater than).
976 pub fn as_str(self) -> &'static str {
978 BinOpKind::Add => "+",
979 BinOpKind::Sub => "-",
980 BinOpKind::Mul => "*",
981 BinOpKind::Div => "/",
982 BinOpKind::Rem => "%",
983 BinOpKind::And => "&&",
984 BinOpKind::Or => "||",
985 BinOpKind::BitXor => "^",
986 BinOpKind::BitAnd => "&",
987 BinOpKind::BitOr => "|",
988 BinOpKind::Shl => "<<",
989 BinOpKind::Shr => ">>",
990 BinOpKind::Eq => "==",
991 BinOpKind::Lt => "<",
992 BinOpKind::Le => "<=",
993 BinOpKind::Ne => "!=",
994 BinOpKind::Ge => ">=",
995 BinOpKind::Gt => ">",
999 pub fn is_lazy(self) -> bool {
1001 BinOpKind::And | BinOpKind::Or => true,
1006 pub fn is_shift(self) -> bool {
1008 BinOpKind::Shl | BinOpKind::Shr => true,
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 {
1091 Self::UnNeg | Self::UnNot => true,
1098 #[derive(Debug, HashStable_Generic)]
1099 pub struct Stmt<'hir> {
1101 pub kind: StmtKind<'hir>,
1105 /// The contents of a statement.
1106 #[derive(Debug, HashStable_Generic)]
1107 pub enum StmtKind<'hir> {
1108 /// A local (`let`) binding.
1109 Local(&'hir Local<'hir>),
1111 /// An item binding.
1114 /// An expression without a trailing semi-colon (must have unit type).
1115 Expr(&'hir Expr<'hir>),
1117 /// An expression with a trailing semi-colon (may have any type).
1118 Semi(&'hir Expr<'hir>),
1121 impl StmtKind<'hir> {
1122 pub fn attrs(&self) -> &'hir [Attribute] {
1124 StmtKind::Local(ref l) => &l.attrs,
1125 StmtKind::Item(_) => &[],
1126 StmtKind::Expr(ref e) | StmtKind::Semi(ref e) => &e.attrs,
1131 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1132 #[derive(Debug, HashStable_Generic)]
1133 pub struct Local<'hir> {
1134 pub pat: &'hir Pat<'hir>,
1135 /// Type annotation, if any (otherwise the type will be inferred).
1136 pub ty: Option<&'hir Ty<'hir>>,
1137 /// Initializer expression to set the value, if any.
1138 pub init: Option<&'hir Expr<'hir>>,
1142 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1143 /// desugaring. Otherwise will be `Normal`.
1144 pub source: LocalSource,
1147 /// Represents a single arm of a `match` expression, e.g.
1148 /// `<pat> (if <guard>) => <body>`.
1149 #[derive(Debug, HashStable_Generic)]
1150 pub struct Arm<'hir> {
1151 #[stable_hasher(ignore)]
1154 pub attrs: &'hir [Attribute],
1155 /// If this pattern and the optional guard matches, then `body` is evaluated.
1156 pub pat: &'hir Pat<'hir>,
1157 /// Optional guard clause.
1158 pub guard: Option<Guard<'hir>>,
1159 /// The expression the arm evaluates to if this arm matches.
1160 pub body: &'hir Expr<'hir>,
1163 #[derive(Debug, HashStable_Generic)]
1164 pub enum Guard<'hir> {
1165 If(&'hir Expr<'hir>),
1168 #[derive(Debug, HashStable_Generic)]
1169 pub struct Field<'hir> {
1170 #[stable_hasher(ignore)]
1173 pub expr: &'hir Expr<'hir>,
1175 pub is_shorthand: bool,
1178 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1179 pub enum BlockCheckMode {
1181 UnsafeBlock(UnsafeSource),
1182 PushUnsafeBlock(UnsafeSource),
1183 PopUnsafeBlock(UnsafeSource),
1186 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1187 pub enum UnsafeSource {
1192 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Hash, Debug)]
1197 /// The body of a function, closure, or constant value. In the case of
1198 /// a function, the body contains not only the function body itself
1199 /// (which is an expression), but also the argument patterns, since
1200 /// those are something that the caller doesn't really care about.
1205 /// fn foo((x, y): (u32, u32)) -> u32 {
1210 /// Here, the `Body` associated with `foo()` would contain:
1212 /// - an `params` array containing the `(x, y)` pattern
1213 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1214 /// - `generator_kind` would be `None`
1216 /// All bodies have an **owner**, which can be accessed via the HIR
1217 /// map using `body_owner_def_id()`.
1219 pub struct Body<'hir> {
1220 pub params: &'hir [Param<'hir>],
1221 pub value: Expr<'hir>,
1222 pub generator_kind: Option<GeneratorKind>,
1226 pub fn id(&self) -> BodyId {
1227 BodyId { hir_id: self.value.hir_id }
1230 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1235 /// The type of source expression that caused this generator to be created.
1236 #[derive(Clone, PartialEq, Eq, HashStable_Generic, Encodable, Decodable, Debug, Copy)]
1237 pub enum GeneratorKind {
1238 /// An explicit `async` block or the body of an async function.
1239 Async(AsyncGeneratorKind),
1241 /// A generator literal created via a `yield` inside a closure.
1245 impl fmt::Display for GeneratorKind {
1246 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1248 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1249 GeneratorKind::Gen => f.write_str("generator"),
1254 /// In the case of a generator created as part of an async construct,
1255 /// which kind of async construct caused it to be created?
1257 /// This helps error messages but is also used to drive coercions in
1258 /// type-checking (see #60424).
1259 #[derive(Clone, PartialEq, Eq, HashStable_Generic, Encodable, Decodable, Debug, Copy)]
1260 pub enum AsyncGeneratorKind {
1261 /// An explicit `async` block written by the user.
1264 /// An explicit `async` block written by the user.
1267 /// The `async` block generated as the body of an async function.
1271 impl fmt::Display for AsyncGeneratorKind {
1272 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1273 f.write_str(match self {
1274 AsyncGeneratorKind::Block => "`async` block",
1275 AsyncGeneratorKind::Closure => "`async` closure body",
1276 AsyncGeneratorKind::Fn => "`async fn` body",
1281 #[derive(Copy, Clone, Debug)]
1282 pub enum BodyOwnerKind {
1283 /// Functions and methods.
1289 /// Constants and associated constants.
1292 /// Initializer of a `static` item.
1296 impl BodyOwnerKind {
1297 pub fn is_fn_or_closure(self) -> bool {
1299 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1300 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1305 /// The kind of an item that requires const-checking.
1306 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1307 pub enum ConstContext {
1311 /// A `static` or `static mut`.
1314 /// A `const`, associated `const`, or other const context.
1316 /// Other contexts include:
1317 /// - Array length expressions
1318 /// - Enum discriminants
1319 /// - Const generics
1321 /// For the most part, other contexts are treated just like a regular `const`, so they are
1322 /// lumped into the same category.
1327 /// A description of this const context that can appear between backticks in an error message.
1329 /// E.g. `const` or `static mut`.
1330 pub fn keyword_name(self) -> &'static str {
1332 Self::Const => "const",
1333 Self::Static(Mutability::Not) => "static",
1334 Self::Static(Mutability::Mut) => "static mut",
1335 Self::ConstFn => "const fn",
1340 /// A colloquial, trivially pluralizable description of this const context for use in error
1342 impl fmt::Display for ConstContext {
1343 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1345 Self::Const => write!(f, "constant"),
1346 Self::Static(_) => write!(f, "static"),
1347 Self::ConstFn => write!(f, "constant function"),
1353 pub type Lit = Spanned<LitKind>;
1355 /// A constant (expression) that's not an item or associated item,
1356 /// but needs its own `DefId` for type-checking, const-eval, etc.
1357 /// These are usually found nested inside types (e.g., array lengths)
1358 /// or expressions (e.g., repeat counts), and also used to define
1359 /// explicit discriminant values for enum variants.
1360 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1361 pub struct AnonConst {
1368 pub struct Expr<'hir> {
1370 pub kind: ExprKind<'hir>,
1375 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1376 #[cfg(target_arch = "x86_64")]
1377 rustc_data_structures::static_assert_size!(Expr<'static>, 72);
1380 pub fn precedence(&self) -> ExprPrecedence {
1382 ExprKind::Box(_) => ExprPrecedence::Box,
1383 ExprKind::Array(_) => ExprPrecedence::Array,
1384 ExprKind::Call(..) => ExprPrecedence::Call,
1385 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1386 ExprKind::Tup(_) => ExprPrecedence::Tup,
1387 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1388 ExprKind::Unary(..) => ExprPrecedence::Unary,
1389 ExprKind::Lit(_) => ExprPrecedence::Lit,
1390 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1391 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1392 ExprKind::Loop(..) => ExprPrecedence::Loop,
1393 ExprKind::Match(..) => ExprPrecedence::Match,
1394 ExprKind::Closure(..) => ExprPrecedence::Closure,
1395 ExprKind::Block(..) => ExprPrecedence::Block,
1396 ExprKind::Assign(..) => ExprPrecedence::Assign,
1397 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1398 ExprKind::Field(..) => ExprPrecedence::Field,
1399 ExprKind::Index(..) => ExprPrecedence::Index,
1400 ExprKind::Path(..) => ExprPrecedence::Path,
1401 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1402 ExprKind::Break(..) => ExprPrecedence::Break,
1403 ExprKind::Continue(..) => ExprPrecedence::Continue,
1404 ExprKind::Ret(..) => ExprPrecedence::Ret,
1405 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1406 ExprKind::LlvmInlineAsm(..) => ExprPrecedence::InlineAsm,
1407 ExprKind::Struct(..) => ExprPrecedence::Struct,
1408 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1409 ExprKind::Yield(..) => ExprPrecedence::Yield,
1410 ExprKind::Err => ExprPrecedence::Err,
1414 // Whether this looks like a place expr, without checking for deref
1416 // This will return `true` in some potentially surprising cases such as
1417 // `CONSTANT.field`.
1418 pub fn is_syntactic_place_expr(&self) -> bool {
1419 self.is_place_expr(|_| true)
1422 // Whether this is a place expression.
1423 // `allow_projections_from` should return `true` if indexing a field or
1424 // index expression based on the given expression should be considered a
1425 // place expression.
1426 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1428 ExprKind::Path(QPath::Resolved(_, ref path)) => match path.res {
1429 Res::Local(..) | Res::Def(DefKind::Static, _) | Res::Err => true,
1433 // Type ascription inherits its place expression kind from its
1435 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1436 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1438 ExprKind::Unary(UnOp::UnDeref, _) => true,
1440 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1441 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
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::Unary(..)
1467 | ExprKind::AddrOf(..)
1468 | ExprKind::Binary(..)
1469 | ExprKind::Yield(..)
1470 | ExprKind::Cast(..)
1471 | ExprKind::DropTemps(..)
1472 | ExprKind::Err => false,
1476 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1477 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1478 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1479 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1480 /// beyond remembering to call this function before doing analysis on it.
1481 pub fn peel_drop_temps(&self) -> &Self {
1482 let mut expr = self;
1483 while let ExprKind::DropTemps(inner) = &expr.kind {
1490 /// Checks if the specified expression is a built-in range literal.
1491 /// (See: `LoweringContext::lower_expr()`).
1493 /// FIXME(#60607): This function is a hack. If and when we have `QPath::Lang(...)`,
1494 /// we can use that instead as simpler, more reliable mechanism, as opposed to using `SourceMap`.
1495 pub fn is_range_literal(sm: &SourceMap, expr: &Expr<'_>) -> bool {
1496 // Returns whether the given path represents a (desugared) range,
1497 // either in std or core, i.e. has either a `::std::ops::Range` or
1498 // `::core::ops::Range` prefix.
1499 fn is_range_path(path: &Path<'_>) -> bool {
1500 let segs: Vec<_> = path.segments.iter().map(|seg| seg.ident.to_string()).collect();
1501 let segs: Vec<_> = segs.iter().map(|seg| &**seg).collect();
1503 // "{{root}}" is the equivalent of `::` prefix in `Path`.
1504 if let ["{{root}}", std_core, "ops", range] = segs.as_slice() {
1505 (*std_core == "std" || *std_core == "core") && range.starts_with("Range")
1511 // Check whether a span corresponding to a range expression is a
1512 // range literal, rather than an explicit struct or `new()` call.
1513 fn is_lit(sm: &SourceMap, span: &Span) -> bool {
1514 sm.span_to_snippet(*span).map(|range_src| range_src.contains("..")).unwrap_or(false)
1518 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1519 ExprKind::Struct(ref qpath, _, _) => {
1520 if let QPath::Resolved(None, ref path) = **qpath {
1521 return is_range_path(&path) && is_lit(sm, &expr.span);
1525 // `..` desugars to its struct path.
1526 ExprKind::Path(QPath::Resolved(None, ref path)) => {
1527 return is_range_path(&path) && is_lit(sm, &expr.span);
1530 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1531 ExprKind::Call(ref func, _) => {
1532 if let ExprKind::Path(QPath::TypeRelative(ref ty, ref segment)) = func.kind {
1533 if let TyKind::Path(QPath::Resolved(None, ref path)) = ty.kind {
1534 let new_call = segment.ident.name == sym::new;
1535 return is_range_path(&path) && is_lit(sm, &expr.span) && new_call;
1546 #[derive(Debug, HashStable_Generic)]
1547 pub enum ExprKind<'hir> {
1548 /// A `box x` expression.
1549 Box(&'hir Expr<'hir>),
1550 /// An array (e.g., `[a, b, c, d]`).
1551 Array(&'hir [Expr<'hir>]),
1552 /// A function call.
1554 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1555 /// and the second field is the list of arguments.
1556 /// This also represents calling the constructor of
1557 /// tuple-like ADTs such as tuple structs and enum variants.
1558 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1559 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1561 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1562 /// (within the angle brackets).
1563 /// The first element of the vector of `Expr`s is the expression that evaluates
1564 /// to the object on which the method is being called on (the receiver),
1565 /// and the remaining elements are the rest of the arguments.
1566 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1567 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1568 /// The final `Span` represents the span of the function and arguments
1569 /// (e.g. `foo::<Bar, Baz>(a, b, c, d)` in `x.foo::<Bar, Baz>(a, b, c, d)`
1571 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1572 /// the `hir_id` of the `MethodCall` node itself.
1574 /// [`type_dependent_def_id`]: ../ty/struct.TypeckResults.html#method.type_dependent_def_id
1575 MethodCall(&'hir PathSegment<'hir>, Span, &'hir [Expr<'hir>], Span),
1576 /// A tuple (e.g., `(a, b, c, d)`).
1577 Tup(&'hir [Expr<'hir>]),
1578 /// A binary operation (e.g., `a + b`, `a * b`).
1579 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1580 /// A unary operation (e.g., `!x`, `*x`).
1581 Unary(UnOp, &'hir Expr<'hir>),
1582 /// A literal (e.g., `1`, `"foo"`).
1584 /// A cast (e.g., `foo as f64`).
1585 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1586 /// A type reference (e.g., `Foo`).
1587 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1588 /// Wraps the expression in a terminating scope.
1589 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1591 /// This construct only exists to tweak the drop order in HIR lowering.
1592 /// An example of that is the desugaring of `for` loops.
1593 DropTemps(&'hir Expr<'hir>),
1594 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1596 /// I.e., `'label: loop { <block> }`.
1597 Loop(&'hir Block<'hir>, Option<Label>, LoopSource),
1598 /// A `match` block, with a source that indicates whether or not it is
1599 /// the result of a desugaring, and if so, which kind.
1600 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1601 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1603 /// The `Span` is the argument block `|...|`.
1605 /// This may also be a generator literal or an `async block` as indicated by the
1606 /// `Option<Movability>`.
1607 Closure(CaptureBy, &'hir FnDecl<'hir>, BodyId, Span, Option<Movability>),
1608 /// A block (e.g., `'label: { ... }`).
1609 Block(&'hir Block<'hir>, Option<Label>),
1611 /// An assignment (e.g., `a = foo()`).
1612 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1613 /// An assignment with an operator.
1616 AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1617 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1618 Field(&'hir Expr<'hir>, Ident),
1619 /// An indexing operation (`foo[2]`).
1620 Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1622 /// Path to a definition, possibly containing lifetime or type parameters.
1625 /// A referencing operation (i.e., `&a` or `&mut a`).
1626 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1627 /// A `break`, with an optional label to break.
1628 Break(Destination, Option<&'hir Expr<'hir>>),
1629 /// A `continue`, with an optional label.
1630 Continue(Destination),
1631 /// A `return`, with an optional value to be returned.
1632 Ret(Option<&'hir Expr<'hir>>),
1634 /// Inline assembly (from `asm!`), with its outputs and inputs.
1635 InlineAsm(&'hir InlineAsm<'hir>),
1636 /// Inline assembly (from `llvm_asm!`), with its outputs and inputs.
1637 LlvmInlineAsm(&'hir LlvmInlineAsm<'hir>),
1639 /// A struct or struct-like variant literal expression.
1641 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1642 /// where `base` is the `Option<Expr>`.
1643 Struct(&'hir QPath<'hir>, &'hir [Field<'hir>], Option<&'hir Expr<'hir>>),
1645 /// An array literal constructed from one repeated element.
1647 /// E.g., `[1; 5]`. The first expression is the element
1648 /// to be repeated; the second is the number of times to repeat it.
1649 Repeat(&'hir Expr<'hir>, AnonConst),
1651 /// A suspension point for generators (i.e., `yield <expr>`).
1652 Yield(&'hir Expr<'hir>, YieldSource),
1654 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1658 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1660 /// To resolve the path to a `DefId`, call [`qpath_res`].
1662 /// [`qpath_res`]: ../rustc_middle/ty/struct.TypeckResults.html#method.qpath_res
1663 #[derive(Debug, HashStable_Generic)]
1664 pub enum QPath<'hir> {
1665 /// Path to a definition, optionally "fully-qualified" with a `Self`
1666 /// type, if the path points to an associated item in a trait.
1668 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1669 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1670 /// even though they both have the same two-segment `Clone::clone` `Path`.
1671 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
1673 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1674 /// Will be resolved by type-checking to an associated item.
1676 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1677 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1678 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1679 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
1682 /// Hints at the original code for a let statement.
1683 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1684 pub enum LocalSource {
1685 /// A `match _ { .. }`.
1687 /// A desugared `for _ in _ { .. }` loop.
1689 /// When lowering async functions, we create locals within the `async move` so that
1690 /// all parameters are dropped after the future is polled.
1692 /// ```ignore (pseudo-Rust)
1693 /// async fn foo(<pattern> @ x: Type) {
1695 /// let <pattern> = x;
1700 /// A desugared `<expr>.await`.
1704 /// Hints at the original code for a `match _ { .. }`.
1705 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
1706 #[derive(HashStable_Generic)]
1707 pub enum MatchSource {
1708 /// A `match _ { .. }`.
1710 /// An `if _ { .. }` (optionally with `else { .. }`).
1711 IfDesugar { contains_else_clause: bool },
1712 /// An `if let _ = _ { .. }` (optionally with `else { .. }`).
1713 IfLetDesugar { contains_else_clause: bool },
1714 /// A `while _ { .. }` (which was desugared to a `loop { match _ { .. } }`).
1716 /// A `while let _ = _ { .. }` (which was desugared to a
1717 /// `loop { match _ { .. } }`).
1719 /// A desugared `for _ in _ { .. }` loop.
1721 /// A desugared `?` operator.
1723 /// A desugared `<expr>.await`.
1728 pub fn name(self) -> &'static str {
1732 IfDesugar { .. } | IfLetDesugar { .. } => "if",
1733 WhileDesugar | WhileLetDesugar => "while",
1734 ForLoopDesugar => "for",
1736 AwaitDesugar => ".await",
1741 /// The loop type that yielded an `ExprKind::Loop`.
1742 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1743 pub enum LoopSource {
1744 /// A `loop { .. }` loop.
1746 /// A `while _ { .. }` loop.
1748 /// A `while let _ = _ { .. }` loop.
1750 /// A `for _ in _ { .. }` loop.
1755 pub fn name(self) -> &'static str {
1757 LoopSource::Loop => "loop",
1758 LoopSource::While | LoopSource::WhileLet => "while",
1759 LoopSource::ForLoop => "for",
1764 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1765 pub enum LoopIdError {
1767 UnlabeledCfInWhileCondition,
1771 impl fmt::Display for LoopIdError {
1772 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1773 f.write_str(match self {
1774 LoopIdError::OutsideLoopScope => "not inside loop scope",
1775 LoopIdError::UnlabeledCfInWhileCondition => {
1776 "unlabeled control flow (break or continue) in while condition"
1778 LoopIdError::UnresolvedLabel => "label not found",
1783 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1784 pub struct Destination {
1785 // This is `Some(_)` iff there is an explicit user-specified `label
1786 pub label: Option<Label>,
1788 // These errors are caught and then reported during the diagnostics pass in
1789 // librustc_passes/loops.rs
1790 pub target_id: Result<HirId, LoopIdError>,
1793 /// The yield kind that caused an `ExprKind::Yield`.
1794 #[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
1795 pub enum YieldSource {
1796 /// An `<expr>.await`.
1797 Await { expr: Option<HirId> },
1798 /// A plain `yield`.
1803 pub fn is_await(&self) -> bool {
1805 YieldSource::Await { .. } => true,
1806 YieldSource::Yield => false,
1811 impl fmt::Display for YieldSource {
1812 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1813 f.write_str(match self {
1814 YieldSource::Await { .. } => "`await`",
1815 YieldSource::Yield => "`yield`",
1820 impl From<GeneratorKind> for YieldSource {
1821 fn from(kind: GeneratorKind) -> Self {
1823 // Guess based on the kind of the current generator.
1824 GeneratorKind::Gen => Self::Yield,
1825 GeneratorKind::Async(_) => Self::Await { expr: None },
1830 // N.B., if you change this, you'll probably want to change the corresponding
1831 // type structure in middle/ty.rs as well.
1832 #[derive(Debug, HashStable_Generic)]
1833 pub struct MutTy<'hir> {
1834 pub ty: &'hir Ty<'hir>,
1835 pub mutbl: Mutability,
1838 /// Represents a function's signature in a trait declaration,
1839 /// trait implementation, or a free function.
1840 #[derive(Debug, HashStable_Generic)]
1841 pub struct FnSig<'hir> {
1842 pub header: FnHeader,
1843 pub decl: &'hir FnDecl<'hir>,
1846 // The bodies for items are stored "out of line", in a separate
1847 // hashmap in the `Crate`. Here we just record the node-id of the item
1848 // so it can fetched later.
1849 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
1850 pub struct TraitItemId {
1854 /// Represents an item declaration within a trait declaration,
1855 /// possibly including a default implementation. A trait item is
1856 /// either required (meaning it doesn't have an implementation, just a
1857 /// signature) or provided (meaning it has a default implementation).
1859 pub struct TraitItem<'hir> {
1862 pub attrs: &'hir [Attribute],
1863 pub generics: Generics<'hir>,
1864 pub kind: TraitItemKind<'hir>,
1868 /// Represents a trait method's body (or just argument names).
1869 #[derive(Encodable, Debug, HashStable_Generic)]
1870 pub enum TraitFn<'hir> {
1871 /// No default body in the trait, just a signature.
1872 Required(&'hir [Ident]),
1874 /// Both signature and body are provided in the trait.
1878 /// Represents a trait method or associated constant or type
1879 #[derive(Debug, HashStable_Generic)]
1880 pub enum TraitItemKind<'hir> {
1881 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
1882 Const(&'hir Ty<'hir>, Option<BodyId>),
1883 /// An associated function with an optional body.
1884 Fn(FnSig<'hir>, TraitFn<'hir>),
1885 /// An associated type with (possibly empty) bounds and optional concrete
1887 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
1890 // The bodies for items are stored "out of line", in a separate
1891 // hashmap in the `Crate`. Here we just record the node-id of the item
1892 // so it can fetched later.
1893 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
1894 pub struct ImplItemId {
1898 /// Represents anything within an `impl` block.
1900 pub struct ImplItem<'hir> {
1903 pub vis: Visibility<'hir>,
1904 pub defaultness: Defaultness,
1905 pub attrs: &'hir [Attribute],
1906 pub generics: Generics<'hir>,
1907 pub kind: ImplItemKind<'hir>,
1911 /// Represents various kinds of content within an `impl`.
1912 #[derive(Debug, HashStable_Generic)]
1913 pub enum ImplItemKind<'hir> {
1914 /// An associated constant of the given type, set to the constant result
1915 /// of the expression.
1916 Const(&'hir Ty<'hir>, BodyId),
1917 /// An associated function implementation with the given signature and body.
1918 Fn(FnSig<'hir>, BodyId),
1919 /// An associated type.
1920 TyAlias(&'hir Ty<'hir>),
1923 impl ImplItemKind<'_> {
1924 pub fn namespace(&self) -> Namespace {
1926 ImplItemKind::TyAlias(..) => Namespace::TypeNS,
1927 ImplItemKind::Const(..) | ImplItemKind::Fn(..) => Namespace::ValueNS,
1932 // The name of the associated type for `Fn` return types.
1933 pub const FN_OUTPUT_NAME: Symbol = sym::Output;
1935 /// Bind a type to an associated type (i.e., `A = Foo`).
1937 /// Bindings like `A: Debug` are represented as a special type `A =
1938 /// $::Debug` that is understood by the astconv code.
1940 /// FIXME(alexreg): why have a separate type for the binding case,
1941 /// wouldn't it be better to make the `ty` field an enum like the
1945 /// enum TypeBindingKind {
1950 #[derive(Debug, HashStable_Generic)]
1951 pub struct TypeBinding<'hir> {
1953 #[stable_hasher(project(name))]
1955 pub kind: TypeBindingKind<'hir>,
1959 // Represents the two kinds of type bindings.
1960 #[derive(Debug, HashStable_Generic)]
1961 pub enum TypeBindingKind<'hir> {
1962 /// E.g., `Foo<Bar: Send>`.
1963 Constraint { bounds: &'hir [GenericBound<'hir>] },
1964 /// E.g., `Foo<Bar = ()>`.
1965 Equality { ty: &'hir Ty<'hir> },
1968 impl TypeBinding<'_> {
1969 pub fn ty(&self) -> &Ty<'_> {
1971 TypeBindingKind::Equality { ref ty } => ty,
1972 _ => panic!("expected equality type binding for parenthesized generic args"),
1978 pub struct Ty<'hir> {
1980 pub kind: TyKind<'hir>,
1984 /// Not represented directly in the AST; referred to by name through a `ty_path`.
1985 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
1986 #[derive(HashStable_Generic)]
1996 #[derive(Debug, HashStable_Generic)]
1997 pub struct BareFnTy<'hir> {
1998 pub unsafety: Unsafety,
2000 pub generic_params: &'hir [GenericParam<'hir>],
2001 pub decl: &'hir FnDecl<'hir>,
2002 pub param_names: &'hir [Ident],
2005 #[derive(Debug, HashStable_Generic)]
2006 pub struct OpaqueTy<'hir> {
2007 pub generics: Generics<'hir>,
2008 pub bounds: GenericBounds<'hir>,
2009 pub impl_trait_fn: Option<DefId>,
2010 pub origin: OpaqueTyOrigin,
2013 /// From whence the opaque type came.
2014 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2015 pub enum OpaqueTyOrigin {
2020 /// `let _: impl Trait = ...`
2022 /// Impl trait in type aliases, consts, statics, bounds.
2026 /// The various kinds of types recognized by the compiler.
2027 #[derive(Debug, HashStable_Generic)]
2028 pub enum TyKind<'hir> {
2029 /// A variable length slice (i.e., `[T]`).
2030 Slice(&'hir Ty<'hir>),
2031 /// A fixed length array (i.e., `[T; n]`).
2032 Array(&'hir Ty<'hir>, AnonConst),
2033 /// A raw pointer (i.e., `*const T` or `*mut T`).
2035 /// A reference (i.e., `&'a T` or `&'a mut T`).
2036 Rptr(Lifetime, MutTy<'hir>),
2037 /// A bare function (e.g., `fn(usize) -> bool`).
2038 BareFn(&'hir BareFnTy<'hir>),
2039 /// The never type (`!`).
2041 /// A tuple (`(A, B, C, D, ...)`).
2042 Tup(&'hir [Ty<'hir>]),
2043 /// A path to a type definition (`module::module::...::Type`), or an
2044 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2046 /// Type parameters may be stored in each `PathSegment`.
2048 /// A opaque type definition itself. This is currently only used for the
2049 /// `opaque type Foo: Trait` item that `impl Trait` in desugars to.
2051 /// The generic argument list contains the lifetimes (and in the future
2052 /// possibly parameters) that are actually bound on the `impl Trait`.
2053 OpaqueDef(ItemId, &'hir [GenericArg<'hir>]),
2054 /// A trait object type `Bound1 + Bound2 + Bound3`
2055 /// where `Bound` is a trait or a lifetime.
2056 TraitObject(&'hir [PolyTraitRef<'hir>], Lifetime),
2059 /// `TyKind::Infer` means the type should be inferred instead of it having been
2060 /// specified. This can appear anywhere in a type.
2062 /// Placeholder for a type that has failed to be defined.
2066 #[derive(Debug, HashStable_Generic)]
2067 pub enum InlineAsmOperand<'hir> {
2069 reg: InlineAsmRegOrRegClass,
2073 reg: InlineAsmRegOrRegClass,
2075 expr: Option<Expr<'hir>>,
2078 reg: InlineAsmRegOrRegClass,
2083 reg: InlineAsmRegOrRegClass,
2085 in_expr: Expr<'hir>,
2086 out_expr: Option<Expr<'hir>>,
2096 impl<'hir> InlineAsmOperand<'hir> {
2097 pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
2099 Self::In { reg, .. }
2100 | Self::Out { reg, .. }
2101 | Self::InOut { reg, .. }
2102 | Self::SplitInOut { reg, .. } => Some(reg),
2103 Self::Const { .. } | Self::Sym { .. } => None,
2108 #[derive(Debug, HashStable_Generic)]
2109 pub struct InlineAsm<'hir> {
2110 pub template: &'hir [InlineAsmTemplatePiece],
2111 pub operands: &'hir [InlineAsmOperand<'hir>],
2112 pub options: InlineAsmOptions,
2113 pub line_spans: &'hir [Span],
2116 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic, PartialEq)]
2117 pub struct LlvmInlineAsmOutput {
2118 pub constraint: Symbol,
2120 pub is_indirect: bool,
2124 // NOTE(eddyb) This is used within MIR as well, so unlike the rest of the HIR,
2125 // it needs to be `Clone` and `Decodable` and use plain `Vec<T>` instead of
2126 // arena-allocated slice.
2127 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic, PartialEq)]
2128 pub struct LlvmInlineAsmInner {
2130 pub asm_str_style: StrStyle,
2131 pub outputs: Vec<LlvmInlineAsmOutput>,
2132 pub inputs: Vec<Symbol>,
2133 pub clobbers: Vec<Symbol>,
2135 pub alignstack: bool,
2136 pub dialect: LlvmAsmDialect,
2139 #[derive(Debug, HashStable_Generic)]
2140 pub struct LlvmInlineAsm<'hir> {
2141 pub inner: LlvmInlineAsmInner,
2142 pub outputs_exprs: &'hir [Expr<'hir>],
2143 pub inputs_exprs: &'hir [Expr<'hir>],
2146 /// Represents a parameter in a function header.
2147 #[derive(Debug, HashStable_Generic)]
2148 pub struct Param<'hir> {
2149 pub attrs: &'hir [Attribute],
2151 pub pat: &'hir Pat<'hir>,
2156 /// Represents the header (not the body) of a function declaration.
2157 #[derive(Debug, HashStable_Generic)]
2158 pub struct FnDecl<'hir> {
2159 /// The types of the function's parameters.
2161 /// Additional argument data is stored in the function's [body](Body::params).
2162 pub inputs: &'hir [Ty<'hir>],
2163 pub output: FnRetTy<'hir>,
2164 pub c_variadic: bool,
2165 /// Does the function have an implicit self?
2166 pub implicit_self: ImplicitSelfKind,
2169 /// Represents what type of implicit self a function has, if any.
2170 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2171 pub enum ImplicitSelfKind {
2172 /// Represents a `fn x(self);`.
2174 /// Represents a `fn x(mut self);`.
2176 /// Represents a `fn x(&self);`.
2178 /// Represents a `fn x(&mut self);`.
2180 /// Represents when a function does not have a self argument or
2181 /// when a function has a `self: X` argument.
2185 impl ImplicitSelfKind {
2186 /// Does this represent an implicit self?
2187 pub fn has_implicit_self(&self) -> bool {
2189 ImplicitSelfKind::None => false,
2195 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable, Debug)]
2196 #[derive(HashStable_Generic)]
2202 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable, HashStable_Generic)]
2203 pub enum Defaultness {
2204 Default { has_value: bool },
2209 pub fn has_value(&self) -> bool {
2211 Defaultness::Default { has_value } => has_value,
2212 Defaultness::Final => true,
2216 pub fn is_final(&self) -> bool {
2217 *self == Defaultness::Final
2220 pub fn is_default(&self) -> bool {
2222 Defaultness::Default { .. } => true,
2228 #[derive(Debug, HashStable_Generic)]
2229 pub enum FnRetTy<'hir> {
2230 /// Return type is not specified.
2232 /// Functions default to `()` and
2233 /// closures default to inference. Span points to where return
2234 /// type would be inserted.
2235 DefaultReturn(Span),
2236 /// Everything else.
2237 Return(&'hir Ty<'hir>),
2241 pub fn span(&self) -> Span {
2243 Self::DefaultReturn(span) => span,
2244 Self::Return(ref ty) => ty.span,
2249 #[derive(Encodable, Debug)]
2250 pub struct Mod<'hir> {
2251 /// A span from the first token past `{` to the last token until `}`.
2252 /// For `mod foo;`, the inner span ranges from the first token
2253 /// to the last token in the external file.
2255 pub item_ids: &'hir [ItemId],
2258 #[derive(Debug, HashStable_Generic)]
2259 pub struct ForeignMod<'hir> {
2261 pub items: &'hir [ForeignItem<'hir>],
2264 #[derive(Encodable, Debug, HashStable_Generic)]
2265 pub struct GlobalAsm {
2269 #[derive(Debug, HashStable_Generic)]
2270 pub struct EnumDef<'hir> {
2271 pub variants: &'hir [Variant<'hir>],
2274 #[derive(Debug, HashStable_Generic)]
2275 pub struct Variant<'hir> {
2276 /// Name of the variant.
2277 #[stable_hasher(project(name))]
2279 /// Attributes of the variant.
2280 pub attrs: &'hir [Attribute],
2281 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2283 /// Fields and constructor id of the variant.
2284 pub data: VariantData<'hir>,
2285 /// Explicit discriminant (e.g., `Foo = 1`).
2286 pub disr_expr: Option<AnonConst>,
2291 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2293 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2294 /// Also produced for each element of a list `use`, e.g.
2295 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2298 /// Glob import, e.g., `use foo::*`.
2301 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2302 /// an additional `use foo::{}` for performing checks such as
2303 /// unstable feature gating. May be removed in the future.
2307 /// References to traits in impls.
2309 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2310 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2311 /// trait being referred to but just a unique `HirId` that serves as a key
2312 /// within the resolution map.
2313 #[derive(Debug, HashStable_Generic)]
2314 pub struct TraitRef<'hir> {
2315 pub path: &'hir Path<'hir>,
2316 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2317 #[stable_hasher(ignore)]
2318 pub hir_ref_id: HirId,
2322 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2323 pub fn trait_def_id(&self) -> Option<DefId> {
2324 match self.path.res {
2325 Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
2327 _ => unreachable!(),
2332 #[derive(Debug, HashStable_Generic)]
2333 pub struct PolyTraitRef<'hir> {
2334 /// The `'a` in `for<'a> Foo<&'a T>`.
2335 pub bound_generic_params: &'hir [GenericParam<'hir>],
2337 /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
2338 pub trait_ref: TraitRef<'hir>,
2343 pub type Visibility<'hir> = Spanned<VisibilityKind<'hir>>;
2346 pub enum VisibilityKind<'hir> {
2349 Restricted { path: &'hir Path<'hir>, hir_id: HirId },
2353 impl VisibilityKind<'_> {
2354 pub fn is_pub(&self) -> bool {
2356 VisibilityKind::Public => true,
2361 pub fn is_pub_restricted(&self) -> bool {
2363 VisibilityKind::Public | VisibilityKind::Inherited => false,
2364 VisibilityKind::Crate(..) | VisibilityKind::Restricted { .. } => true,
2368 pub fn descr(&self) -> &'static str {
2370 VisibilityKind::Public => "public",
2371 VisibilityKind::Inherited => "private",
2372 VisibilityKind::Crate(..) => "crate-visible",
2373 VisibilityKind::Restricted { .. } => "restricted",
2378 #[derive(Debug, HashStable_Generic)]
2379 pub struct StructField<'hir> {
2381 #[stable_hasher(project(name))]
2383 pub vis: Visibility<'hir>,
2385 pub ty: &'hir Ty<'hir>,
2386 pub attrs: &'hir [Attribute],
2389 impl StructField<'_> {
2390 // Still necessary in couple of places
2391 pub fn is_positional(&self) -> bool {
2392 let first = self.ident.as_str().as_bytes()[0];
2393 first >= b'0' && first <= b'9'
2397 /// Fields and constructor IDs of enum variants and structs.
2398 #[derive(Debug, HashStable_Generic)]
2399 pub enum VariantData<'hir> {
2400 /// A struct variant.
2402 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2403 Struct(&'hir [StructField<'hir>], /* recovered */ bool),
2404 /// A tuple variant.
2406 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2407 Tuple(&'hir [StructField<'hir>], HirId),
2410 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2414 impl VariantData<'hir> {
2415 /// Return the fields of this variant.
2416 pub fn fields(&self) -> &'hir [StructField<'hir>] {
2418 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2423 /// Return the `HirId` of this variant's constructor, if it has one.
2424 pub fn ctor_hir_id(&self) -> Option<HirId> {
2426 VariantData::Struct(_, _) => None,
2427 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2432 // The bodies for items are stored "out of line", in a separate
2433 // hashmap in the `Crate`. Here we just record the node-id of the item
2434 // so it can fetched later.
2435 #[derive(Copy, Clone, Encodable, Debug)]
2442 /// The name might be a dummy name in case of anonymous items
2444 pub struct Item<'hir> {
2447 pub attrs: &'hir [Attribute],
2448 pub kind: ItemKind<'hir>,
2449 pub vis: Visibility<'hir>,
2453 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2454 #[derive(Encodable, Decodable, HashStable_Generic)]
2461 pub fn prefix_str(&self) -> &'static str {
2463 Self::Unsafe => "unsafe ",
2469 impl fmt::Display for Unsafety {
2470 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2471 f.write_str(match *self {
2472 Self::Unsafe => "unsafe",
2473 Self::Normal => "normal",
2478 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2479 #[derive(Encodable, Decodable, HashStable_Generic)]
2480 pub enum Constness {
2485 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2486 pub struct FnHeader {
2487 pub unsafety: Unsafety,
2488 pub constness: Constness,
2489 pub asyncness: IsAsync,
2494 pub fn is_const(&self) -> bool {
2495 match &self.constness {
2496 Constness::Const => true,
2502 #[derive(Debug, HashStable_Generic)]
2503 pub enum ItemKind<'hir> {
2504 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2506 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2507 ExternCrate(Option<Symbol>),
2509 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2513 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2514 Use(&'hir Path<'hir>, UseKind),
2516 /// A `static` item.
2517 Static(&'hir Ty<'hir>, Mutability, BodyId),
2519 Const(&'hir Ty<'hir>, BodyId),
2520 /// A function declaration.
2521 Fn(FnSig<'hir>, Generics<'hir>, BodyId),
2524 /// An external module, e.g. `extern { .. }`.
2525 ForeignMod(ForeignMod<'hir>),
2526 /// Module-level inline assembly (from `global_asm!`).
2527 GlobalAsm(&'hir GlobalAsm),
2528 /// A type alias, e.g., `type Foo = Bar<u8>`.
2529 TyAlias(&'hir Ty<'hir>, Generics<'hir>),
2530 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2531 OpaqueTy(OpaqueTy<'hir>),
2532 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2533 Enum(EnumDef<'hir>, Generics<'hir>),
2534 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2535 Struct(VariantData<'hir>, Generics<'hir>),
2536 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2537 Union(VariantData<'hir>, Generics<'hir>),
2538 /// A trait definition.
2539 Trait(IsAuto, Unsafety, Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
2541 TraitAlias(Generics<'hir>, GenericBounds<'hir>),
2543 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2546 polarity: ImplPolarity,
2547 defaultness: Defaultness,
2548 // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata
2549 // decoding as `Span`s cannot be decoded when a `Session` is not available.
2550 defaultness_span: Option<Span>,
2551 constness: Constness,
2552 generics: Generics<'hir>,
2554 /// The trait being implemented, if any.
2555 of_trait: Option<TraitRef<'hir>>,
2557 self_ty: &'hir Ty<'hir>,
2558 items: &'hir [ImplItemRef<'hir>],
2563 pub fn generics(&self) -> Option<&Generics<'_>> {
2565 ItemKind::Fn(_, ref generics, _)
2566 | ItemKind::TyAlias(_, ref generics)
2567 | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
2568 | ItemKind::Enum(_, ref generics)
2569 | ItemKind::Struct(_, ref generics)
2570 | ItemKind::Union(_, ref generics)
2571 | ItemKind::Trait(_, _, ref generics, _, _)
2572 | ItemKind::Impl { ref generics, .. } => generics,
2578 /// A reference from an trait to one of its associated items. This
2579 /// contains the item's id, naturally, but also the item's name and
2580 /// some other high-level details (like whether it is an associated
2581 /// type or method, and whether it is public). This allows other
2582 /// passes to find the impl they want without loading the ID (which
2583 /// means fewer edges in the incremental compilation graph).
2584 #[derive(Encodable, Debug, HashStable_Generic)]
2585 pub struct TraitItemRef {
2586 pub id: TraitItemId,
2587 #[stable_hasher(project(name))]
2589 pub kind: AssocItemKind,
2591 pub defaultness: Defaultness,
2594 /// A reference from an impl to one of its associated items. This
2595 /// contains the item's ID, naturally, but also the item's name and
2596 /// some other high-level details (like whether it is an associated
2597 /// type or method, and whether it is public). This allows other
2598 /// passes to find the impl they want without loading the ID (which
2599 /// means fewer edges in the incremental compilation graph).
2600 #[derive(Debug, HashStable_Generic)]
2601 pub struct ImplItemRef<'hir> {
2603 #[stable_hasher(project(name))]
2605 pub kind: AssocItemKind,
2607 pub vis: Visibility<'hir>,
2608 pub defaultness: Defaultness,
2611 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2612 pub enum AssocItemKind {
2614 Fn { has_self: bool },
2618 #[derive(Debug, HashStable_Generic)]
2619 pub struct ForeignItem<'hir> {
2620 #[stable_hasher(project(name))]
2622 pub attrs: &'hir [Attribute],
2623 pub kind: ForeignItemKind<'hir>,
2626 pub vis: Visibility<'hir>,
2629 /// An item within an `extern` block.
2630 #[derive(Debug, HashStable_Generic)]
2631 pub enum ForeignItemKind<'hir> {
2632 /// A foreign function.
2633 Fn(&'hir FnDecl<'hir>, &'hir [Ident], Generics<'hir>),
2634 /// A foreign static item (`static ext: u8`).
2635 Static(&'hir Ty<'hir>, Mutability),
2640 /// A variable captured by a closure.
2641 #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)]
2643 // First span where it is accessed (there can be multiple).
2647 pub type CaptureModeMap = NodeMap<CaptureBy>;
2649 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2650 // has length > 0 if the trait is found through an chain of imports, starting with the
2651 // import/use statement in the scope where the trait is used.
2652 #[derive(Encodable, Decodable, Clone, Debug)]
2653 pub struct TraitCandidate {
2655 pub import_ids: SmallVec<[LocalDefId; 1]>,
2658 #[derive(Copy, Clone, Debug, HashStable_Generic)]
2659 pub enum Node<'hir> {
2660 Param(&'hir Param<'hir>),
2661 Item(&'hir Item<'hir>),
2662 ForeignItem(&'hir ForeignItem<'hir>),
2663 TraitItem(&'hir TraitItem<'hir>),
2664 ImplItem(&'hir ImplItem<'hir>),
2665 Variant(&'hir Variant<'hir>),
2666 Field(&'hir StructField<'hir>),
2667 AnonConst(&'hir AnonConst),
2668 Expr(&'hir Expr<'hir>),
2669 Stmt(&'hir Stmt<'hir>),
2670 PathSegment(&'hir PathSegment<'hir>),
2672 TraitRef(&'hir TraitRef<'hir>),
2673 Binding(&'hir Pat<'hir>),
2674 Pat(&'hir Pat<'hir>),
2675 Arm(&'hir Arm<'hir>),
2676 Block(&'hir Block<'hir>),
2677 Local(&'hir Local<'hir>),
2678 MacroDef(&'hir MacroDef<'hir>),
2680 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
2681 /// with synthesized constructors.
2682 Ctor(&'hir VariantData<'hir>),
2684 Lifetime(&'hir Lifetime),
2685 GenericParam(&'hir GenericParam<'hir>),
2686 Visibility(&'hir Visibility<'hir>),
2688 Crate(&'hir CrateItem<'hir>),
2691 impl<'hir> Node<'hir> {
2692 pub fn ident(&self) -> Option<Ident> {
2694 Node::TraitItem(TraitItem { ident, .. })
2695 | Node::ImplItem(ImplItem { ident, .. })
2696 | Node::ForeignItem(ForeignItem { ident, .. })
2697 | Node::Item(Item { ident, .. }) => Some(*ident),
2702 pub fn fn_decl(&self) -> Option<&FnDecl<'hir>> {
2704 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
2705 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
2706 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
2707 Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
2714 pub fn body_id(&self) -> Option<BodyId> {
2716 Node::TraitItem(TraitItem {
2717 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
2720 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
2721 | Node::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
2726 pub fn generics(&self) -> Option<&'hir Generics<'hir>> {
2728 Node::TraitItem(TraitItem { generics, .. })
2729 | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
2730 Node::Item(item) => item.kind.generics(),
2735 pub fn hir_id(&self) -> Option<HirId> {
2737 Node::Item(Item { hir_id, .. })
2738 | Node::ForeignItem(ForeignItem { hir_id, .. })
2739 | Node::TraitItem(TraitItem { hir_id, .. })
2740 | Node::ImplItem(ImplItem { hir_id, .. })
2741 | Node::Field(StructField { hir_id, .. })
2742 | Node::AnonConst(AnonConst { hir_id, .. })
2743 | Node::Expr(Expr { hir_id, .. })
2744 | Node::Stmt(Stmt { hir_id, .. })
2745 | Node::Ty(Ty { hir_id, .. })
2746 | Node::Binding(Pat { hir_id, .. })
2747 | Node::Pat(Pat { hir_id, .. })
2748 | Node::Arm(Arm { hir_id, .. })
2749 | Node::Block(Block { hir_id, .. })
2750 | Node::Local(Local { hir_id, .. })
2751 | Node::MacroDef(MacroDef { hir_id, .. })
2752 | Node::Lifetime(Lifetime { hir_id, .. })
2753 | Node::Param(Param { hir_id, .. })
2754 | Node::GenericParam(GenericParam { hir_id, .. }) => Some(*hir_id),
2755 Node::TraitRef(TraitRef { hir_ref_id, .. }) => Some(*hir_ref_id),
2756 Node::PathSegment(PathSegment { hir_id, .. }) => *hir_id,
2757 Node::Variant(Variant { id, .. }) => Some(*id),
2758 Node::Ctor(variant) => variant.ctor_hir_id(),
2759 Node::Crate(_) | Node::Visibility(_) => None,