1 use crate::def::{DefKind, Namespace, Res};
2 use crate::def_id::DefId;
3 crate use crate::hir_id::HirId;
4 use crate::itemlikevisit;
7 crate use BlockCheckMode::*;
9 crate use UnsafeSource::*;
11 use rustc_ast::ast::{self, AsmDialect, CrateSugar, Ident, Name};
12 use rustc_ast::ast::{AttrVec, Attribute, FloatTy, IntTy, Label, LitKind, StrStyle, UintTy};
13 pub use rustc_ast::ast::{BorrowKind, ImplPolarity, IsAuto};
14 pub use rustc_ast::ast::{CaptureBy, Movability, Mutability};
15 use rustc_ast::node_id::NodeMap;
16 use rustc_ast::tokenstream::TokenStream;
17 use rustc_ast::util::parser::ExprPrecedence;
18 use rustc_data_structures::fx::FxHashSet;
19 use rustc_data_structures::sync::{par_for_each_in, Send, Sync};
20 use rustc_errors::FatalError;
21 use rustc_macros::HashStable_Generic;
22 use rustc_span::source_map::{SourceMap, Spanned};
23 use rustc_span::symbol::{kw, sym, Symbol};
24 use rustc_span::{MultiSpan, Span, DUMMY_SP};
25 use rustc_target::spec::abi::Abi;
27 use smallvec::SmallVec;
28 use std::collections::{BTreeMap, BTreeSet};
31 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, HashStable_Generic)]
36 /// Either "`'a`", referring to a named lifetime definition,
37 /// or "``" (i.e., `kw::Invalid`), for elision placeholders.
39 /// HIR lowering inserts these placeholders in type paths that
40 /// refer to type definitions needing lifetime parameters,
41 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
42 pub name: LifetimeName,
45 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
46 #[derive(HashStable_Generic)]
48 /// Some user-given name like `T` or `'x`.
51 /// Synthetic name generated when user elided a lifetime in an impl header.
53 /// E.g., the lifetimes in cases like these:
56 /// impl Foo<'_> for u32
58 /// in that case, we rewrite to
60 /// impl<'f> Foo for &'f u32
61 /// impl<'f> Foo<'f> for u32
63 /// where `'f` is something like `Fresh(0)`. The indices are
64 /// unique per impl, but not necessarily continuous.
67 /// Indicates an illegal name was given and an error has been
68 /// reported (so we should squelch other derived errors). Occurs
69 /// when, e.g., `'_` is used in the wrong place.
74 pub fn ident(&self) -> Ident {
76 ParamName::Plain(ident) => ident,
77 ParamName::Fresh(_) | ParamName::Error => {
78 Ident::with_dummy_span(kw::UnderscoreLifetime)
83 pub fn modern(&self) -> ParamName {
85 ParamName::Plain(ident) => ParamName::Plain(ident.modern()),
86 param_name => param_name,
91 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
92 #[derive(HashStable_Generic)]
93 pub enum LifetimeName {
94 /// User-given names or fresh (synthetic) names.
97 /// User wrote nothing (e.g., the lifetime in `&u32`).
100 /// Implicit lifetime in a context like `dyn Foo`. This is
101 /// distinguished from implicit lifetimes elsewhere because the
102 /// lifetime that they default to must appear elsewhere within the
103 /// enclosing type. This means that, in an `impl Trait` context, we
104 /// don't have to create a parameter for them. That is, `impl
105 /// Trait<Item = &u32>` expands to an opaque type like `type
106 /// Foo<'a> = impl Trait<Item = &'a u32>`, but `impl Trait<item =
107 /// dyn Bar>` expands to `type Foo = impl Trait<Item = dyn Bar +
108 /// 'static>`. The latter uses `ImplicitObjectLifetimeDefault` so
109 /// that surrounding code knows not to create a lifetime
111 ImplicitObjectLifetimeDefault,
113 /// Indicates an error during lowering (usually `'_` in wrong place)
114 /// that was already reported.
117 /// User wrote specifies `'_`.
120 /// User wrote `'static`.
125 pub fn ident(&self) -> Ident {
127 LifetimeName::ImplicitObjectLifetimeDefault
128 | LifetimeName::Implicit
129 | LifetimeName::Error => Ident::invalid(),
130 LifetimeName::Underscore => Ident::with_dummy_span(kw::UnderscoreLifetime),
131 LifetimeName::Static => Ident::with_dummy_span(kw::StaticLifetime),
132 LifetimeName::Param(param_name) => param_name.ident(),
136 pub fn is_elided(&self) -> bool {
138 LifetimeName::ImplicitObjectLifetimeDefault
139 | LifetimeName::Implicit
140 | LifetimeName::Underscore => true,
142 // It might seem surprising that `Fresh(_)` counts as
143 // *not* elided -- but this is because, as far as the code
144 // in the compiler is concerned -- `Fresh(_)` variants act
145 // equivalently to "some fresh name". They correspond to
146 // early-bound regions on an impl, in other words.
147 LifetimeName::Error | LifetimeName::Param(_) | LifetimeName::Static => false,
151 fn is_static(&self) -> bool {
152 self == &LifetimeName::Static
155 pub fn modern(&self) -> LifetimeName {
157 LifetimeName::Param(param_name) => LifetimeName::Param(param_name.modern()),
158 lifetime_name => lifetime_name,
163 impl fmt::Display for Lifetime {
164 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
165 self.name.ident().fmt(f)
169 impl fmt::Debug for Lifetime {
170 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
175 print::to_string(print::NO_ANN, |s| s.print_lifetime(self))
181 pub fn is_elided(&self) -> bool {
182 self.name.is_elided()
185 pub fn is_static(&self) -> bool {
186 self.name.is_static()
190 /// A `Path` is essentially Rust's notion of a name; for instance,
191 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
192 /// along with a bunch of supporting information.
193 #[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
194 pub struct Path<'hir> {
196 /// The resolution for the path.
198 /// The segments in the path: the things separated by `::`.
199 pub segments: &'hir [PathSegment<'hir>],
203 pub fn is_global(&self) -> bool {
204 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
208 impl fmt::Debug for Path<'_> {
209 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
210 write!(f, "path({})", self)
214 impl fmt::Display for Path<'_> {
215 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
216 write!(f, "{}", print::to_string(print::NO_ANN, |s| s.print_path(self, false)))
220 /// A segment of a path: an identifier, an optional lifetime, and a set of
222 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
223 pub struct PathSegment<'hir> {
224 /// The identifier portion of this path segment.
225 #[stable_hasher(project(name))]
227 // `id` and `res` are optional. We currently only use these in save-analysis,
228 // any path segments without these will not have save-analysis info and
229 // therefore will not have 'jump to def' in IDEs, but otherwise will not be
230 // affected. (In general, we don't bother to get the defs for synthesized
231 // segments, only for segments which have come from the AST).
232 pub hir_id: Option<HirId>,
233 pub res: Option<Res>,
235 /// Type/lifetime parameters attached to this path. They come in
236 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
237 /// this is more than just simple syntactic sugar; the use of
238 /// parens affects the region binding rules, so we preserve the
240 pub args: Option<&'hir GenericArgs<'hir>>,
242 /// Whether to infer remaining type parameters, if any.
243 /// This only applies to expression and pattern paths, and
244 /// out of those only the segments with no type parameters
245 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
246 pub infer_args: bool,
249 impl<'hir> PathSegment<'hir> {
250 /// Converts an identifier to the corresponding segment.
251 pub fn from_ident(ident: Ident) -> PathSegment<'hir> {
252 PathSegment { ident, hir_id: None, res: None, infer_args: true, args: None }
255 pub fn generic_args(&self) -> &GenericArgs<'hir> {
256 if let Some(ref args) = self.args {
259 const DUMMY: &GenericArgs<'_> = &GenericArgs::none();
265 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
266 pub struct ConstArg {
267 pub value: AnonConst,
271 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
272 pub enum GenericArg<'hir> {
278 impl GenericArg<'_> {
279 pub fn span(&self) -> Span {
281 GenericArg::Lifetime(l) => l.span,
282 GenericArg::Type(t) => t.span,
283 GenericArg::Const(c) => c.span,
287 pub fn id(&self) -> HirId {
289 GenericArg::Lifetime(l) => l.hir_id,
290 GenericArg::Type(t) => t.hir_id,
291 GenericArg::Const(c) => c.value.hir_id,
295 pub fn is_const(&self) -> bool {
297 GenericArg::Const(_) => true,
302 pub fn descr(&self) -> &'static str {
304 GenericArg::Lifetime(_) => "lifetime",
305 GenericArg::Type(_) => "type",
306 GenericArg::Const(_) => "constant",
311 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
312 pub struct GenericArgs<'hir> {
313 /// The generic arguments for this path segment.
314 pub args: &'hir [GenericArg<'hir>],
315 /// Bindings (equality constraints) on associated types, if present.
316 /// E.g., `Foo<A = Bar>`.
317 pub bindings: &'hir [TypeBinding<'hir>],
318 /// Were arguments written in parenthesized form `Fn(T) -> U`?
319 /// This is required mostly for pretty-printing and diagnostics,
320 /// but also for changing lifetime elision rules to be "function-like".
321 pub parenthesized: bool,
324 impl GenericArgs<'_> {
325 pub const fn none() -> Self {
326 Self { args: &[], bindings: &[], parenthesized: false }
329 pub fn is_empty(&self) -> bool {
330 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
333 pub fn inputs(&self) -> &[Ty<'_>] {
334 if self.parenthesized {
335 for arg in self.args {
337 GenericArg::Lifetime(_) => {}
338 GenericArg::Type(ref ty) => {
339 if let TyKind::Tup(ref tys) = ty.kind {
344 GenericArg::Const(_) => {}
348 panic!("GenericArgs::inputs: not a `Fn(T) -> U`");
351 pub fn own_counts(&self) -> GenericParamCount {
352 // We could cache this as a property of `GenericParamCount`, but
353 // the aim is to refactor this away entirely eventually and the
354 // presence of this method will be a constant reminder.
355 let mut own_counts: GenericParamCount = Default::default();
357 for arg in self.args {
359 GenericArg::Lifetime(_) => own_counts.lifetimes += 1,
360 GenericArg::Type(_) => own_counts.types += 1,
361 GenericArg::Const(_) => own_counts.consts += 1,
369 /// A modifier on a bound, currently this is only used for `?Sized`, where the
370 /// modifier is `Maybe`. Negative bounds should also be handled here.
371 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
372 #[derive(HashStable_Generic)]
373 pub enum TraitBoundModifier {
379 /// The AST represents all type param bounds as types.
380 /// `typeck::collect::compute_bounds` matches these against
381 /// the "special" built-in traits (see `middle::lang_items`) and
382 /// detects `Copy`, `Send` and `Sync`.
383 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
384 pub enum GenericBound<'hir> {
385 Trait(PolyTraitRef<'hir>, TraitBoundModifier),
389 impl GenericBound<'_> {
390 pub fn trait_def_id(&self) -> Option<DefId> {
392 GenericBound::Trait(data, _) => Some(data.trait_ref.trait_def_id()),
397 pub fn span(&self) -> Span {
399 &GenericBound::Trait(ref t, ..) => t.span,
400 &GenericBound::Outlives(ref l) => l.span,
405 pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
407 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
408 pub enum LifetimeParamKind {
409 // Indicates that the lifetime definition was explicitly declared (e.g., in
410 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
413 // Indicates that the lifetime definition was synthetically added
414 // as a result of an in-band lifetime usage (e.g., in
415 // `fn foo(x: &'a u8) -> &'a u8 { x }`).
418 // Indication that the lifetime was elided (e.g., in both cases in
419 // `fn foo(x: &u8) -> &'_ u8 { x }`).
422 // Indication that the lifetime name was somehow in error.
426 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
427 pub enum GenericParamKind<'hir> {
428 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
430 kind: LifetimeParamKind,
433 default: Option<&'hir Ty<'hir>>,
434 synthetic: Option<SyntheticTyParamKind>,
441 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
442 pub struct GenericParam<'hir> {
445 pub attrs: &'hir [Attribute],
446 pub bounds: GenericBounds<'hir>,
448 pub pure_wrt_drop: bool,
449 pub kind: GenericParamKind<'hir>,
452 impl GenericParam<'hir> {
453 pub fn bounds_span(&self) -> Option<Span> {
454 self.bounds.iter().fold(None, |span, bound| {
455 let span = span.map(|s| s.to(bound.span())).unwrap_or_else(|| bound.span());
463 pub struct GenericParamCount {
464 pub lifetimes: usize,
469 /// Represents lifetimes and type parameters attached to a declaration
470 /// of a function, enum, trait, etc.
471 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
472 pub struct Generics<'hir> {
473 pub params: &'hir [GenericParam<'hir>],
474 pub where_clause: WhereClause<'hir>,
478 impl Generics<'hir> {
479 pub const fn empty() -> Generics<'hir> {
482 where_clause: WhereClause { predicates: &[], span: DUMMY_SP },
487 pub fn own_counts(&self) -> GenericParamCount {
488 // We could cache this as a property of `GenericParamCount`, but
489 // the aim is to refactor this away entirely eventually and the
490 // presence of this method will be a constant reminder.
491 let mut own_counts: GenericParamCount = Default::default();
493 for param in self.params {
495 GenericParamKind::Lifetime { .. } => own_counts.lifetimes += 1,
496 GenericParamKind::Type { .. } => own_counts.types += 1,
497 GenericParamKind::Const { .. } => own_counts.consts += 1,
504 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'_>> {
505 for param in self.params {
506 if name == param.name.ident().name {
513 pub fn spans(&self) -> MultiSpan {
514 if self.params.is_empty() {
517 self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
522 /// Synthetic type parameters are converted to another form during lowering; this allows
523 /// us to track the original form they had, and is useful for error messages.
524 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
525 #[derive(HashStable_Generic)]
526 pub enum SyntheticTyParamKind {
530 /// A where-clause in a definition.
531 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
532 pub struct WhereClause<'hir> {
533 pub predicates: &'hir [WherePredicate<'hir>],
534 // Only valid if predicates aren't empty.
538 impl WhereClause<'_> {
539 pub fn span(&self) -> Option<Span> {
540 if self.predicates.is_empty() { None } else { Some(self.span) }
543 /// The `WhereClause` under normal circumstances points at either the predicates or the empty
544 /// space where the `where` clause should be. Only of use for diagnostic suggestions.
545 pub fn span_for_predicates_or_empty_place(&self) -> Span {
550 /// A single predicate in a where-clause.
551 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
552 pub enum WherePredicate<'hir> {
553 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
554 BoundPredicate(WhereBoundPredicate<'hir>),
555 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
556 RegionPredicate(WhereRegionPredicate<'hir>),
557 /// An equality predicate (unsupported).
558 EqPredicate(WhereEqPredicate<'hir>),
561 impl WherePredicate<'_> {
562 pub fn span(&self) -> Span {
564 &WherePredicate::BoundPredicate(ref p) => p.span,
565 &WherePredicate::RegionPredicate(ref p) => p.span,
566 &WherePredicate::EqPredicate(ref p) => p.span,
571 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
572 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
573 pub struct WhereBoundPredicate<'hir> {
575 /// Any generics from a `for` binding.
576 pub bound_generic_params: &'hir [GenericParam<'hir>],
577 /// The type being bounded.
578 pub bounded_ty: &'hir Ty<'hir>,
579 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
580 pub bounds: GenericBounds<'hir>,
583 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
584 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
585 pub struct WhereRegionPredicate<'hir> {
587 pub lifetime: Lifetime,
588 pub bounds: GenericBounds<'hir>,
591 /// An equality predicate (e.g., `T = int`); currently unsupported.
592 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
593 pub struct WhereEqPredicate<'hir> {
596 pub lhs_ty: &'hir Ty<'hir>,
597 pub rhs_ty: &'hir Ty<'hir>,
600 #[derive(RustcEncodable, RustcDecodable, Debug)]
601 pub struct ModuleItems {
602 // Use BTreeSets here so items are in the same order as in the
603 // list of all items in Crate
604 pub items: BTreeSet<HirId>,
605 pub trait_items: BTreeSet<TraitItemId>,
606 pub impl_items: BTreeSet<ImplItemId>,
609 /// The top-level data structure that stores the entire contents of
610 /// the crate currently being compiled.
612 /// For more details, see the [rustc guide].
614 /// [rustc guide]: https://rust-lang.github.io/rustc-guide/hir.html
615 #[derive(RustcEncodable, RustcDecodable, Debug)]
616 pub struct Crate<'hir> {
617 pub module: Mod<'hir>,
618 pub attrs: &'hir [Attribute],
620 pub exported_macros: &'hir [MacroDef<'hir>],
621 // Attributes from non-exported macros, kept only for collecting the library feature list.
622 pub non_exported_macro_attrs: &'hir [Attribute],
624 // N.B., we use a `BTreeMap` here so that `visit_all_items` iterates
625 // over the ids in increasing order. In principle it should not
626 // matter what order we visit things in, but in *practice* it
627 // does, because it can affect the order in which errors are
628 // detected, which in turn can make compile-fail tests yield
629 // slightly different results.
630 pub items: BTreeMap<HirId, Item<'hir>>,
632 pub trait_items: BTreeMap<TraitItemId, TraitItem<'hir>>,
633 pub impl_items: BTreeMap<ImplItemId, ImplItem<'hir>>,
634 pub bodies: BTreeMap<BodyId, Body<'hir>>,
635 pub trait_impls: BTreeMap<DefId, Vec<HirId>>,
637 /// A list of the body ids written out in the order in which they
638 /// appear in the crate. If you're going to process all the bodies
639 /// in the crate, you should iterate over this list rather than the keys
641 pub body_ids: Vec<BodyId>,
643 /// A list of modules written out in the order in which they
644 /// appear in the crate. This includes the main crate module.
645 pub modules: BTreeMap<HirId, ModuleItems>,
646 /// A list of proc macro HirIds, written out in the order in which
647 /// they are declared in the static array generated by proc_macro_harness.
648 pub proc_macros: Vec<HirId>,
652 pub fn item(&self, id: HirId) -> &Item<'hir> {
656 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem<'hir> {
657 &self.trait_items[&id]
660 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem<'hir> {
661 &self.impl_items[&id]
664 pub fn body(&self, id: BodyId) -> &Body<'hir> {
670 /// Visits all items in the crate in some deterministic (but
671 /// unspecified) order. If you just need to process every item,
672 /// but don't care about nesting, this method is the best choice.
674 /// If you do care about nesting -- usually because your algorithm
675 /// follows lexical scoping rules -- then you want a different
676 /// approach. You should override `visit_nested_item` in your
677 /// visitor and then call `intravisit::walk_crate` instead.
678 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
680 V: itemlikevisit::ItemLikeVisitor<'hir>,
682 for item in self.items.values() {
683 visitor.visit_item(item);
686 for trait_item in self.trait_items.values() {
687 visitor.visit_trait_item(trait_item);
690 for impl_item in self.impl_items.values() {
691 visitor.visit_impl_item(impl_item);
695 /// A parallel version of `visit_all_item_likes`.
696 pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
698 V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send,
702 par_for_each_in(&self.items, |(_, item)| {
703 visitor.visit_item(item);
707 par_for_each_in(&self.trait_items, |(_, trait_item)| {
708 visitor.visit_trait_item(trait_item);
712 par_for_each_in(&self.impl_items, |(_, impl_item)| {
713 visitor.visit_impl_item(impl_item);
720 /// A macro definition, in this crate or imported from another.
722 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
723 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
724 pub struct MacroDef<'hir> {
726 pub vis: Visibility<'hir>,
727 pub attrs: &'hir [Attribute],
730 pub body: TokenStream,
734 /// A block of statements `{ .. }`, which may have a label (in this case the
735 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
736 /// the `rules` being anything but `DefaultBlock`.
737 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
738 pub struct Block<'hir> {
739 /// Statements in a block.
740 pub stmts: &'hir [Stmt<'hir>],
741 /// An expression at the end of the block
742 /// without a semicolon, if any.
743 pub expr: Option<&'hir Expr<'hir>>,
744 #[stable_hasher(ignore)]
746 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
747 pub rules: BlockCheckMode,
749 /// If true, then there may exist `break 'a` values that aim to
750 /// break out of this block early.
751 /// Used by `'label: {}` blocks and by `try {}` blocks.
752 pub targeted_by_break: bool,
755 #[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
756 pub struct Pat<'hir> {
757 #[stable_hasher(ignore)]
759 pub kind: PatKind<'hir>,
763 impl fmt::Debug for Pat<'_> {
764 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
769 print::to_string(print::NO_ANN, |s| s.print_pat(self))
775 // FIXME(#19596) this is a workaround, but there should be a better way
776 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'_>) -> bool) -> bool {
783 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
784 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
785 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
786 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
787 Slice(before, slice, after) => {
788 before.iter().chain(slice.iter()).chain(after.iter()).all(|p| p.walk_short_(it))
793 /// Walk the pattern in left-to-right order,
794 /// short circuiting (with `.all(..)`) if `false` is returned.
796 /// Note that when visiting e.g. `Tuple(ps)`,
797 /// if visiting `ps[0]` returns `false`,
798 /// then `ps[1]` will not be visited.
799 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'_>) -> bool) -> bool {
800 self.walk_short_(&mut it)
803 // FIXME(#19596) this is a workaround, but there should be a better way
804 fn walk_(&self, it: &mut impl FnMut(&Pat<'_>) -> bool) {
811 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
812 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
813 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
814 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
815 Slice(before, slice, after) => {
816 before.iter().chain(slice.iter()).chain(after.iter()).for_each(|p| p.walk_(it))
821 /// Walk the pattern in left-to-right order.
823 /// If `it(pat)` returns `false`, the children are not visited.
824 pub fn walk(&self, mut it: impl FnMut(&Pat<'_>) -> bool) {
828 /// Walk the pattern in left-to-right order.
830 /// If you always want to recurse, prefer this method over `walk`.
831 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
839 /// A single field in a struct pattern.
841 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
842 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
843 /// except `is_shorthand` is true.
844 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
845 pub struct FieldPat<'hir> {
846 #[stable_hasher(ignore)]
848 /// The identifier for the field.
849 #[stable_hasher(project(name))]
851 /// The pattern the field is destructured to.
852 pub pat: &'hir Pat<'hir>,
853 pub is_shorthand: bool,
857 /// Explicit binding annotations given in the HIR for a binding. Note
858 /// that this is not the final binding *mode* that we infer after type
860 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
861 pub enum BindingAnnotation {
862 /// No binding annotation given: this means that the final binding mode
863 /// will depend on whether we have skipped through a `&` reference
864 /// when matching. For example, the `x` in `Some(x)` will have binding
865 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
866 /// ultimately be inferred to be by-reference.
868 /// Note that implicit reference skipping is not implemented yet (#42640).
871 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
874 /// Annotated as `ref`, like `ref x`
877 /// Annotated as `ref mut x`.
881 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
887 impl fmt::Display for RangeEnd {
888 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
889 f.write_str(match self {
890 RangeEnd::Included => "..=",
891 RangeEnd::Excluded => "..",
896 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
897 pub enum PatKind<'hir> {
898 /// Represents a wildcard pattern (i.e., `_`).
901 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
902 /// The `HirId` is the canonical ID for the variable being bound,
903 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
904 /// which is the pattern ID of the first `x`.
905 Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
907 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
908 /// The `bool` is `true` in the presence of a `..`.
909 Struct(QPath<'hir>, &'hir [FieldPat<'hir>], bool),
911 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
912 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
913 /// `0 <= position <= subpats.len()`
914 TupleStruct(QPath<'hir>, &'hir [&'hir Pat<'hir>], Option<usize>),
916 /// An or-pattern `A | B | C`.
917 /// Invariant: `pats.len() >= 2`.
918 Or(&'hir [&'hir Pat<'hir>]),
920 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
923 /// A tuple pattern (e.g., `(a, b)`).
924 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
925 /// `0 <= position <= subpats.len()`
926 Tuple(&'hir [&'hir Pat<'hir>], Option<usize>),
929 Box(&'hir Pat<'hir>),
931 /// A reference pattern (e.g., `&mut (a, b)`).
932 Ref(&'hir Pat<'hir>, Mutability),
935 Lit(&'hir Expr<'hir>),
937 /// A range pattern (e.g., `1..=2` or `1..2`).
938 Range(Option<&'hir Expr<'hir>>, Option<&'hir Expr<'hir>>, RangeEnd),
940 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
942 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
943 /// If `slice` exists, then `after` can be non-empty.
945 /// The representation for e.g., `[a, b, .., c, d]` is:
947 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
949 Slice(&'hir [&'hir Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [&'hir Pat<'hir>]),
952 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
954 /// The `+` operator (addition).
956 /// The `-` operator (subtraction).
958 /// The `*` operator (multiplication).
960 /// The `/` operator (division).
962 /// The `%` operator (modulus).
964 /// The `&&` operator (logical and).
966 /// The `||` operator (logical or).
968 /// The `^` operator (bitwise xor).
970 /// The `&` operator (bitwise and).
972 /// The `|` operator (bitwise or).
974 /// The `<<` operator (shift left).
976 /// The `>>` operator (shift right).
978 /// The `==` operator (equality).
980 /// The `<` operator (less than).
982 /// The `<=` operator (less than or equal to).
984 /// The `!=` operator (not equal to).
986 /// The `>=` operator (greater than or equal to).
988 /// The `>` operator (greater than).
993 pub fn as_str(self) -> &'static str {
995 BinOpKind::Add => "+",
996 BinOpKind::Sub => "-",
997 BinOpKind::Mul => "*",
998 BinOpKind::Div => "/",
999 BinOpKind::Rem => "%",
1000 BinOpKind::And => "&&",
1001 BinOpKind::Or => "||",
1002 BinOpKind::BitXor => "^",
1003 BinOpKind::BitAnd => "&",
1004 BinOpKind::BitOr => "|",
1005 BinOpKind::Shl => "<<",
1006 BinOpKind::Shr => ">>",
1007 BinOpKind::Eq => "==",
1008 BinOpKind::Lt => "<",
1009 BinOpKind::Le => "<=",
1010 BinOpKind::Ne => "!=",
1011 BinOpKind::Ge => ">=",
1012 BinOpKind::Gt => ">",
1016 pub fn is_lazy(self) -> bool {
1018 BinOpKind::And | BinOpKind::Or => true,
1023 pub fn is_shift(self) -> bool {
1025 BinOpKind::Shl | BinOpKind::Shr => true,
1030 pub fn is_comparison(self) -> bool {
1037 | BinOpKind::Ge => true,
1049 | BinOpKind::Shr => false,
1053 /// Returns `true` if the binary operator takes its arguments by value.
1054 pub fn is_by_value(self) -> bool {
1055 !self.is_comparison()
1059 impl Into<ast::BinOpKind> for BinOpKind {
1060 fn into(self) -> ast::BinOpKind {
1062 BinOpKind::Add => ast::BinOpKind::Add,
1063 BinOpKind::Sub => ast::BinOpKind::Sub,
1064 BinOpKind::Mul => ast::BinOpKind::Mul,
1065 BinOpKind::Div => ast::BinOpKind::Div,
1066 BinOpKind::Rem => ast::BinOpKind::Rem,
1067 BinOpKind::And => ast::BinOpKind::And,
1068 BinOpKind::Or => ast::BinOpKind::Or,
1069 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1070 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1071 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1072 BinOpKind::Shl => ast::BinOpKind::Shl,
1073 BinOpKind::Shr => ast::BinOpKind::Shr,
1074 BinOpKind::Eq => ast::BinOpKind::Eq,
1075 BinOpKind::Lt => ast::BinOpKind::Lt,
1076 BinOpKind::Le => ast::BinOpKind::Le,
1077 BinOpKind::Ne => ast::BinOpKind::Ne,
1078 BinOpKind::Ge => ast::BinOpKind::Ge,
1079 BinOpKind::Gt => ast::BinOpKind::Gt,
1084 pub type BinOp = Spanned<BinOpKind>;
1086 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1088 /// The `*` operator (deferencing).
1090 /// The `!` operator (logical negation).
1092 /// The `-` operator (negation).
1097 pub fn as_str(self) -> &'static str {
1099 Self::UnDeref => "*",
1105 /// Returns `true` if the unary operator takes its argument by value.
1106 pub fn is_by_value(self) -> bool {
1108 Self::UnNeg | Self::UnNot => true,
1115 #[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
1116 pub struct Stmt<'hir> {
1118 pub kind: StmtKind<'hir>,
1122 impl fmt::Debug for Stmt<'_> {
1123 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1128 print::to_string(print::NO_ANN, |s| s.print_stmt(self))
1133 /// The contents of a statement.
1134 #[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
1135 pub enum StmtKind<'hir> {
1136 /// A local (`let`) binding.
1137 Local(&'hir Local<'hir>),
1139 /// An item binding.
1142 /// An expression without a trailing semi-colon (must have unit type).
1143 Expr(&'hir Expr<'hir>),
1145 /// An expression with a trailing semi-colon (may have any type).
1146 Semi(&'hir Expr<'hir>),
1149 impl StmtKind<'hir> {
1150 pub fn attrs(&self) -> &'hir [Attribute] {
1152 StmtKind::Local(ref l) => &l.attrs,
1153 StmtKind::Item(_) => &[],
1154 StmtKind::Expr(ref e) | StmtKind::Semi(ref e) => &e.attrs,
1159 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1160 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1161 pub struct Local<'hir> {
1162 pub pat: &'hir Pat<'hir>,
1163 /// Type annotation, if any (otherwise the type will be inferred).
1164 pub ty: Option<&'hir Ty<'hir>>,
1165 /// Initializer expression to set the value, if any.
1166 pub init: Option<&'hir Expr<'hir>>,
1170 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1171 /// desugaring. Otherwise will be `Normal`.
1172 pub source: LocalSource,
1175 /// Represents a single arm of a `match` expression, e.g.
1176 /// `<pat> (if <guard>) => <body>`.
1177 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1178 pub struct Arm<'hir> {
1179 #[stable_hasher(ignore)]
1182 pub attrs: &'hir [Attribute],
1183 /// If this pattern and the optional guard matches, then `body` is evaluated.
1184 pub pat: &'hir Pat<'hir>,
1185 /// Optional guard clause.
1186 pub guard: Option<Guard<'hir>>,
1187 /// The expression the arm evaluates to if this arm matches.
1188 pub body: &'hir Expr<'hir>,
1191 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1192 pub enum Guard<'hir> {
1193 If(&'hir Expr<'hir>),
1196 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1197 pub struct Field<'hir> {
1198 #[stable_hasher(ignore)]
1201 pub expr: &'hir Expr<'hir>,
1203 pub is_shorthand: bool,
1206 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1207 pub enum BlockCheckMode {
1209 UnsafeBlock(UnsafeSource),
1210 PushUnsafeBlock(UnsafeSource),
1211 PopUnsafeBlock(UnsafeSource),
1214 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1215 pub enum UnsafeSource {
1220 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1225 /// The body of a function, closure, or constant value. In the case of
1226 /// a function, the body contains not only the function body itself
1227 /// (which is an expression), but also the argument patterns, since
1228 /// those are something that the caller doesn't really care about.
1233 /// fn foo((x, y): (u32, u32)) -> u32 {
1238 /// Here, the `Body` associated with `foo()` would contain:
1240 /// - an `params` array containing the `(x, y)` pattern
1241 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1242 /// - `generator_kind` would be `None`
1244 /// All bodies have an **owner**, which can be accessed via the HIR
1245 /// map using `body_owner_def_id()`.
1246 #[derive(RustcEncodable, RustcDecodable, Debug)]
1247 pub struct Body<'hir> {
1248 pub params: &'hir [Param<'hir>],
1249 pub value: Expr<'hir>,
1250 pub generator_kind: Option<GeneratorKind>,
1254 pub fn id(&self) -> BodyId {
1255 BodyId { hir_id: self.value.hir_id }
1258 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1263 /// The type of source expression that caused this generator to be created.
1264 #[derive(Clone, PartialEq, Eq, HashStable_Generic, RustcEncodable, RustcDecodable, Debug, Copy)]
1265 pub enum GeneratorKind {
1266 /// An explicit `async` block or the body of an async function.
1267 Async(AsyncGeneratorKind),
1269 /// A generator literal created via a `yield` inside a closure.
1273 impl fmt::Display for GeneratorKind {
1274 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1276 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1277 GeneratorKind::Gen => f.write_str("generator"),
1282 /// In the case of a generator created as part of an async construct,
1283 /// which kind of async construct caused it to be created?
1285 /// This helps error messages but is also used to drive coercions in
1286 /// type-checking (see #60424).
1287 #[derive(Clone, PartialEq, Eq, HashStable_Generic, RustcEncodable, RustcDecodable, Debug, Copy)]
1288 pub enum AsyncGeneratorKind {
1289 /// An explicit `async` block written by the user.
1292 /// An explicit `async` block written by the user.
1295 /// The `async` block generated as the body of an async function.
1299 impl fmt::Display for AsyncGeneratorKind {
1300 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1301 f.write_str(match self {
1302 AsyncGeneratorKind::Block => "`async` block",
1303 AsyncGeneratorKind::Closure => "`async` closure body",
1304 AsyncGeneratorKind::Fn => "`async fn` body",
1309 #[derive(Copy, Clone, Debug)]
1310 pub enum BodyOwnerKind {
1311 /// Functions and methods.
1317 /// Constants and associated constants.
1320 /// Initializer of a `static` item.
1324 impl BodyOwnerKind {
1325 pub fn is_fn_or_closure(self) -> bool {
1327 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1328 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1334 pub type Lit = Spanned<LitKind>;
1336 /// A constant (expression) that's not an item or associated item,
1337 /// but needs its own `DefId` for type-checking, const-eval, etc.
1338 /// These are usually found nested inside types (e.g., array lengths)
1339 /// or expressions (e.g., repeat counts), and also used to define
1340 /// explicit discriminant values for enum variants.
1341 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1342 pub struct AnonConst {
1348 #[derive(RustcEncodable, RustcDecodable)]
1349 pub struct Expr<'hir> {
1351 pub kind: ExprKind<'hir>,
1356 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1357 #[cfg(target_arch = "x86_64")]
1358 rustc_data_structures::static_assert_size!(Expr<'static>, 64);
1361 pub fn precedence(&self) -> ExprPrecedence {
1363 ExprKind::Box(_) => ExprPrecedence::Box,
1364 ExprKind::Array(_) => ExprPrecedence::Array,
1365 ExprKind::Call(..) => ExprPrecedence::Call,
1366 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1367 ExprKind::Tup(_) => ExprPrecedence::Tup,
1368 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1369 ExprKind::Unary(..) => ExprPrecedence::Unary,
1370 ExprKind::Lit(_) => ExprPrecedence::Lit,
1371 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1372 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1373 ExprKind::Loop(..) => ExprPrecedence::Loop,
1374 ExprKind::Match(..) => ExprPrecedence::Match,
1375 ExprKind::Closure(..) => ExprPrecedence::Closure,
1376 ExprKind::Block(..) => ExprPrecedence::Block,
1377 ExprKind::Assign(..) => ExprPrecedence::Assign,
1378 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1379 ExprKind::Field(..) => ExprPrecedence::Field,
1380 ExprKind::Index(..) => ExprPrecedence::Index,
1381 ExprKind::Path(..) => ExprPrecedence::Path,
1382 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1383 ExprKind::Break(..) => ExprPrecedence::Break,
1384 ExprKind::Continue(..) => ExprPrecedence::Continue,
1385 ExprKind::Ret(..) => ExprPrecedence::Ret,
1386 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1387 ExprKind::Struct(..) => ExprPrecedence::Struct,
1388 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1389 ExprKind::Yield(..) => ExprPrecedence::Yield,
1390 ExprKind::Err => ExprPrecedence::Err,
1394 // Whether this looks like a place expr, without checking for deref
1396 // This will return `true` in some potentially surprising cases such as
1397 // `CONSTANT.field`.
1398 pub fn is_syntactic_place_expr(&self) -> bool {
1399 self.is_place_expr(|_| true)
1402 // Whether this is a place expression.
1403 // `allow_projections_from` should return `true` if indexing a field or
1404 // index expression based on the given expression should be considered a
1405 // place expression.
1406 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1408 ExprKind::Path(QPath::Resolved(_, ref path)) => match path.res {
1409 Res::Local(..) | Res::Def(DefKind::Static, _) | Res::Err => true,
1413 // Type ascription inherits its place expression kind from its
1415 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1416 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1418 ExprKind::Unary(UnOp::UnDeref, _) => true,
1420 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1421 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1424 // Partially qualified paths in expressions can only legally
1425 // refer to associated items which are always rvalues.
1426 ExprKind::Path(QPath::TypeRelative(..))
1427 | ExprKind::Call(..)
1428 | ExprKind::MethodCall(..)
1429 | ExprKind::Struct(..)
1431 | ExprKind::Match(..)
1432 | ExprKind::Closure(..)
1433 | ExprKind::Block(..)
1434 | ExprKind::Repeat(..)
1435 | ExprKind::Array(..)
1436 | ExprKind::Break(..)
1437 | ExprKind::Continue(..)
1439 | ExprKind::Loop(..)
1440 | ExprKind::Assign(..)
1441 | ExprKind::InlineAsm(..)
1442 | ExprKind::AssignOp(..)
1444 | ExprKind::Unary(..)
1446 | ExprKind::AddrOf(..)
1447 | ExprKind::Binary(..)
1448 | ExprKind::Yield(..)
1449 | ExprKind::Cast(..)
1450 | ExprKind::DropTemps(..)
1451 | ExprKind::Err => false,
1455 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1456 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1457 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1458 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1459 /// beyond remembering to call this function before doing analysis on it.
1460 pub fn peel_drop_temps(&self) -> &Self {
1461 let mut expr = self;
1462 while let ExprKind::DropTemps(inner) = &expr.kind {
1469 impl fmt::Debug for Expr<'_> {
1470 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1475 print::to_string(print::NO_ANN, |s| s.print_expr(self))
1480 /// Checks if the specified expression is a built-in range literal.
1481 /// (See: `LoweringContext::lower_expr()`).
1483 /// FIXME(#60607): This function is a hack. If and when we have `QPath::Lang(...)`,
1484 /// we can use that instead as simpler, more reliable mechanism, as opposed to using `SourceMap`.
1485 pub fn is_range_literal(sm: &SourceMap, expr: &Expr<'_>) -> bool {
1486 // Returns whether the given path represents a (desugared) range,
1487 // either in std or core, i.e. has either a `::std::ops::Range` or
1488 // `::core::ops::Range` prefix.
1489 fn is_range_path(path: &Path<'_>) -> bool {
1490 let segs: Vec<_> = path.segments.iter().map(|seg| seg.ident.to_string()).collect();
1491 let segs: Vec<_> = segs.iter().map(|seg| &**seg).collect();
1493 // "{{root}}" is the equivalent of `::` prefix in `Path`.
1494 if let ["{{root}}", std_core, "ops", range] = segs.as_slice() {
1495 (*std_core == "std" || *std_core == "core") && range.starts_with("Range")
1501 // Check whether a span corresponding to a range expression is a
1502 // range literal, rather than an explicit struct or `new()` call.
1503 fn is_lit(sm: &SourceMap, span: &Span) -> bool {
1504 let end_point = sm.end_point(*span);
1506 if let Ok(end_string) = sm.span_to_snippet(end_point) {
1507 !(end_string.ends_with('}') || end_string.ends_with(')'))
1514 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1515 ExprKind::Struct(ref qpath, _, _) => {
1516 if let QPath::Resolved(None, ref path) = **qpath {
1517 return is_range_path(&path) && is_lit(sm, &expr.span);
1521 // `..` desugars to its struct path.
1522 ExprKind::Path(QPath::Resolved(None, ref path)) => {
1523 return is_range_path(&path) && is_lit(sm, &expr.span);
1526 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1527 ExprKind::Call(ref func, _) => {
1528 if let ExprKind::Path(QPath::TypeRelative(ref ty, ref segment)) = func.kind {
1529 if let TyKind::Path(QPath::Resolved(None, ref path)) = ty.kind {
1530 let new_call = segment.ident.name == sym::new;
1531 return is_range_path(&path) && is_lit(sm, &expr.span) && new_call;
1542 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1543 pub enum ExprKind<'hir> {
1544 /// A `box x` expression.
1545 Box(&'hir Expr<'hir>),
1546 /// An array (e.g., `[a, b, c, d]`).
1547 Array(&'hir [Expr<'hir>]),
1548 /// A function call.
1550 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1551 /// and the second field is the list of arguments.
1552 /// This also represents calling the constructor of
1553 /// tuple-like ADTs such as tuple structs and enum variants.
1554 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1555 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1557 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1558 /// (within the angle brackets).
1559 /// The first element of the vector of `Expr`s is the expression that evaluates
1560 /// to the object on which the method is being called on (the receiver),
1561 /// and the remaining elements are the rest of the arguments.
1562 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1563 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1565 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1566 /// the `hir_id` of the `MethodCall` node itself.
1568 /// [`type_dependent_def_id`]: ../ty/struct.TypeckTables.html#method.type_dependent_def_id
1569 MethodCall(&'hir PathSegment<'hir>, Span, &'hir [Expr<'hir>]),
1570 /// A tuple (e.g., `(a, b, c, d)`).
1571 Tup(&'hir [Expr<'hir>]),
1572 /// A binary operation (e.g., `a + b`, `a * b`).
1573 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1574 /// A unary operation (e.g., `!x`, `*x`).
1575 Unary(UnOp, &'hir Expr<'hir>),
1576 /// A literal (e.g., `1`, `"foo"`).
1578 /// A cast (e.g., `foo as f64`).
1579 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1580 /// A type reference (e.g., `Foo`).
1581 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1582 /// Wraps the expression in a terminating scope.
1583 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1585 /// This construct only exists to tweak the drop order in HIR lowering.
1586 /// An example of that is the desugaring of `for` loops.
1587 DropTemps(&'hir Expr<'hir>),
1588 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1590 /// I.e., `'label: loop { <block> }`.
1591 Loop(&'hir Block<'hir>, Option<Label>, LoopSource),
1592 /// A `match` block, with a source that indicates whether or not it is
1593 /// the result of a desugaring, and if so, which kind.
1594 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1595 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1597 /// The `Span` is the argument block `|...|`.
1599 /// This may also be a generator literal or an `async block` as indicated by the
1600 /// `Option<Movability>`.
1601 Closure(CaptureBy, &'hir FnDecl<'hir>, BodyId, Span, Option<Movability>),
1602 /// A block (e.g., `'label: { ... }`).
1603 Block(&'hir Block<'hir>, Option<Label>),
1605 /// An assignment (e.g., `a = foo()`).
1606 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1607 /// An assignment with an operator.
1610 AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1611 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1612 Field(&'hir Expr<'hir>, Ident),
1613 /// An indexing operation (`foo[2]`).
1614 Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1616 /// Path to a definition, possibly containing lifetime or type parameters.
1619 /// A referencing operation (i.e., `&a` or `&mut a`).
1620 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1621 /// A `break`, with an optional label to break.
1622 Break(Destination, Option<&'hir Expr<'hir>>),
1623 /// A `continue`, with an optional label.
1624 Continue(Destination),
1625 /// A `return`, with an optional value to be returned.
1626 Ret(Option<&'hir Expr<'hir>>),
1628 /// Inline assembly (from `asm!`), with its outputs and inputs.
1629 InlineAsm(&'hir InlineAsm<'hir>),
1631 /// A struct or struct-like variant literal expression.
1633 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1634 /// where `base` is the `Option<Expr>`.
1635 Struct(&'hir QPath<'hir>, &'hir [Field<'hir>], Option<&'hir Expr<'hir>>),
1637 /// An array literal constructed from one repeated element.
1639 /// E.g., `[1; 5]`. The first expression is the element
1640 /// to be repeated; the second is the number of times to repeat it.
1641 Repeat(&'hir Expr<'hir>, AnonConst),
1643 /// A suspension point for generators (i.e., `yield <expr>`).
1644 Yield(&'hir Expr<'hir>, YieldSource),
1646 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1650 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1652 /// To resolve the path to a `DefId`, call [`qpath_res`].
1654 /// [`qpath_res`]: ../ty/struct.TypeckTables.html#method.qpath_res
1655 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1656 pub enum QPath<'hir> {
1657 /// Path to a definition, optionally "fully-qualified" with a `Self`
1658 /// type, if the path points to an associated item in a trait.
1660 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1661 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1662 /// even though they both have the same two-segment `Clone::clone` `Path`.
1663 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
1665 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1666 /// Will be resolved by type-checking to an associated item.
1668 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1669 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1670 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1671 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
1674 /// Hints at the original code for a let statement.
1675 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1676 pub enum LocalSource {
1677 /// A `match _ { .. }`.
1679 /// A desugared `for _ in _ { .. }` loop.
1681 /// When lowering async functions, we create locals within the `async move` so that
1682 /// all parameters are dropped after the future is polled.
1684 /// ```ignore (pseudo-Rust)
1685 /// async fn foo(<pattern> @ x: Type) {
1687 /// let <pattern> = x;
1692 /// A desugared `<expr>.await`.
1696 /// Hints at the original code for a `match _ { .. }`.
1697 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1698 #[derive(HashStable_Generic)]
1699 pub enum MatchSource {
1700 /// A `match _ { .. }`.
1702 /// An `if _ { .. }` (optionally with `else { .. }`).
1703 IfDesugar { contains_else_clause: bool },
1704 /// An `if let _ = _ { .. }` (optionally with `else { .. }`).
1705 IfLetDesugar { contains_else_clause: bool },
1706 /// A `while _ { .. }` (which was desugared to a `loop { match _ { .. } }`).
1708 /// A `while let _ = _ { .. }` (which was desugared to a
1709 /// `loop { match _ { .. } }`).
1711 /// A desugared `for _ in _ { .. }` loop.
1713 /// A desugared `?` operator.
1715 /// A desugared `<expr>.await`.
1720 pub fn name(self) -> &'static str {
1724 IfDesugar { .. } | IfLetDesugar { .. } => "if",
1725 WhileDesugar | WhileLetDesugar => "while",
1726 ForLoopDesugar => "for",
1728 AwaitDesugar => ".await",
1733 /// The loop type that yielded an `ExprKind::Loop`.
1734 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1735 pub enum LoopSource {
1736 /// A `loop { .. }` loop.
1738 /// A `while _ { .. }` loop.
1740 /// A `while let _ = _ { .. }` loop.
1742 /// A `for _ in _ { .. }` loop.
1747 pub fn name(self) -> &'static str {
1749 LoopSource::Loop => "loop",
1750 LoopSource::While | LoopSource::WhileLet => "while",
1751 LoopSource::ForLoop => "for",
1756 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1757 pub enum LoopIdError {
1759 UnlabeledCfInWhileCondition,
1763 impl fmt::Display for LoopIdError {
1764 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1765 f.write_str(match self {
1766 LoopIdError::OutsideLoopScope => "not inside loop scope",
1767 LoopIdError::UnlabeledCfInWhileCondition => {
1768 "unlabeled control flow (break or continue) in while condition"
1770 LoopIdError::UnresolvedLabel => "label not found",
1775 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1776 pub struct Destination {
1777 // This is `Some(_)` iff there is an explicit user-specified `label
1778 pub label: Option<Label>,
1780 // These errors are caught and then reported during the diagnostics pass in
1781 // librustc_passes/loops.rs
1782 pub target_id: Result<HirId, LoopIdError>,
1785 /// The yield kind that caused an `ExprKind::Yield`.
1786 #[derive(Copy, Clone, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable, HashStable_Generic)]
1787 pub enum YieldSource {
1788 /// An `<expr>.await`.
1790 /// A plain `yield`.
1794 impl fmt::Display for YieldSource {
1795 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1796 f.write_str(match self {
1797 YieldSource::Await => "`await`",
1798 YieldSource::Yield => "`yield`",
1803 impl From<GeneratorKind> for YieldSource {
1804 fn from(kind: GeneratorKind) -> Self {
1806 // Guess based on the kind of the current generator.
1807 GeneratorKind::Gen => Self::Yield,
1808 GeneratorKind::Async(_) => Self::Await,
1813 // N.B., if you change this, you'll probably want to change the corresponding
1814 // type structure in middle/ty.rs as well.
1815 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1816 pub struct MutTy<'hir> {
1817 pub ty: &'hir Ty<'hir>,
1818 pub mutbl: Mutability,
1821 /// Represents a function's signature in a trait declaration,
1822 /// trait implementation, or a free function.
1823 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1824 pub struct FnSig<'hir> {
1825 pub header: FnHeader,
1826 pub decl: &'hir FnDecl<'hir>,
1829 // The bodies for items are stored "out of line", in a separate
1830 // hashmap in the `Crate`. Here we just record the node-id of the item
1831 // so it can fetched later.
1832 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1833 pub struct TraitItemId {
1837 /// Represents an item declaration within a trait declaration,
1838 /// possibly including a default implementation. A trait item is
1839 /// either required (meaning it doesn't have an implementation, just a
1840 /// signature) or provided (meaning it has a default implementation).
1841 #[derive(RustcEncodable, RustcDecodable, Debug)]
1842 pub struct TraitItem<'hir> {
1845 pub attrs: &'hir [Attribute],
1846 pub generics: Generics<'hir>,
1847 pub kind: TraitItemKind<'hir>,
1851 /// Represents a trait method's body (or just argument names).
1852 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1853 pub enum TraitMethod<'hir> {
1854 /// No default body in the trait, just a signature.
1855 Required(&'hir [Ident]),
1857 /// Both signature and body are provided in the trait.
1861 /// Represents a trait method or associated constant or type
1862 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1863 pub enum TraitItemKind<'hir> {
1864 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
1865 Const(&'hir Ty<'hir>, Option<BodyId>),
1866 /// A method with an optional body.
1867 Method(FnSig<'hir>, TraitMethod<'hir>),
1868 /// An associated type with (possibly empty) bounds and optional concrete
1870 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
1873 // The bodies for items are stored "out of line", in a separate
1874 // hashmap in the `Crate`. Here we just record the node-id of the item
1875 // so it can fetched later.
1876 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1877 pub struct ImplItemId {
1881 /// Represents anything within an `impl` block.
1882 #[derive(RustcEncodable, RustcDecodable, Debug)]
1883 pub struct ImplItem<'hir> {
1886 pub vis: Visibility<'hir>,
1887 pub defaultness: Defaultness,
1888 pub attrs: &'hir [Attribute],
1889 pub generics: Generics<'hir>,
1890 pub kind: ImplItemKind<'hir>,
1894 /// Represents various kinds of content within an `impl`.
1895 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1896 pub enum ImplItemKind<'hir> {
1897 /// An associated constant of the given type, set to the constant result
1898 /// of the expression.
1899 Const(&'hir Ty<'hir>, BodyId),
1900 /// A method implementation with the given signature and body.
1901 Method(FnSig<'hir>, BodyId),
1902 /// An associated type.
1903 TyAlias(&'hir Ty<'hir>),
1904 /// An associated `type = impl Trait`.
1905 OpaqueTy(GenericBounds<'hir>),
1908 impl ImplItemKind<'_> {
1909 pub fn namespace(&self) -> Namespace {
1911 ImplItemKind::OpaqueTy(..) | ImplItemKind::TyAlias(..) => Namespace::TypeNS,
1912 ImplItemKind::Const(..) | ImplItemKind::Method(..) => Namespace::ValueNS,
1917 // The name of the associated type for `Fn` return types.
1918 pub const FN_OUTPUT_NAME: Symbol = sym::Output;
1920 /// Bind a type to an associated type (i.e., `A = Foo`).
1922 /// Bindings like `A: Debug` are represented as a special type `A =
1923 /// $::Debug` that is understood by the astconv code.
1925 /// FIXME(alexreg): why have a separate type for the binding case,
1926 /// wouldn't it be better to make the `ty` field an enum like the
1930 /// enum TypeBindingKind {
1935 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1936 pub struct TypeBinding<'hir> {
1938 #[stable_hasher(project(name))]
1940 pub kind: TypeBindingKind<'hir>,
1944 // Represents the two kinds of type bindings.
1945 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1946 pub enum TypeBindingKind<'hir> {
1947 /// E.g., `Foo<Bar: Send>`.
1948 Constraint { bounds: &'hir [GenericBound<'hir>] },
1949 /// E.g., `Foo<Bar = ()>`.
1950 Equality { ty: &'hir Ty<'hir> },
1953 impl TypeBinding<'_> {
1954 pub fn ty(&self) -> &Ty<'_> {
1956 TypeBindingKind::Equality { ref ty } => ty,
1957 _ => panic!("expected equality type binding for parenthesized generic args"),
1962 #[derive(RustcEncodable, RustcDecodable)]
1963 pub struct Ty<'hir> {
1965 pub kind: TyKind<'hir>,
1969 impl fmt::Debug for Ty<'_> {
1970 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1971 write!(f, "type({})", print::to_string(print::NO_ANN, |s| s.print_type(self)))
1975 /// Not represented directly in the AST; referred to by name through a `ty_path`.
1976 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1977 #[derive(HashStable_Generic)]
1987 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1988 pub struct BareFnTy<'hir> {
1989 pub unsafety: Unsafety,
1991 pub generic_params: &'hir [GenericParam<'hir>],
1992 pub decl: &'hir FnDecl<'hir>,
1993 pub param_names: &'hir [Ident],
1996 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1997 pub struct OpaqueTy<'hir> {
1998 pub generics: Generics<'hir>,
1999 pub bounds: GenericBounds<'hir>,
2000 pub impl_trait_fn: Option<DefId>,
2001 pub origin: OpaqueTyOrigin,
2004 /// From whence the opaque type came.
2005 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2006 pub enum OpaqueTyOrigin {
2007 /// `type Foo = impl Trait;`
2013 /// Impl trait in bindings, consts, statics, bounds.
2017 /// The various kinds of types recognized by the compiler.
2018 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2019 pub enum TyKind<'hir> {
2020 /// A variable length slice (i.e., `[T]`).
2021 Slice(&'hir Ty<'hir>),
2022 /// A fixed length array (i.e., `[T; n]`).
2023 Array(&'hir Ty<'hir>, AnonConst),
2024 /// A raw pointer (i.e., `*const T` or `*mut T`).
2026 /// A reference (i.e., `&'a T` or `&'a mut T`).
2027 Rptr(Lifetime, MutTy<'hir>),
2028 /// A bare function (e.g., `fn(usize) -> bool`).
2029 BareFn(&'hir BareFnTy<'hir>),
2030 /// The never type (`!`).
2032 /// A tuple (`(A, B, C, D, ...)`).
2033 Tup(&'hir [Ty<'hir>]),
2034 /// A path to a type definition (`module::module::...::Type`), or an
2035 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2037 /// Type parameters may be stored in each `PathSegment`.
2039 /// A type definition itself. This is currently only used for the `type Foo = impl Trait`
2040 /// item that `impl Trait` in return position desugars to.
2042 /// The generic argument list contains the lifetimes (and in the future possibly parameters)
2043 /// that are actually bound on the `impl Trait`.
2044 Def(ItemId, &'hir [GenericArg<'hir>]),
2045 /// A trait object type `Bound1 + Bound2 + Bound3`
2046 /// where `Bound` is a trait or a lifetime.
2047 TraitObject(&'hir [PolyTraitRef<'hir>], Lifetime),
2050 /// `TyKind::Infer` means the type should be inferred instead of it having been
2051 /// specified. This can appear anywhere in a type.
2053 /// Placeholder for a type that has failed to be defined.
2057 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic, PartialEq)]
2058 pub struct InlineAsmOutput {
2059 pub constraint: Symbol,
2061 pub is_indirect: bool,
2065 // NOTE(eddyb) This is used within MIR as well, so unlike the rest of the HIR,
2066 // it needs to be `Clone` and use plain `Vec<T>` instead of arena-allocated slice.
2067 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic, PartialEq)]
2068 pub struct InlineAsmInner {
2070 pub asm_str_style: StrStyle,
2071 pub outputs: Vec<InlineAsmOutput>,
2072 pub inputs: Vec<Symbol>,
2073 pub clobbers: Vec<Symbol>,
2075 pub alignstack: bool,
2076 pub dialect: AsmDialect,
2079 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2080 pub struct InlineAsm<'hir> {
2081 pub inner: InlineAsmInner,
2082 pub outputs_exprs: &'hir [Expr<'hir>],
2083 pub inputs_exprs: &'hir [Expr<'hir>],
2086 /// Represents a parameter in a function header.
2087 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2088 pub struct Param<'hir> {
2089 pub attrs: &'hir [Attribute],
2091 pub pat: &'hir Pat<'hir>,
2095 /// Represents the header (not the body) of a function declaration.
2096 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2097 pub struct FnDecl<'hir> {
2098 /// The types of the function's parameters.
2100 /// Additional argument data is stored in the function's [body](Body::parameters).
2101 pub inputs: &'hir [Ty<'hir>],
2102 pub output: FnRetTy<'hir>,
2103 pub c_variadic: bool,
2104 /// Does the function have an implicit self?
2105 pub implicit_self: ImplicitSelfKind,
2108 /// Represents what type of implicit self a function has, if any.
2109 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2110 pub enum ImplicitSelfKind {
2111 /// Represents a `fn x(self);`.
2113 /// Represents a `fn x(mut self);`.
2115 /// Represents a `fn x(&self);`.
2117 /// Represents a `fn x(&mut self);`.
2119 /// Represents when a function does not have a self argument or
2120 /// when a function has a `self: X` argument.
2124 impl ImplicitSelfKind {
2125 /// Does this represent an implicit self?
2126 pub fn has_implicit_self(&self) -> bool {
2128 ImplicitSelfKind::None => false,
2134 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
2135 #[derive(HashStable_Generic)]
2141 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2142 pub enum Defaultness {
2143 Default { has_value: bool },
2148 pub fn has_value(&self) -> bool {
2150 Defaultness::Default { has_value, .. } => has_value,
2151 Defaultness::Final => true,
2155 pub fn is_final(&self) -> bool {
2156 *self == Defaultness::Final
2159 pub fn is_default(&self) -> bool {
2161 Defaultness::Default { .. } => true,
2167 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2168 pub enum FnRetTy<'hir> {
2169 /// Return type is not specified.
2171 /// Functions default to `()` and
2172 /// closures default to inference. Span points to where return
2173 /// type would be inserted.
2174 DefaultReturn(Span),
2175 /// Everything else.
2176 Return(&'hir Ty<'hir>),
2179 impl fmt::Display for FnRetTy<'_> {
2180 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2182 Self::Return(ref ty) => print::to_string(print::NO_ANN, |s| s.print_type(ty)).fmt(f),
2183 Self::DefaultReturn(_) => "()".fmt(f),
2189 pub fn span(&self) -> Span {
2191 Self::DefaultReturn(span) => span,
2192 Self::Return(ref ty) => ty.span,
2197 #[derive(RustcEncodable, RustcDecodable, Debug)]
2198 pub struct Mod<'hir> {
2199 /// A span from the first token past `{` to the last token until `}`.
2200 /// For `mod foo;`, the inner span ranges from the first token
2201 /// to the last token in the external file.
2203 pub item_ids: &'hir [ItemId],
2206 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2207 pub struct ForeignMod<'hir> {
2209 pub items: &'hir [ForeignItem<'hir>],
2212 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2213 pub struct GlobalAsm {
2217 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2218 pub struct EnumDef<'hir> {
2219 pub variants: &'hir [Variant<'hir>],
2222 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2223 pub struct Variant<'hir> {
2224 /// Name of the variant.
2225 #[stable_hasher(project(name))]
2227 /// Attributes of the variant.
2228 pub attrs: &'hir [Attribute],
2229 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2231 /// Fields and constructor id of the variant.
2232 pub data: VariantData<'hir>,
2233 /// Explicit discriminant (e.g., `Foo = 1`).
2234 pub disr_expr: Option<AnonConst>,
2239 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2241 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2242 /// Also produced for each element of a list `use`, e.g.
2243 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2246 /// Glob import, e.g., `use foo::*`.
2249 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2250 /// an additional `use foo::{}` for performing checks such as
2251 /// unstable feature gating. May be removed in the future.
2255 /// References to traits in impls.
2257 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2258 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2259 /// trait being referred to but just a unique `HirId` that serves as a key
2260 /// within the resolution map.
2261 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2262 pub struct TraitRef<'hir> {
2263 pub path: &'hir Path<'hir>,
2264 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2265 #[stable_hasher(ignore)]
2266 pub hir_ref_id: HirId,
2270 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2271 pub fn trait_def_id(&self) -> DefId {
2272 match self.path.res {
2273 Res::Def(DefKind::Trait, did) => did,
2274 Res::Def(DefKind::TraitAlias, did) => did,
2278 _ => unreachable!(),
2283 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2284 pub struct PolyTraitRef<'hir> {
2285 /// The `'a` in `for<'a> Foo<&'a T>`.
2286 pub bound_generic_params: &'hir [GenericParam<'hir>],
2288 /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
2289 pub trait_ref: TraitRef<'hir>,
2294 pub type Visibility<'hir> = Spanned<VisibilityKind<'hir>>;
2296 #[derive(RustcEncodable, RustcDecodable, Debug)]
2297 pub enum VisibilityKind<'hir> {
2300 Restricted { path: &'hir Path<'hir>, hir_id: HirId },
2304 impl VisibilityKind<'_> {
2305 pub fn is_pub(&self) -> bool {
2307 VisibilityKind::Public => true,
2312 pub fn is_pub_restricted(&self) -> bool {
2314 VisibilityKind::Public | VisibilityKind::Inherited => false,
2315 VisibilityKind::Crate(..) | VisibilityKind::Restricted { .. } => true,
2319 pub fn descr(&self) -> &'static str {
2321 VisibilityKind::Public => "public",
2322 VisibilityKind::Inherited => "private",
2323 VisibilityKind::Crate(..) => "crate-visible",
2324 VisibilityKind::Restricted { .. } => "restricted",
2329 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2330 pub struct StructField<'hir> {
2332 #[stable_hasher(project(name))]
2334 pub vis: Visibility<'hir>,
2336 pub ty: &'hir Ty<'hir>,
2337 pub attrs: &'hir [Attribute],
2340 impl StructField<'_> {
2341 // Still necessary in couple of places
2342 pub fn is_positional(&self) -> bool {
2343 let first = self.ident.as_str().as_bytes()[0];
2344 first >= b'0' && first <= b'9'
2348 /// Fields and constructor IDs of enum variants and structs.
2349 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2350 pub enum VariantData<'hir> {
2351 /// A struct variant.
2353 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2354 Struct(&'hir [StructField<'hir>], /* recovered */ bool),
2355 /// A tuple variant.
2357 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2358 Tuple(&'hir [StructField<'hir>], HirId),
2361 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2365 impl VariantData<'hir> {
2366 /// Return the fields of this variant.
2367 pub fn fields(&self) -> &'hir [StructField<'hir>] {
2369 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2374 /// Return the `HirId` of this variant's constructor, if it has one.
2375 pub fn ctor_hir_id(&self) -> Option<HirId> {
2377 VariantData::Struct(_, _) => None,
2378 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2383 // The bodies for items are stored "out of line", in a separate
2384 // hashmap in the `Crate`. Here we just record the node-id of the item
2385 // so it can fetched later.
2386 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2393 /// The name might be a dummy name in case of anonymous items
2394 #[derive(RustcEncodable, RustcDecodable, Debug)]
2395 pub struct Item<'hir> {
2398 pub attrs: &'hir [Attribute],
2399 pub kind: ItemKind<'hir>,
2400 pub vis: Visibility<'hir>,
2404 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2405 #[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
2412 pub fn prefix_str(&self) -> &'static str {
2414 Self::Unsafe => "unsafe ",
2420 impl fmt::Display for Unsafety {
2421 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2422 f.write_str(match *self {
2423 Self::Unsafe => "unsafe",
2424 Self::Normal => "normal",
2429 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2430 #[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
2431 pub enum Constness {
2436 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2437 pub struct FnHeader {
2438 pub unsafety: Unsafety,
2439 pub constness: Constness,
2440 pub asyncness: IsAsync,
2445 pub fn is_const(&self) -> bool {
2446 match &self.constness {
2447 Constness::Const => true,
2453 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2454 pub enum ItemKind<'hir> {
2455 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2457 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2458 ExternCrate(Option<Name>),
2460 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2464 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2465 Use(&'hir Path<'hir>, UseKind),
2467 /// A `static` item.
2468 Static(&'hir Ty<'hir>, Mutability, BodyId),
2470 Const(&'hir Ty<'hir>, BodyId),
2471 /// A function declaration.
2472 Fn(FnSig<'hir>, Generics<'hir>, BodyId),
2475 /// An external module, e.g. `extern { .. }`.
2476 ForeignMod(ForeignMod<'hir>),
2477 /// Module-level inline assembly (from `global_asm!`).
2478 GlobalAsm(&'hir GlobalAsm),
2479 /// A type alias, e.g., `type Foo = Bar<u8>`.
2480 TyAlias(&'hir Ty<'hir>, Generics<'hir>),
2481 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2482 OpaqueTy(OpaqueTy<'hir>),
2483 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2484 Enum(EnumDef<'hir>, Generics<'hir>),
2485 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2486 Struct(VariantData<'hir>, Generics<'hir>),
2487 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2488 Union(VariantData<'hir>, Generics<'hir>),
2489 /// A trait definition.
2490 Trait(IsAuto, Unsafety, Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
2492 TraitAlias(Generics<'hir>, GenericBounds<'hir>),
2494 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2497 polarity: ImplPolarity,
2498 defaultness: Defaultness,
2499 constness: Constness,
2500 generics: Generics<'hir>,
2502 /// The trait being implemented, if any.
2503 of_trait: Option<TraitRef<'hir>>,
2505 self_ty: &'hir Ty<'hir>,
2506 items: &'hir [ImplItemRef<'hir>],
2511 pub fn descr(&self) -> &str {
2513 ItemKind::ExternCrate(..) => "extern crate",
2514 ItemKind::Use(..) => "`use` import",
2515 ItemKind::Static(..) => "static item",
2516 ItemKind::Const(..) => "constant item",
2517 ItemKind::Fn(..) => "function",
2518 ItemKind::Mod(..) => "module",
2519 ItemKind::ForeignMod(..) => "extern block",
2520 ItemKind::GlobalAsm(..) => "global asm item",
2521 ItemKind::TyAlias(..) => "type alias",
2522 ItemKind::OpaqueTy(..) => "opaque type",
2523 ItemKind::Enum(..) => "enum",
2524 ItemKind::Struct(..) => "struct",
2525 ItemKind::Union(..) => "union",
2526 ItemKind::Trait(..) => "trait",
2527 ItemKind::TraitAlias(..) => "trait alias",
2528 ItemKind::Impl { .. } => "implementation",
2532 pub fn generics(&self) -> Option<&Generics<'_>> {
2534 ItemKind::Fn(_, ref generics, _)
2535 | ItemKind::TyAlias(_, ref generics)
2536 | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
2537 | ItemKind::Enum(_, ref generics)
2538 | ItemKind::Struct(_, ref generics)
2539 | ItemKind::Union(_, ref generics)
2540 | ItemKind::Trait(_, _, ref generics, _, _)
2541 | ItemKind::Impl { ref generics, .. } => generics,
2547 /// A reference from an trait to one of its associated items. This
2548 /// contains the item's id, naturally, but also the item's name and
2549 /// some other high-level details (like whether it is an associated
2550 /// type or method, and whether it is public). This allows other
2551 /// passes to find the impl they want without loading the ID (which
2552 /// means fewer edges in the incremental compilation graph).
2553 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2554 pub struct TraitItemRef {
2555 pub id: TraitItemId,
2556 #[stable_hasher(project(name))]
2558 pub kind: AssocItemKind,
2560 pub defaultness: Defaultness,
2563 /// A reference from an impl to one of its associated items. This
2564 /// contains the item's ID, naturally, but also the item's name and
2565 /// some other high-level details (like whether it is an associated
2566 /// type or method, and whether it is public). This allows other
2567 /// passes to find the impl they want without loading the ID (which
2568 /// means fewer edges in the incremental compilation graph).
2569 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2570 pub struct ImplItemRef<'hir> {
2572 #[stable_hasher(project(name))]
2574 pub kind: AssocItemKind,
2576 pub vis: Visibility<'hir>,
2577 pub defaultness: Defaultness,
2580 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2581 pub enum AssocItemKind {
2583 Method { has_self: bool },
2588 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2589 pub struct ForeignItem<'hir> {
2590 #[stable_hasher(project(name))]
2592 pub attrs: &'hir [Attribute],
2593 pub kind: ForeignItemKind<'hir>,
2596 pub vis: Visibility<'hir>,
2599 /// An item within an `extern` block.
2600 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2601 pub enum ForeignItemKind<'hir> {
2602 /// A foreign function.
2603 Fn(&'hir FnDecl<'hir>, &'hir [Ident], Generics<'hir>),
2604 /// A foreign static item (`static ext: u8`).
2605 Static(&'hir Ty<'hir>, Mutability),
2610 impl ForeignItemKind<'hir> {
2611 pub fn descriptive_variant(&self) -> &str {
2613 ForeignItemKind::Fn(..) => "foreign function",
2614 ForeignItemKind::Static(..) => "foreign static item",
2615 ForeignItemKind::Type => "foreign type",
2620 /// A variable captured by a closure.
2621 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable, HashStable_Generic)]
2623 // First span where it is accessed (there can be multiple).
2627 pub type CaptureModeMap = NodeMap<CaptureBy>;
2629 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2630 // has length > 0 if the trait is found through an chain of imports, starting with the
2631 // import/use statement in the scope where the trait is used.
2632 #[derive(Clone, Debug)]
2633 pub struct TraitCandidate<ID = HirId> {
2635 pub import_ids: SmallVec<[ID; 1]>,
2638 impl<ID> TraitCandidate<ID> {
2639 pub fn map_import_ids<F, T>(self, f: F) -> TraitCandidate<T>
2643 let TraitCandidate { def_id, import_ids } = self;
2644 let import_ids = import_ids.into_iter().map(f).collect();
2645 TraitCandidate { def_id, import_ids }
2649 // Trait method resolution
2650 pub type TraitMap<ID = HirId> = NodeMap<Vec<TraitCandidate<ID>>>;
2652 // Map from the NodeId of a glob import to a list of items which are actually
2654 pub type GlobMap = NodeMap<FxHashSet<Name>>;
2656 #[derive(Copy, Clone, Debug)]
2657 pub enum Node<'hir> {
2658 Param(&'hir Param<'hir>),
2659 Item(&'hir Item<'hir>),
2660 ForeignItem(&'hir ForeignItem<'hir>),
2661 TraitItem(&'hir TraitItem<'hir>),
2662 ImplItem(&'hir ImplItem<'hir>),
2663 Variant(&'hir Variant<'hir>),
2664 Field(&'hir StructField<'hir>),
2665 AnonConst(&'hir AnonConst),
2666 Expr(&'hir Expr<'hir>),
2667 Stmt(&'hir Stmt<'hir>),
2668 PathSegment(&'hir PathSegment<'hir>),
2670 TraitRef(&'hir TraitRef<'hir>),
2671 Binding(&'hir Pat<'hir>),
2672 Pat(&'hir Pat<'hir>),
2673 Arm(&'hir Arm<'hir>),
2674 Block(&'hir Block<'hir>),
2675 Local(&'hir Local<'hir>),
2676 MacroDef(&'hir MacroDef<'hir>),
2678 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
2679 /// with synthesized constructors.
2680 Ctor(&'hir VariantData<'hir>),
2682 Lifetime(&'hir Lifetime),
2683 GenericParam(&'hir GenericParam<'hir>),
2684 Visibility(&'hir Visibility<'hir>),
2690 pub fn ident(&self) -> Option<Ident> {
2692 Node::TraitItem(TraitItem { ident, .. })
2693 | Node::ImplItem(ImplItem { ident, .. })
2694 | Node::ForeignItem(ForeignItem { ident, .. })
2695 | Node::Item(Item { ident, .. }) => Some(*ident),
2700 pub fn fn_decl(&self) -> Option<&FnDecl<'_>> {
2702 Node::TraitItem(TraitItem { kind: TraitItemKind::Method(fn_sig, _), .. })
2703 | Node::ImplItem(ImplItem { kind: ImplItemKind::Method(fn_sig, _), .. })
2704 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
2705 Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
2712 pub fn generics(&self) -> Option<&Generics<'_>> {
2714 Node::TraitItem(TraitItem { generics, .. })
2715 | Node::ImplItem(ImplItem { generics, .. })
2716 | Node::Item(Item { kind: ItemKind::Fn(_, generics, _), .. }) => Some(generics),