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_data_structures::fx::FxHashSet;
12 use rustc_data_structures::sync::{par_for_each_in, Send, Sync};
13 use rustc_errors::FatalError;
14 use rustc_macros::HashStable_Generic;
15 use rustc_span::source_map::{SourceMap, Spanned};
16 use rustc_span::symbol::{kw, sym, Symbol};
17 use rustc_span::{MultiSpan, Span, DUMMY_SP};
18 use rustc_target::spec::abi::Abi;
19 use syntax::ast::{self, AsmDialect, CrateSugar, Ident, Name};
20 use syntax::ast::{AttrVec, Attribute, FloatTy, IntTy, Label, LitKind, StrStyle, UintTy};
21 pub use syntax::ast::{BorrowKind, ImplPolarity, IsAuto};
22 pub use syntax::ast::{CaptureBy, Movability, Mutability};
23 use syntax::node_id::NodeMap;
24 use syntax::tokenstream::TokenStream;
25 use syntax::util::parser::ExprPrecedence;
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,
303 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
304 pub struct GenericArgs<'hir> {
305 /// The generic arguments for this path segment.
306 pub args: &'hir [GenericArg<'hir>],
307 /// Bindings (equality constraints) on associated types, if present.
308 /// E.g., `Foo<A = Bar>`.
309 pub bindings: &'hir [TypeBinding<'hir>],
310 /// Were arguments written in parenthesized form `Fn(T) -> U`?
311 /// This is required mostly for pretty-printing and diagnostics,
312 /// but also for changing lifetime elision rules to be "function-like".
313 pub parenthesized: bool,
316 impl GenericArgs<'_> {
317 pub const fn none() -> Self {
318 Self { args: &[], bindings: &[], parenthesized: false }
321 pub fn is_empty(&self) -> bool {
322 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
325 pub fn inputs(&self) -> &[Ty<'_>] {
326 if self.parenthesized {
327 for arg in self.args {
329 GenericArg::Lifetime(_) => {}
330 GenericArg::Type(ref ty) => {
331 if let TyKind::Tup(ref tys) = ty.kind {
336 GenericArg::Const(_) => {}
340 panic!("GenericArgs::inputs: not a `Fn(T) -> U`");
343 pub fn own_counts(&self) -> GenericParamCount {
344 // We could cache this as a property of `GenericParamCount`, but
345 // the aim is to refactor this away entirely eventually and the
346 // presence of this method will be a constant reminder.
347 let mut own_counts: GenericParamCount = Default::default();
349 for arg in self.args {
351 GenericArg::Lifetime(_) => own_counts.lifetimes += 1,
352 GenericArg::Type(_) => own_counts.types += 1,
353 GenericArg::Const(_) => own_counts.consts += 1,
361 /// A modifier on a bound, currently this is only used for `?Sized`, where the
362 /// modifier is `Maybe`. Negative bounds should also be handled here.
363 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
364 #[derive(HashStable_Generic)]
365 pub enum TraitBoundModifier {
371 /// The AST represents all type param bounds as types.
372 /// `typeck::collect::compute_bounds` matches these against
373 /// the "special" built-in traits (see `middle::lang_items`) and
374 /// detects `Copy`, `Send` and `Sync`.
375 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
376 pub enum GenericBound<'hir> {
377 Trait(PolyTraitRef<'hir>, TraitBoundModifier),
381 impl GenericBound<'_> {
382 pub fn trait_def_id(&self) -> Option<DefId> {
384 GenericBound::Trait(data, _) => Some(data.trait_ref.trait_def_id()),
389 pub fn span(&self) -> Span {
391 &GenericBound::Trait(ref t, ..) => t.span,
392 &GenericBound::Outlives(ref l) => l.span,
397 pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
399 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
400 pub enum LifetimeParamKind {
401 // Indicates that the lifetime definition was explicitly declared (e.g., in
402 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
405 // Indicates that the lifetime definition was synthetically added
406 // as a result of an in-band lifetime usage (e.g., in
407 // `fn foo(x: &'a u8) -> &'a u8 { x }`).
410 // Indication that the lifetime was elided (e.g., in both cases in
411 // `fn foo(x: &u8) -> &'_ u8 { x }`).
414 // Indication that the lifetime name was somehow in error.
418 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
419 pub enum GenericParamKind<'hir> {
420 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
422 kind: LifetimeParamKind,
425 default: Option<&'hir Ty<'hir>>,
426 synthetic: Option<SyntheticTyParamKind>,
433 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
434 pub struct GenericParam<'hir> {
437 pub attrs: &'hir [Attribute],
438 pub bounds: GenericBounds<'hir>,
440 pub pure_wrt_drop: bool,
441 pub kind: GenericParamKind<'hir>,
444 impl GenericParam<'hir> {
445 pub fn bounds_span(&self) -> Option<Span> {
446 self.bounds.iter().fold(None, |span, bound| {
447 let span = span.map(|s| s.to(bound.span())).unwrap_or_else(|| bound.span());
455 pub struct GenericParamCount {
456 pub lifetimes: usize,
461 /// Represents lifetimes and type parameters attached to a declaration
462 /// of a function, enum, trait, etc.
463 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
464 pub struct Generics<'hir> {
465 pub params: &'hir [GenericParam<'hir>],
466 pub where_clause: WhereClause<'hir>,
470 impl Generics<'hir> {
471 pub const fn empty() -> Generics<'hir> {
474 where_clause: WhereClause { predicates: &[], span: DUMMY_SP },
479 pub fn own_counts(&self) -> GenericParamCount {
480 // We could cache this as a property of `GenericParamCount`, but
481 // the aim is to refactor this away entirely eventually and the
482 // presence of this method will be a constant reminder.
483 let mut own_counts: GenericParamCount = Default::default();
485 for param in self.params {
487 GenericParamKind::Lifetime { .. } => own_counts.lifetimes += 1,
488 GenericParamKind::Type { .. } => own_counts.types += 1,
489 GenericParamKind::Const { .. } => own_counts.consts += 1,
496 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'_>> {
497 for param in self.params {
498 if name == param.name.ident().name {
505 pub fn spans(&self) -> MultiSpan {
506 if self.params.is_empty() {
509 self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
514 /// Synthetic type parameters are converted to another form during lowering; this allows
515 /// us to track the original form they had, and is useful for error messages.
516 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
517 #[derive(HashStable_Generic)]
518 pub enum SyntheticTyParamKind {
522 /// A where-clause in a definition.
523 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
524 pub struct WhereClause<'hir> {
525 pub predicates: &'hir [WherePredicate<'hir>],
526 // Only valid if predicates aren't empty.
530 impl WhereClause<'_> {
531 pub fn span(&self) -> Option<Span> {
532 if self.predicates.is_empty() { None } else { Some(self.span) }
535 /// The `WhereClause` under normal circumstances points at either the predicates or the empty
536 /// space where the `where` clause should be. Only of use for diagnostic suggestions.
537 pub fn span_for_predicates_or_empty_place(&self) -> Span {
542 /// A single predicate in a where-clause.
543 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
544 pub enum WherePredicate<'hir> {
545 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
546 BoundPredicate(WhereBoundPredicate<'hir>),
547 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
548 RegionPredicate(WhereRegionPredicate<'hir>),
549 /// An equality predicate (unsupported).
550 EqPredicate(WhereEqPredicate<'hir>),
553 impl WherePredicate<'_> {
554 pub fn span(&self) -> Span {
556 &WherePredicate::BoundPredicate(ref p) => p.span,
557 &WherePredicate::RegionPredicate(ref p) => p.span,
558 &WherePredicate::EqPredicate(ref p) => p.span,
563 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
564 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
565 pub struct WhereBoundPredicate<'hir> {
567 /// Any generics from a `for` binding.
568 pub bound_generic_params: &'hir [GenericParam<'hir>],
569 /// The type being bounded.
570 pub bounded_ty: &'hir Ty<'hir>,
571 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
572 pub bounds: GenericBounds<'hir>,
575 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
576 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
577 pub struct WhereRegionPredicate<'hir> {
579 pub lifetime: Lifetime,
580 pub bounds: GenericBounds<'hir>,
583 /// An equality predicate (e.g., `T = int`); currently unsupported.
584 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
585 pub struct WhereEqPredicate<'hir> {
588 pub lhs_ty: &'hir Ty<'hir>,
589 pub rhs_ty: &'hir Ty<'hir>,
592 #[derive(RustcEncodable, RustcDecodable, Debug)]
593 pub struct ModuleItems {
594 // Use BTreeSets here so items are in the same order as in the
595 // list of all items in Crate
596 pub items: BTreeSet<HirId>,
597 pub trait_items: BTreeSet<TraitItemId>,
598 pub impl_items: BTreeSet<ImplItemId>,
601 /// The top-level data structure that stores the entire contents of
602 /// the crate currently being compiled.
604 /// For more details, see the [rustc guide].
606 /// [rustc guide]: https://rust-lang.github.io/rustc-guide/hir.html
607 #[derive(RustcEncodable, RustcDecodable, Debug)]
608 pub struct Crate<'hir> {
609 pub module: Mod<'hir>,
610 pub attrs: &'hir [Attribute],
612 pub exported_macros: &'hir [MacroDef<'hir>],
613 // Attributes from non-exported macros, kept only for collecting the library feature list.
614 pub non_exported_macro_attrs: &'hir [Attribute],
616 // N.B., we use a `BTreeMap` here so that `visit_all_items` iterates
617 // over the ids in increasing order. In principle it should not
618 // matter what order we visit things in, but in *practice* it
619 // does, because it can affect the order in which errors are
620 // detected, which in turn can make compile-fail tests yield
621 // slightly different results.
622 pub items: BTreeMap<HirId, Item<'hir>>,
624 pub trait_items: BTreeMap<TraitItemId, TraitItem<'hir>>,
625 pub impl_items: BTreeMap<ImplItemId, ImplItem<'hir>>,
626 pub bodies: BTreeMap<BodyId, Body<'hir>>,
627 pub trait_impls: BTreeMap<DefId, Vec<HirId>>,
629 /// A list of the body ids written out in the order in which they
630 /// appear in the crate. If you're going to process all the bodies
631 /// in the crate, you should iterate over this list rather than the keys
633 pub body_ids: Vec<BodyId>,
635 /// A list of modules written out in the order in which they
636 /// appear in the crate. This includes the main crate module.
637 pub modules: BTreeMap<HirId, ModuleItems>,
638 /// A list of proc macro HirIds, written out in the order in which
639 /// they are declared in the static array generated by proc_macro_harness.
640 pub proc_macros: Vec<HirId>,
644 pub fn item(&self, id: HirId) -> &Item<'hir> {
648 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem<'hir> {
649 &self.trait_items[&id]
652 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem<'hir> {
653 &self.impl_items[&id]
656 pub fn body(&self, id: BodyId) -> &Body<'hir> {
662 /// Visits all items in the crate in some deterministic (but
663 /// unspecified) order. If you just need to process every item,
664 /// but don't care about nesting, this method is the best choice.
666 /// If you do care about nesting -- usually because your algorithm
667 /// follows lexical scoping rules -- then you want a different
668 /// approach. You should override `visit_nested_item` in your
669 /// visitor and then call `intravisit::walk_crate` instead.
670 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
672 V: itemlikevisit::ItemLikeVisitor<'hir>,
674 for (_, item) in &self.items {
675 visitor.visit_item(item);
678 for (_, trait_item) in &self.trait_items {
679 visitor.visit_trait_item(trait_item);
682 for (_, impl_item) in &self.impl_items {
683 visitor.visit_impl_item(impl_item);
687 /// A parallel version of `visit_all_item_likes`.
688 pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
690 V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send,
694 par_for_each_in(&self.items, |(_, item)| {
695 visitor.visit_item(item);
699 par_for_each_in(&self.trait_items, |(_, trait_item)| {
700 visitor.visit_trait_item(trait_item);
704 par_for_each_in(&self.impl_items, |(_, impl_item)| {
705 visitor.visit_impl_item(impl_item);
712 /// A macro definition, in this crate or imported from another.
714 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
715 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
716 pub struct MacroDef<'hir> {
718 pub vis: Visibility<'hir>,
719 pub attrs: &'hir [Attribute],
722 pub body: TokenStream,
726 /// A block of statements `{ .. }`, which may have a label (in this case the
727 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
728 /// the `rules` being anything but `DefaultBlock`.
729 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
730 pub struct Block<'hir> {
731 /// Statements in a block.
732 pub stmts: &'hir [Stmt<'hir>],
733 /// An expression at the end of the block
734 /// without a semicolon, if any.
735 pub expr: Option<&'hir Expr<'hir>>,
736 #[stable_hasher(ignore)]
738 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
739 pub rules: BlockCheckMode,
741 /// If true, then there may exist `break 'a` values that aim to
742 /// break out of this block early.
743 /// Used by `'label: {}` blocks and by `try {}` blocks.
744 pub targeted_by_break: bool,
747 #[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
748 pub struct Pat<'hir> {
749 #[stable_hasher(ignore)]
751 pub kind: PatKind<'hir>,
755 impl fmt::Debug for Pat<'_> {
756 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
761 print::to_string(print::NO_ANN, |s| s.print_pat(self))
767 // FIXME(#19596) this is a workaround, but there should be a better way
768 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'_>) -> bool) -> bool {
775 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
776 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
777 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
778 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
779 Slice(before, slice, after) => {
780 before.iter().chain(slice.iter()).chain(after.iter()).all(|p| p.walk_short_(it))
785 /// Walk the pattern in left-to-right order,
786 /// short circuiting (with `.all(..)`) if `false` is returned.
788 /// Note that when visiting e.g. `Tuple(ps)`,
789 /// if visiting `ps[0]` returns `false`,
790 /// then `ps[1]` will not be visited.
791 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'_>) -> bool) -> bool {
792 self.walk_short_(&mut it)
795 // FIXME(#19596) this is a workaround, but there should be a better way
796 fn walk_(&self, it: &mut impl FnMut(&Pat<'_>) -> bool) {
803 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
804 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
805 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
806 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
807 Slice(before, slice, after) => {
808 before.iter().chain(slice.iter()).chain(after.iter()).for_each(|p| p.walk_(it))
813 /// Walk the pattern in left-to-right order.
815 /// If `it(pat)` returns `false`, the children are not visited.
816 pub fn walk(&self, mut it: impl FnMut(&Pat<'_>) -> bool) {
820 /// Walk the pattern in left-to-right order.
822 /// If you always want to recurse, prefer this method over `walk`.
823 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
831 /// A single field in a struct pattern.
833 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
834 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
835 /// except `is_shorthand` is true.
836 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
837 pub struct FieldPat<'hir> {
838 #[stable_hasher(ignore)]
840 /// The identifier for the field.
841 #[stable_hasher(project(name))]
843 /// The pattern the field is destructured to.
844 pub pat: &'hir Pat<'hir>,
845 pub is_shorthand: bool,
849 /// Explicit binding annotations given in the HIR for a binding. Note
850 /// that this is not the final binding *mode* that we infer after type
852 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
853 pub enum BindingAnnotation {
854 /// No binding annotation given: this means that the final binding mode
855 /// will depend on whether we have skipped through a `&` reference
856 /// when matching. For example, the `x` in `Some(x)` will have binding
857 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
858 /// ultimately be inferred to be by-reference.
860 /// Note that implicit reference skipping is not implemented yet (#42640).
863 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
866 /// Annotated as `ref`, like `ref x`
869 /// Annotated as `ref mut x`.
873 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
879 impl fmt::Display for RangeEnd {
880 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
881 f.write_str(match self {
882 RangeEnd::Included => "..=",
883 RangeEnd::Excluded => "..",
888 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
889 pub enum PatKind<'hir> {
890 /// Represents a wildcard pattern (i.e., `_`).
893 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
894 /// The `HirId` is the canonical ID for the variable being bound,
895 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
896 /// which is the pattern ID of the first `x`.
897 Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
899 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
900 /// The `bool` is `true` in the presence of a `..`.
901 Struct(QPath<'hir>, &'hir [FieldPat<'hir>], bool),
903 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
904 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
905 /// `0 <= position <= subpats.len()`
906 TupleStruct(QPath<'hir>, &'hir [&'hir Pat<'hir>], Option<usize>),
908 /// An or-pattern `A | B | C`.
909 /// Invariant: `pats.len() >= 2`.
910 Or(&'hir [&'hir Pat<'hir>]),
912 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
915 /// A tuple pattern (e.g., `(a, b)`).
916 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
917 /// `0 <= position <= subpats.len()`
918 Tuple(&'hir [&'hir Pat<'hir>], Option<usize>),
921 Box(&'hir Pat<'hir>),
923 /// A reference pattern (e.g., `&mut (a, b)`).
924 Ref(&'hir Pat<'hir>, Mutability),
927 Lit(&'hir Expr<'hir>),
929 /// A range pattern (e.g., `1..=2` or `1..2`).
930 Range(Option<&'hir Expr<'hir>>, Option<&'hir Expr<'hir>>, RangeEnd),
932 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
934 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
935 /// If `slice` exists, then `after` can be non-empty.
937 /// The representation for e.g., `[a, b, .., c, d]` is:
939 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
941 Slice(&'hir [&'hir Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [&'hir Pat<'hir>]),
944 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
946 /// The `+` operator (addition).
948 /// The `-` operator (subtraction).
950 /// The `*` operator (multiplication).
952 /// The `/` operator (division).
954 /// The `%` operator (modulus).
956 /// The `&&` operator (logical and).
958 /// The `||` operator (logical or).
960 /// The `^` operator (bitwise xor).
962 /// The `&` operator (bitwise and).
964 /// The `|` operator (bitwise or).
966 /// The `<<` operator (shift left).
968 /// The `>>` operator (shift right).
970 /// The `==` operator (equality).
972 /// The `<` operator (less than).
974 /// The `<=` operator (less than or equal to).
976 /// The `!=` operator (not equal to).
978 /// The `>=` operator (greater than or equal to).
980 /// The `>` operator (greater than).
985 pub fn as_str(self) -> &'static str {
987 BinOpKind::Add => "+",
988 BinOpKind::Sub => "-",
989 BinOpKind::Mul => "*",
990 BinOpKind::Div => "/",
991 BinOpKind::Rem => "%",
992 BinOpKind::And => "&&",
993 BinOpKind::Or => "||",
994 BinOpKind::BitXor => "^",
995 BinOpKind::BitAnd => "&",
996 BinOpKind::BitOr => "|",
997 BinOpKind::Shl => "<<",
998 BinOpKind::Shr => ">>",
999 BinOpKind::Eq => "==",
1000 BinOpKind::Lt => "<",
1001 BinOpKind::Le => "<=",
1002 BinOpKind::Ne => "!=",
1003 BinOpKind::Ge => ">=",
1004 BinOpKind::Gt => ">",
1008 pub fn is_lazy(self) -> bool {
1010 BinOpKind::And | BinOpKind::Or => true,
1015 pub fn is_shift(self) -> bool {
1017 BinOpKind::Shl | BinOpKind::Shr => true,
1022 pub fn is_comparison(self) -> bool {
1029 | BinOpKind::Ge => true,
1041 | BinOpKind::Shr => false,
1045 /// Returns `true` if the binary operator takes its arguments by value.
1046 pub fn is_by_value(self) -> bool {
1047 !self.is_comparison()
1051 impl Into<ast::BinOpKind> for BinOpKind {
1052 fn into(self) -> ast::BinOpKind {
1054 BinOpKind::Add => ast::BinOpKind::Add,
1055 BinOpKind::Sub => ast::BinOpKind::Sub,
1056 BinOpKind::Mul => ast::BinOpKind::Mul,
1057 BinOpKind::Div => ast::BinOpKind::Div,
1058 BinOpKind::Rem => ast::BinOpKind::Rem,
1059 BinOpKind::And => ast::BinOpKind::And,
1060 BinOpKind::Or => ast::BinOpKind::Or,
1061 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1062 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1063 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1064 BinOpKind::Shl => ast::BinOpKind::Shl,
1065 BinOpKind::Shr => ast::BinOpKind::Shr,
1066 BinOpKind::Eq => ast::BinOpKind::Eq,
1067 BinOpKind::Lt => ast::BinOpKind::Lt,
1068 BinOpKind::Le => ast::BinOpKind::Le,
1069 BinOpKind::Ne => ast::BinOpKind::Ne,
1070 BinOpKind::Ge => ast::BinOpKind::Ge,
1071 BinOpKind::Gt => ast::BinOpKind::Gt,
1076 pub type BinOp = Spanned<BinOpKind>;
1078 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1080 /// The `*` operator (deferencing).
1082 /// The `!` operator (logical negation).
1084 /// The `-` operator (negation).
1089 pub fn as_str(self) -> &'static str {
1091 Self::UnDeref => "*",
1097 /// Returns `true` if the unary operator takes its argument by value.
1098 pub fn is_by_value(self) -> bool {
1100 Self::UnNeg | Self::UnNot => true,
1107 #[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
1108 pub struct Stmt<'hir> {
1110 pub kind: StmtKind<'hir>,
1114 impl fmt::Debug for Stmt<'_> {
1115 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1120 print::to_string(print::NO_ANN, |s| s.print_stmt(self))
1125 /// The contents of a statement.
1126 #[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
1127 pub enum StmtKind<'hir> {
1128 /// A local (`let`) binding.
1129 Local(&'hir Local<'hir>),
1131 /// An item binding.
1134 /// An expression without a trailing semi-colon (must have unit type).
1135 Expr(&'hir Expr<'hir>),
1137 /// An expression with a trailing semi-colon (may have any type).
1138 Semi(&'hir Expr<'hir>),
1141 impl StmtKind<'hir> {
1142 pub fn attrs(&self) -> &'hir [Attribute] {
1144 StmtKind::Local(ref l) => &l.attrs,
1145 StmtKind::Item(_) => &[],
1146 StmtKind::Expr(ref e) | StmtKind::Semi(ref e) => &e.attrs,
1151 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1152 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1153 pub struct Local<'hir> {
1154 pub pat: &'hir Pat<'hir>,
1155 /// Type annotation, if any (otherwise the type will be inferred).
1156 pub ty: Option<&'hir Ty<'hir>>,
1157 /// Initializer expression to set the value, if any.
1158 pub init: Option<&'hir Expr<'hir>>,
1162 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1163 /// desugaring. Otherwise will be `Normal`.
1164 pub source: LocalSource,
1167 /// Represents a single arm of a `match` expression, e.g.
1168 /// `<pat> (if <guard>) => <body>`.
1169 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1170 pub struct Arm<'hir> {
1171 #[stable_hasher(ignore)]
1174 pub attrs: &'hir [Attribute],
1175 /// If this pattern and the optional guard matches, then `body` is evaluated.
1176 pub pat: &'hir Pat<'hir>,
1177 /// Optional guard clause.
1178 pub guard: Option<Guard<'hir>>,
1179 /// The expression the arm evaluates to if this arm matches.
1180 pub body: &'hir Expr<'hir>,
1183 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1184 pub enum Guard<'hir> {
1185 If(&'hir Expr<'hir>),
1188 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1189 pub struct Field<'hir> {
1190 #[stable_hasher(ignore)]
1193 pub expr: &'hir Expr<'hir>,
1195 pub is_shorthand: bool,
1198 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1199 pub enum BlockCheckMode {
1201 UnsafeBlock(UnsafeSource),
1202 PushUnsafeBlock(UnsafeSource),
1203 PopUnsafeBlock(UnsafeSource),
1206 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1207 pub enum UnsafeSource {
1212 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1217 /// The body of a function, closure, or constant value. In the case of
1218 /// a function, the body contains not only the function body itself
1219 /// (which is an expression), but also the argument patterns, since
1220 /// those are something that the caller doesn't really care about.
1225 /// fn foo((x, y): (u32, u32)) -> u32 {
1230 /// Here, the `Body` associated with `foo()` would contain:
1232 /// - an `params` array containing the `(x, y)` pattern
1233 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1234 /// - `generator_kind` would be `None`
1236 /// All bodies have an **owner**, which can be accessed via the HIR
1237 /// map using `body_owner_def_id()`.
1238 #[derive(RustcEncodable, RustcDecodable, Debug)]
1239 pub struct Body<'hir> {
1240 pub params: &'hir [Param<'hir>],
1241 pub value: Expr<'hir>,
1242 pub generator_kind: Option<GeneratorKind>,
1246 pub fn id(&self) -> BodyId {
1247 BodyId { hir_id: self.value.hir_id }
1250 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1255 /// The type of source expression that caused this generator to be created.
1256 #[derive(Clone, PartialEq, Eq, HashStable_Generic, RustcEncodable, RustcDecodable, Debug, Copy)]
1257 pub enum GeneratorKind {
1258 /// An explicit `async` block or the body of an async function.
1259 Async(AsyncGeneratorKind),
1261 /// A generator literal created via a `yield` inside a closure.
1265 impl fmt::Display for GeneratorKind {
1266 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1268 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1269 GeneratorKind::Gen => f.write_str("generator"),
1274 /// In the case of a generator created as part of an async construct,
1275 /// which kind of async construct caused it to be created?
1277 /// This helps error messages but is also used to drive coercions in
1278 /// type-checking (see #60424).
1279 #[derive(Clone, PartialEq, Eq, HashStable_Generic, RustcEncodable, RustcDecodable, Debug, Copy)]
1280 pub enum AsyncGeneratorKind {
1281 /// An explicit `async` block written by the user.
1284 /// An explicit `async` block written by the user.
1287 /// The `async` block generated as the body of an async function.
1291 impl fmt::Display for AsyncGeneratorKind {
1292 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1293 f.write_str(match self {
1294 AsyncGeneratorKind::Block => "`async` block",
1295 AsyncGeneratorKind::Closure => "`async` closure body",
1296 AsyncGeneratorKind::Fn => "`async fn` body",
1301 #[derive(Copy, Clone, Debug)]
1302 pub enum BodyOwnerKind {
1303 /// Functions and methods.
1309 /// Constants and associated constants.
1312 /// Initializer of a `static` item.
1316 impl BodyOwnerKind {
1317 pub fn is_fn_or_closure(self) -> bool {
1319 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1320 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1326 pub type Lit = Spanned<LitKind>;
1328 /// A constant (expression) that's not an item or associated item,
1329 /// but needs its own `DefId` for type-checking, const-eval, etc.
1330 /// These are usually found nested inside types (e.g., array lengths)
1331 /// or expressions (e.g., repeat counts), and also used to define
1332 /// explicit discriminant values for enum variants.
1333 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1334 pub struct AnonConst {
1340 #[derive(RustcEncodable, RustcDecodable)]
1341 pub struct Expr<'hir> {
1343 pub kind: ExprKind<'hir>,
1348 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1349 #[cfg(target_arch = "x86_64")]
1350 rustc_data_structures::static_assert_size!(Expr<'static>, 64);
1353 pub fn precedence(&self) -> ExprPrecedence {
1355 ExprKind::Box(_) => ExprPrecedence::Box,
1356 ExprKind::Array(_) => ExprPrecedence::Array,
1357 ExprKind::Call(..) => ExprPrecedence::Call,
1358 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1359 ExprKind::Tup(_) => ExprPrecedence::Tup,
1360 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1361 ExprKind::Unary(..) => ExprPrecedence::Unary,
1362 ExprKind::Lit(_) => ExprPrecedence::Lit,
1363 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1364 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1365 ExprKind::Loop(..) => ExprPrecedence::Loop,
1366 ExprKind::Match(..) => ExprPrecedence::Match,
1367 ExprKind::Closure(..) => ExprPrecedence::Closure,
1368 ExprKind::Block(..) => ExprPrecedence::Block,
1369 ExprKind::Assign(..) => ExprPrecedence::Assign,
1370 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1371 ExprKind::Field(..) => ExprPrecedence::Field,
1372 ExprKind::Index(..) => ExprPrecedence::Index,
1373 ExprKind::Path(..) => ExprPrecedence::Path,
1374 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1375 ExprKind::Break(..) => ExprPrecedence::Break,
1376 ExprKind::Continue(..) => ExprPrecedence::Continue,
1377 ExprKind::Ret(..) => ExprPrecedence::Ret,
1378 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1379 ExprKind::Struct(..) => ExprPrecedence::Struct,
1380 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1381 ExprKind::Yield(..) => ExprPrecedence::Yield,
1382 ExprKind::Err => ExprPrecedence::Err,
1386 // Whether this looks like a place expr, without checking for deref
1388 // This will return `true` in some potentially surprising cases such as
1389 // `CONSTANT.field`.
1390 pub fn is_syntactic_place_expr(&self) -> bool {
1391 self.is_place_expr(|_| true)
1394 // Whether this is a place expression.
1395 // `allow_projections_from` should return `true` if indexing a field or
1396 // index expression based on the given expression should be considered a
1397 // place expression.
1398 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1400 ExprKind::Path(QPath::Resolved(_, ref path)) => match path.res {
1401 Res::Local(..) | Res::Def(DefKind::Static, _) | Res::Err => true,
1405 // Type ascription inherits its place expression kind from its
1407 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1408 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1410 ExprKind::Unary(UnOp::UnDeref, _) => true,
1412 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1413 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1416 // Partially qualified paths in expressions can only legally
1417 // refer to associated items which are always rvalues.
1418 ExprKind::Path(QPath::TypeRelative(..))
1419 | ExprKind::Call(..)
1420 | ExprKind::MethodCall(..)
1421 | ExprKind::Struct(..)
1423 | ExprKind::Match(..)
1424 | ExprKind::Closure(..)
1425 | ExprKind::Block(..)
1426 | ExprKind::Repeat(..)
1427 | ExprKind::Array(..)
1428 | ExprKind::Break(..)
1429 | ExprKind::Continue(..)
1431 | ExprKind::Loop(..)
1432 | ExprKind::Assign(..)
1433 | ExprKind::InlineAsm(..)
1434 | ExprKind::AssignOp(..)
1436 | ExprKind::Unary(..)
1438 | ExprKind::AddrOf(..)
1439 | ExprKind::Binary(..)
1440 | ExprKind::Yield(..)
1441 | ExprKind::Cast(..)
1442 | ExprKind::DropTemps(..)
1443 | ExprKind::Err => false,
1447 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1448 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1449 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1450 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1451 /// beyond remembering to call this function before doing analysis on it.
1452 pub fn peel_drop_temps(&self) -> &Self {
1453 let mut expr = self;
1454 while let ExprKind::DropTemps(inner) = &expr.kind {
1461 impl fmt::Debug for Expr<'_> {
1462 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1467 print::to_string(print::NO_ANN, |s| s.print_expr(self))
1472 /// Checks if the specified expression is a built-in range literal.
1473 /// (See: `LoweringContext::lower_expr()`).
1475 /// FIXME(#60607): This function is a hack. If and when we have `QPath::Lang(...)`,
1476 /// we can use that instead as simpler, more reliable mechanism, as opposed to using `SourceMap`.
1477 pub fn is_range_literal(sm: &SourceMap, expr: &Expr<'_>) -> bool {
1478 // Returns whether the given path represents a (desugared) range,
1479 // either in std or core, i.e. has either a `::std::ops::Range` or
1480 // `::core::ops::Range` prefix.
1481 fn is_range_path(path: &Path<'_>) -> bool {
1482 let segs: Vec<_> = path.segments.iter().map(|seg| seg.ident.to_string()).collect();
1483 let segs: Vec<_> = segs.iter().map(|seg| &**seg).collect();
1485 // "{{root}}" is the equivalent of `::` prefix in `Path`.
1486 if let ["{{root}}", std_core, "ops", range] = segs.as_slice() {
1487 (*std_core == "std" || *std_core == "core") && range.starts_with("Range")
1493 // Check whether a span corresponding to a range expression is a
1494 // range literal, rather than an explicit struct or `new()` call.
1495 fn is_lit(sm: &SourceMap, span: &Span) -> bool {
1496 let end_point = sm.end_point(*span);
1498 if let Ok(end_string) = sm.span_to_snippet(end_point) {
1499 !(end_string.ends_with("}") || end_string.ends_with(")"))
1506 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1507 ExprKind::Struct(ref qpath, _, _) => {
1508 if let QPath::Resolved(None, ref path) = **qpath {
1509 return is_range_path(&path) && is_lit(sm, &expr.span);
1513 // `..` desugars to its struct path.
1514 ExprKind::Path(QPath::Resolved(None, ref path)) => {
1515 return is_range_path(&path) && is_lit(sm, &expr.span);
1518 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1519 ExprKind::Call(ref func, _) => {
1520 if let ExprKind::Path(QPath::TypeRelative(ref ty, ref segment)) = func.kind {
1521 if let TyKind::Path(QPath::Resolved(None, ref path)) = ty.kind {
1522 let new_call = segment.ident.name == sym::new;
1523 return is_range_path(&path) && is_lit(sm, &expr.span) && new_call;
1534 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1535 pub enum ExprKind<'hir> {
1536 /// A `box x` expression.
1537 Box(&'hir Expr<'hir>),
1538 /// An array (e.g., `[a, b, c, d]`).
1539 Array(&'hir [Expr<'hir>]),
1540 /// A function call.
1542 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1543 /// and the second field is the list of arguments.
1544 /// This also represents calling the constructor of
1545 /// tuple-like ADTs such as tuple structs and enum variants.
1546 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1547 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1549 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1550 /// (within the angle brackets).
1551 /// The first element of the vector of `Expr`s is the expression that evaluates
1552 /// to the object on which the method is being called on (the receiver),
1553 /// and the remaining elements are the rest of the arguments.
1554 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1555 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1557 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1558 /// the `hir_id` of the `MethodCall` node itself.
1560 /// [`type_dependent_def_id`]: ../ty/struct.TypeckTables.html#method.type_dependent_def_id
1561 MethodCall(&'hir PathSegment<'hir>, Span, &'hir [Expr<'hir>]),
1562 /// A tuple (e.g., `(a, b, c, d)`).
1563 Tup(&'hir [Expr<'hir>]),
1564 /// A binary operation (e.g., `a + b`, `a * b`).
1565 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1566 /// A unary operation (e.g., `!x`, `*x`).
1567 Unary(UnOp, &'hir Expr<'hir>),
1568 /// A literal (e.g., `1`, `"foo"`).
1570 /// A cast (e.g., `foo as f64`).
1571 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1572 /// A type reference (e.g., `Foo`).
1573 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1574 /// Wraps the expression in a terminating scope.
1575 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1577 /// This construct only exists to tweak the drop order in HIR lowering.
1578 /// An example of that is the desugaring of `for` loops.
1579 DropTemps(&'hir Expr<'hir>),
1580 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1582 /// I.e., `'label: loop { <block> }`.
1583 Loop(&'hir Block<'hir>, Option<Label>, LoopSource),
1584 /// A `match` block, with a source that indicates whether or not it is
1585 /// the result of a desugaring, and if so, which kind.
1586 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1587 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1589 /// The `Span` is the argument block `|...|`.
1591 /// This may also be a generator literal or an `async block` as indicated by the
1592 /// `Option<Movability>`.
1593 Closure(CaptureBy, &'hir FnDecl<'hir>, BodyId, Span, Option<Movability>),
1594 /// A block (e.g., `'label: { ... }`).
1595 Block(&'hir Block<'hir>, Option<Label>),
1597 /// An assignment (e.g., `a = foo()`).
1598 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1599 /// An assignment with an operator.
1602 AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1603 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1604 Field(&'hir Expr<'hir>, Ident),
1605 /// An indexing operation (`foo[2]`).
1606 Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1608 /// Path to a definition, possibly containing lifetime or type parameters.
1611 /// A referencing operation (i.e., `&a` or `&mut a`).
1612 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1613 /// A `break`, with an optional label to break.
1614 Break(Destination, Option<&'hir Expr<'hir>>),
1615 /// A `continue`, with an optional label.
1616 Continue(Destination),
1617 /// A `return`, with an optional value to be returned.
1618 Ret(Option<&'hir Expr<'hir>>),
1620 /// Inline assembly (from `asm!`), with its outputs and inputs.
1621 InlineAsm(&'hir InlineAsm<'hir>),
1623 /// A struct or struct-like variant literal expression.
1625 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1626 /// where `base` is the `Option<Expr>`.
1627 Struct(&'hir QPath<'hir>, &'hir [Field<'hir>], Option<&'hir Expr<'hir>>),
1629 /// An array literal constructed from one repeated element.
1631 /// E.g., `[1; 5]`. The first expression is the element
1632 /// to be repeated; the second is the number of times to repeat it.
1633 Repeat(&'hir Expr<'hir>, AnonConst),
1635 /// A suspension point for generators (i.e., `yield <expr>`).
1636 Yield(&'hir Expr<'hir>, YieldSource),
1638 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1642 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1644 /// To resolve the path to a `DefId`, call [`qpath_res`].
1646 /// [`qpath_res`]: ../ty/struct.TypeckTables.html#method.qpath_res
1647 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1648 pub enum QPath<'hir> {
1649 /// Path to a definition, optionally "fully-qualified" with a `Self`
1650 /// type, if the path points to an associated item in a trait.
1652 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1653 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1654 /// even though they both have the same two-segment `Clone::clone` `Path`.
1655 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
1657 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1658 /// Will be resolved by type-checking to an associated item.
1660 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1661 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1662 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1663 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
1666 /// Hints at the original code for a let statement.
1667 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1668 pub enum LocalSource {
1669 /// A `match _ { .. }`.
1671 /// A desugared `for _ in _ { .. }` loop.
1673 /// When lowering async functions, we create locals within the `async move` so that
1674 /// all parameters are dropped after the future is polled.
1676 /// ```ignore (pseudo-Rust)
1677 /// async fn foo(<pattern> @ x: Type) {
1679 /// let <pattern> = x;
1684 /// A desugared `<expr>.await`.
1688 /// Hints at the original code for a `match _ { .. }`.
1689 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1690 #[derive(HashStable_Generic)]
1691 pub enum MatchSource {
1692 /// A `match _ { .. }`.
1694 /// An `if _ { .. }` (optionally with `else { .. }`).
1695 IfDesugar { contains_else_clause: bool },
1696 /// An `if let _ = _ { .. }` (optionally with `else { .. }`).
1697 IfLetDesugar { contains_else_clause: bool },
1698 /// A `while _ { .. }` (which was desugared to a `loop { match _ { .. } }`).
1700 /// A `while let _ = _ { .. }` (which was desugared to a
1701 /// `loop { match _ { .. } }`).
1703 /// A desugared `for _ in _ { .. }` loop.
1705 /// A desugared `?` operator.
1707 /// A desugared `<expr>.await`.
1712 pub fn name(self) -> &'static str {
1716 IfDesugar { .. } | IfLetDesugar { .. } => "if",
1717 WhileDesugar | WhileLetDesugar => "while",
1718 ForLoopDesugar => "for",
1720 AwaitDesugar => ".await",
1725 /// The loop type that yielded an `ExprKind::Loop`.
1726 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1727 pub enum LoopSource {
1728 /// A `loop { .. }` loop.
1730 /// A `while _ { .. }` loop.
1732 /// A `while let _ = _ { .. }` loop.
1734 /// A `for _ in _ { .. }` loop.
1739 pub fn name(self) -> &'static str {
1741 LoopSource::Loop => "loop",
1742 LoopSource::While | LoopSource::WhileLet => "while",
1743 LoopSource::ForLoop => "for",
1748 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1749 pub enum LoopIdError {
1751 UnlabeledCfInWhileCondition,
1755 impl fmt::Display for LoopIdError {
1756 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1757 f.write_str(match self {
1758 LoopIdError::OutsideLoopScope => "not inside loop scope",
1759 LoopIdError::UnlabeledCfInWhileCondition => {
1760 "unlabeled control flow (break or continue) in while condition"
1762 LoopIdError::UnresolvedLabel => "label not found",
1767 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1768 pub struct Destination {
1769 // This is `Some(_)` iff there is an explicit user-specified `label
1770 pub label: Option<Label>,
1772 // These errors are caught and then reported during the diagnostics pass in
1773 // librustc_passes/loops.rs
1774 pub target_id: Result<HirId, LoopIdError>,
1777 /// The yield kind that caused an `ExprKind::Yield`.
1778 #[derive(Copy, Clone, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable, HashStable_Generic)]
1779 pub enum YieldSource {
1780 /// An `<expr>.await`.
1782 /// A plain `yield`.
1786 impl fmt::Display for YieldSource {
1787 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1788 f.write_str(match self {
1789 YieldSource::Await => "`await`",
1790 YieldSource::Yield => "`yield`",
1795 impl From<GeneratorKind> for YieldSource {
1796 fn from(kind: GeneratorKind) -> Self {
1798 // Guess based on the kind of the current generator.
1799 GeneratorKind::Gen => Self::Yield,
1800 GeneratorKind::Async(_) => Self::Await,
1805 // N.B., if you change this, you'll probably want to change the corresponding
1806 // type structure in middle/ty.rs as well.
1807 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1808 pub struct MutTy<'hir> {
1809 pub ty: &'hir Ty<'hir>,
1810 pub mutbl: Mutability,
1813 /// Represents a function's signature in a trait declaration,
1814 /// trait implementation, or a free function.
1815 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1816 pub struct FnSig<'hir> {
1817 pub header: FnHeader,
1818 pub decl: &'hir FnDecl<'hir>,
1821 // The bodies for items are stored "out of line", in a separate
1822 // hashmap in the `Crate`. Here we just record the node-id of the item
1823 // so it can fetched later.
1824 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1825 pub struct TraitItemId {
1829 /// Represents an item declaration within a trait declaration,
1830 /// possibly including a default implementation. A trait item is
1831 /// either required (meaning it doesn't have an implementation, just a
1832 /// signature) or provided (meaning it has a default implementation).
1833 #[derive(RustcEncodable, RustcDecodable, Debug)]
1834 pub struct TraitItem<'hir> {
1837 pub attrs: &'hir [Attribute],
1838 pub generics: Generics<'hir>,
1839 pub kind: TraitItemKind<'hir>,
1843 /// Represents a trait method's body (or just argument names).
1844 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1845 pub enum TraitMethod<'hir> {
1846 /// No default body in the trait, just a signature.
1847 Required(&'hir [Ident]),
1849 /// Both signature and body are provided in the trait.
1853 /// Represents a trait method or associated constant or type
1854 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1855 pub enum TraitItemKind<'hir> {
1856 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
1857 Const(&'hir Ty<'hir>, Option<BodyId>),
1858 /// A method with an optional body.
1859 Method(FnSig<'hir>, TraitMethod<'hir>),
1860 /// An associated type with (possibly empty) bounds and optional concrete
1862 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
1865 // The bodies for items are stored "out of line", in a separate
1866 // hashmap in the `Crate`. Here we just record the node-id of the item
1867 // so it can fetched later.
1868 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1869 pub struct ImplItemId {
1873 /// Represents anything within an `impl` block.
1874 #[derive(RustcEncodable, RustcDecodable, Debug)]
1875 pub struct ImplItem<'hir> {
1878 pub vis: Visibility<'hir>,
1879 pub defaultness: Defaultness,
1880 pub attrs: &'hir [Attribute],
1881 pub generics: Generics<'hir>,
1882 pub kind: ImplItemKind<'hir>,
1886 /// Represents various kinds of content within an `impl`.
1887 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1888 pub enum ImplItemKind<'hir> {
1889 /// An associated constant of the given type, set to the constant result
1890 /// of the expression.
1891 Const(&'hir Ty<'hir>, BodyId),
1892 /// A method implementation with the given signature and body.
1893 Method(FnSig<'hir>, BodyId),
1894 /// An associated type.
1895 TyAlias(&'hir Ty<'hir>),
1896 /// An associated `type = impl Trait`.
1897 OpaqueTy(GenericBounds<'hir>),
1900 impl ImplItemKind<'_> {
1901 pub fn namespace(&self) -> Namespace {
1903 ImplItemKind::OpaqueTy(..) | ImplItemKind::TyAlias(..) => Namespace::TypeNS,
1904 ImplItemKind::Const(..) | ImplItemKind::Method(..) => Namespace::ValueNS,
1909 // The name of the associated type for `Fn` return types.
1910 pub const FN_OUTPUT_NAME: Symbol = sym::Output;
1912 /// Bind a type to an associated type (i.e., `A = Foo`).
1914 /// Bindings like `A: Debug` are represented as a special type `A =
1915 /// $::Debug` that is understood by the astconv code.
1917 /// FIXME(alexreg): why have a separate type for the binding case,
1918 /// wouldn't it be better to make the `ty` field an enum like the
1922 /// enum TypeBindingKind {
1927 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1928 pub struct TypeBinding<'hir> {
1930 #[stable_hasher(project(name))]
1932 pub kind: TypeBindingKind<'hir>,
1936 // Represents the two kinds of type bindings.
1937 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1938 pub enum TypeBindingKind<'hir> {
1939 /// E.g., `Foo<Bar: Send>`.
1940 Constraint { bounds: &'hir [GenericBound<'hir>] },
1941 /// E.g., `Foo<Bar = ()>`.
1942 Equality { ty: &'hir Ty<'hir> },
1945 impl TypeBinding<'_> {
1946 pub fn ty(&self) -> &Ty<'_> {
1948 TypeBindingKind::Equality { ref ty } => ty,
1949 _ => panic!("expected equality type binding for parenthesized generic args"),
1954 #[derive(RustcEncodable, RustcDecodable)]
1955 pub struct Ty<'hir> {
1957 pub kind: TyKind<'hir>,
1961 impl fmt::Debug for Ty<'_> {
1962 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1963 write!(f, "type({})", print::to_string(print::NO_ANN, |s| s.print_type(self)))
1967 /// Not represented directly in the AST; referred to by name through a `ty_path`.
1968 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1969 #[derive(HashStable_Generic)]
1979 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1980 pub struct BareFnTy<'hir> {
1981 pub unsafety: Unsafety,
1983 pub generic_params: &'hir [GenericParam<'hir>],
1984 pub decl: &'hir FnDecl<'hir>,
1985 pub param_names: &'hir [Ident],
1988 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1989 pub struct OpaqueTy<'hir> {
1990 pub generics: Generics<'hir>,
1991 pub bounds: GenericBounds<'hir>,
1992 pub impl_trait_fn: Option<DefId>,
1993 pub origin: OpaqueTyOrigin,
1996 /// From whence the opaque type came.
1997 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1998 pub enum OpaqueTyOrigin {
1999 /// `type Foo = impl Trait;`
2005 /// Impl trait in bindings, consts, statics, bounds.
2009 /// The various kinds of types recognized by the compiler.
2010 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2011 pub enum TyKind<'hir> {
2012 /// A variable length slice (i.e., `[T]`).
2013 Slice(&'hir Ty<'hir>),
2014 /// A fixed length array (i.e., `[T; n]`).
2015 Array(&'hir Ty<'hir>, AnonConst),
2016 /// A raw pointer (i.e., `*const T` or `*mut T`).
2018 /// A reference (i.e., `&'a T` or `&'a mut T`).
2019 Rptr(Lifetime, MutTy<'hir>),
2020 /// A bare function (e.g., `fn(usize) -> bool`).
2021 BareFn(&'hir BareFnTy<'hir>),
2022 /// The never type (`!`).
2024 /// A tuple (`(A, B, C, D, ...)`).
2025 Tup(&'hir [Ty<'hir>]),
2026 /// A path to a type definition (`module::module::...::Type`), or an
2027 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2029 /// Type parameters may be stored in each `PathSegment`.
2031 /// A type definition itself. This is currently only used for the `type Foo = impl Trait`
2032 /// item that `impl Trait` in return position desugars to.
2034 /// The generic argument list contains the lifetimes (and in the future possibly parameters)
2035 /// that are actually bound on the `impl Trait`.
2036 Def(ItemId, &'hir [GenericArg<'hir>]),
2037 /// A trait object type `Bound1 + Bound2 + Bound3`
2038 /// where `Bound` is a trait or a lifetime.
2039 TraitObject(&'hir [PolyTraitRef<'hir>], Lifetime),
2042 /// `TyKind::Infer` means the type should be inferred instead of it having been
2043 /// specified. This can appear anywhere in a type.
2045 /// Placeholder for a type that has failed to be defined.
2049 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic, PartialEq)]
2050 pub struct InlineAsmOutput {
2051 pub constraint: Symbol,
2053 pub is_indirect: bool,
2057 // NOTE(eddyb) This is used within MIR as well, so unlike the rest of the HIR,
2058 // it needs to be `Clone` and use plain `Vec<T>` instead of arena-allocated slice.
2059 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic, PartialEq)]
2060 pub struct InlineAsmInner {
2062 pub asm_str_style: StrStyle,
2063 pub outputs: Vec<InlineAsmOutput>,
2064 pub inputs: Vec<Symbol>,
2065 pub clobbers: Vec<Symbol>,
2067 pub alignstack: bool,
2068 pub dialect: AsmDialect,
2071 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2072 pub struct InlineAsm<'hir> {
2073 pub inner: InlineAsmInner,
2074 pub outputs_exprs: &'hir [Expr<'hir>],
2075 pub inputs_exprs: &'hir [Expr<'hir>],
2078 /// Represents a parameter in a function header.
2079 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2080 pub struct Param<'hir> {
2081 pub attrs: &'hir [Attribute],
2083 pub pat: &'hir Pat<'hir>,
2087 /// Represents the header (not the body) of a function declaration.
2088 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2089 pub struct FnDecl<'hir> {
2090 /// The types of the function's parameters.
2092 /// Additional argument data is stored in the function's [body](Body::parameters).
2093 pub inputs: &'hir [Ty<'hir>],
2094 pub output: FnRetTy<'hir>,
2095 pub c_variadic: bool,
2096 /// Does the function have an implicit self?
2097 pub implicit_self: ImplicitSelfKind,
2100 /// Represents what type of implicit self a function has, if any.
2101 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2102 pub enum ImplicitSelfKind {
2103 /// Represents a `fn x(self);`.
2105 /// Represents a `fn x(mut self);`.
2107 /// Represents a `fn x(&self);`.
2109 /// Represents a `fn x(&mut self);`.
2111 /// Represents when a function does not have a self argument or
2112 /// when a function has a `self: X` argument.
2116 impl ImplicitSelfKind {
2117 /// Does this represent an implicit self?
2118 pub fn has_implicit_self(&self) -> bool {
2120 ImplicitSelfKind::None => false,
2126 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
2127 #[derive(HashStable_Generic)]
2133 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2134 pub enum Defaultness {
2135 Default { has_value: bool },
2140 pub fn has_value(&self) -> bool {
2142 Defaultness::Default { has_value, .. } => has_value,
2143 Defaultness::Final => true,
2147 pub fn is_final(&self) -> bool {
2148 *self == Defaultness::Final
2151 pub fn is_default(&self) -> bool {
2153 Defaultness::Default { .. } => true,
2159 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2160 pub enum FnRetTy<'hir> {
2161 /// Return type is not specified.
2163 /// Functions default to `()` and
2164 /// closures default to inference. Span points to where return
2165 /// type would be inserted.
2166 DefaultReturn(Span),
2167 /// Everything else.
2168 Return(&'hir Ty<'hir>),
2171 impl fmt::Display for FnRetTy<'_> {
2172 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2174 Self::Return(ref ty) => print::to_string(print::NO_ANN, |s| s.print_type(ty)).fmt(f),
2175 Self::DefaultReturn(_) => "()".fmt(f),
2181 pub fn span(&self) -> Span {
2183 Self::DefaultReturn(span) => span,
2184 Self::Return(ref ty) => ty.span,
2189 #[derive(RustcEncodable, RustcDecodable, Debug)]
2190 pub struct Mod<'hir> {
2191 /// A span from the first token past `{` to the last token until `}`.
2192 /// For `mod foo;`, the inner span ranges from the first token
2193 /// to the last token in the external file.
2195 pub item_ids: &'hir [ItemId],
2198 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2199 pub struct ForeignMod<'hir> {
2201 pub items: &'hir [ForeignItem<'hir>],
2204 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2205 pub struct GlobalAsm {
2209 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2210 pub struct EnumDef<'hir> {
2211 pub variants: &'hir [Variant<'hir>],
2214 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2215 pub struct Variant<'hir> {
2216 /// Name of the variant.
2217 #[stable_hasher(project(name))]
2219 /// Attributes of the variant.
2220 pub attrs: &'hir [Attribute],
2221 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2223 /// Fields and constructor id of the variant.
2224 pub data: VariantData<'hir>,
2225 /// Explicit discriminant (e.g., `Foo = 1`).
2226 pub disr_expr: Option<AnonConst>,
2231 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2233 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2234 /// Also produced for each element of a list `use`, e.g.
2235 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2238 /// Glob import, e.g., `use foo::*`.
2241 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2242 /// an additional `use foo::{}` for performing checks such as
2243 /// unstable feature gating. May be removed in the future.
2247 /// References to traits in impls.
2249 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2250 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2251 /// trait being referred to but just a unique `HirId` that serves as a key
2252 /// within the resolution map.
2253 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2254 pub struct TraitRef<'hir> {
2255 pub path: &'hir Path<'hir>,
2256 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2257 #[stable_hasher(ignore)]
2258 pub hir_ref_id: HirId,
2262 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2263 pub fn trait_def_id(&self) -> DefId {
2264 match self.path.res {
2265 Res::Def(DefKind::Trait, did) => did,
2266 Res::Def(DefKind::TraitAlias, did) => did,
2270 _ => unreachable!(),
2275 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2276 pub struct PolyTraitRef<'hir> {
2277 /// The `'a` in `for<'a> Foo<&'a T>`.
2278 pub bound_generic_params: &'hir [GenericParam<'hir>],
2280 /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
2281 pub trait_ref: TraitRef<'hir>,
2286 pub type Visibility<'hir> = Spanned<VisibilityKind<'hir>>;
2288 #[derive(RustcEncodable, RustcDecodable, Debug)]
2289 pub enum VisibilityKind<'hir> {
2292 Restricted { path: &'hir Path<'hir>, hir_id: HirId },
2296 impl VisibilityKind<'_> {
2297 pub fn is_pub(&self) -> bool {
2299 VisibilityKind::Public => true,
2304 pub fn is_pub_restricted(&self) -> bool {
2306 VisibilityKind::Public | VisibilityKind::Inherited => false,
2307 VisibilityKind::Crate(..) | VisibilityKind::Restricted { .. } => true,
2311 pub fn descr(&self) -> &'static str {
2313 VisibilityKind::Public => "public",
2314 VisibilityKind::Inherited => "private",
2315 VisibilityKind::Crate(..) => "crate-visible",
2316 VisibilityKind::Restricted { .. } => "restricted",
2321 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2322 pub struct StructField<'hir> {
2324 #[stable_hasher(project(name))]
2326 pub vis: Visibility<'hir>,
2328 pub ty: &'hir Ty<'hir>,
2329 pub attrs: &'hir [Attribute],
2332 impl StructField<'_> {
2333 // Still necessary in couple of places
2334 pub fn is_positional(&self) -> bool {
2335 let first = self.ident.as_str().as_bytes()[0];
2336 first >= b'0' && first <= b'9'
2340 /// Fields and constructor IDs of enum variants and structs.
2341 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2342 pub enum VariantData<'hir> {
2343 /// A struct variant.
2345 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2346 Struct(&'hir [StructField<'hir>], /* recovered */ bool),
2347 /// A tuple variant.
2349 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2350 Tuple(&'hir [StructField<'hir>], HirId),
2353 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2357 impl VariantData<'hir> {
2358 /// Return the fields of this variant.
2359 pub fn fields(&self) -> &'hir [StructField<'hir>] {
2361 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2366 /// Return the `HirId` of this variant's constructor, if it has one.
2367 pub fn ctor_hir_id(&self) -> Option<HirId> {
2369 VariantData::Struct(_, _) => None,
2370 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2375 // The bodies for items are stored "out of line", in a separate
2376 // hashmap in the `Crate`. Here we just record the node-id of the item
2377 // so it can fetched later.
2378 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2385 /// The name might be a dummy name in case of anonymous items
2386 #[derive(RustcEncodable, RustcDecodable, Debug)]
2387 pub struct Item<'hir> {
2390 pub attrs: &'hir [Attribute],
2391 pub kind: ItemKind<'hir>,
2392 pub vis: Visibility<'hir>,
2396 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2397 #[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
2404 pub fn prefix_str(&self) -> &'static str {
2406 Self::Unsafe => "unsafe ",
2412 impl fmt::Display for Unsafety {
2413 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2414 f.write_str(match *self {
2415 Self::Unsafe => "unsafe",
2416 Self::Normal => "normal",
2421 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2422 #[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
2423 pub enum Constness {
2428 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2429 pub struct FnHeader {
2430 pub unsafety: Unsafety,
2431 pub constness: Constness,
2432 pub asyncness: IsAsync,
2437 pub fn is_const(&self) -> bool {
2438 match &self.constness {
2439 Constness::Const => true,
2445 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2446 pub enum ItemKind<'hir> {
2447 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2449 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2450 ExternCrate(Option<Name>),
2452 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2456 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2457 Use(&'hir Path<'hir>, UseKind),
2459 /// A `static` item.
2460 Static(&'hir Ty<'hir>, Mutability, BodyId),
2462 Const(&'hir Ty<'hir>, BodyId),
2463 /// A function declaration.
2464 Fn(FnSig<'hir>, Generics<'hir>, BodyId),
2467 /// An external module, e.g. `extern { .. }`.
2468 ForeignMod(ForeignMod<'hir>),
2469 /// Module-level inline assembly (from `global_asm!`).
2470 GlobalAsm(&'hir GlobalAsm),
2471 /// A type alias, e.g., `type Foo = Bar<u8>`.
2472 TyAlias(&'hir Ty<'hir>, Generics<'hir>),
2473 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2474 OpaqueTy(OpaqueTy<'hir>),
2475 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2476 Enum(EnumDef<'hir>, Generics<'hir>),
2477 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2478 Struct(VariantData<'hir>, Generics<'hir>),
2479 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2480 Union(VariantData<'hir>, Generics<'hir>),
2481 /// A trait definition.
2482 Trait(IsAuto, Unsafety, Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
2484 TraitAlias(Generics<'hir>, GenericBounds<'hir>),
2486 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2489 polarity: ImplPolarity,
2490 defaultness: Defaultness,
2491 constness: Constness,
2492 generics: Generics<'hir>,
2494 /// The trait being implemented, if any.
2495 of_trait: Option<TraitRef<'hir>>,
2497 self_ty: &'hir Ty<'hir>,
2498 items: &'hir [ImplItemRef<'hir>],
2503 pub fn descriptive_variant(&self) -> &str {
2505 ItemKind::ExternCrate(..) => "extern crate",
2506 ItemKind::Use(..) => "use",
2507 ItemKind::Static(..) => "static item",
2508 ItemKind::Const(..) => "constant item",
2509 ItemKind::Fn(..) => "function",
2510 ItemKind::Mod(..) => "module",
2511 ItemKind::ForeignMod(..) => "foreign module",
2512 ItemKind::GlobalAsm(..) => "global asm",
2513 ItemKind::TyAlias(..) => "type alias",
2514 ItemKind::OpaqueTy(..) => "opaque type",
2515 ItemKind::Enum(..) => "enum",
2516 ItemKind::Struct(..) => "struct",
2517 ItemKind::Union(..) => "union",
2518 ItemKind::Trait(..) => "trait",
2519 ItemKind::TraitAlias(..) => "trait alias",
2520 ItemKind::Impl { .. } => "impl",
2524 pub fn generics(&self) -> Option<&Generics<'_>> {
2526 ItemKind::Fn(_, ref generics, _)
2527 | ItemKind::TyAlias(_, ref generics)
2528 | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
2529 | ItemKind::Enum(_, ref generics)
2530 | ItemKind::Struct(_, ref generics)
2531 | ItemKind::Union(_, ref generics)
2532 | ItemKind::Trait(_, _, ref generics, _, _)
2533 | ItemKind::Impl { ref generics, .. } => generics,
2539 /// A reference from an trait to one of its associated items. This
2540 /// contains the item's id, naturally, but also the item's name and
2541 /// some other high-level details (like whether it is an associated
2542 /// type or method, and whether it is public). This allows other
2543 /// passes to find the impl they want without loading the ID (which
2544 /// means fewer edges in the incremental compilation graph).
2545 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2546 pub struct TraitItemRef {
2547 pub id: TraitItemId,
2548 #[stable_hasher(project(name))]
2550 pub kind: AssocItemKind,
2552 pub defaultness: Defaultness,
2555 /// A reference from an impl to one of its associated items. This
2556 /// contains the item's ID, naturally, but also the item's name and
2557 /// some other high-level details (like whether it is an associated
2558 /// type or method, and whether it is public). This allows other
2559 /// passes to find the impl they want without loading the ID (which
2560 /// means fewer edges in the incremental compilation graph).
2561 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2562 pub struct ImplItemRef<'hir> {
2564 #[stable_hasher(project(name))]
2566 pub kind: AssocItemKind,
2568 pub vis: Visibility<'hir>,
2569 pub defaultness: Defaultness,
2572 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2573 pub enum AssocItemKind {
2575 Method { has_self: bool },
2580 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2581 pub struct ForeignItem<'hir> {
2582 #[stable_hasher(project(name))]
2584 pub attrs: &'hir [Attribute],
2585 pub kind: ForeignItemKind<'hir>,
2588 pub vis: Visibility<'hir>,
2591 /// An item within an `extern` block.
2592 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2593 pub enum ForeignItemKind<'hir> {
2594 /// A foreign function.
2595 Fn(&'hir FnDecl<'hir>, &'hir [Ident], Generics<'hir>),
2596 /// A foreign static item (`static ext: u8`).
2597 Static(&'hir Ty<'hir>, Mutability),
2602 impl ForeignItemKind<'hir> {
2603 pub fn descriptive_variant(&self) -> &str {
2605 ForeignItemKind::Fn(..) => "foreign function",
2606 ForeignItemKind::Static(..) => "foreign static item",
2607 ForeignItemKind::Type => "foreign type",
2612 /// A variable captured by a closure.
2613 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable, HashStable_Generic)]
2615 // First span where it is accessed (there can be multiple).
2619 pub type CaptureModeMap = NodeMap<CaptureBy>;
2621 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2622 // has length > 0 if the trait is found through an chain of imports, starting with the
2623 // import/use statement in the scope where the trait is used.
2624 #[derive(Clone, Debug)]
2625 pub struct TraitCandidate<ID = HirId> {
2627 pub import_ids: SmallVec<[ID; 1]>,
2630 impl<ID> TraitCandidate<ID> {
2631 pub fn map_import_ids<F, T>(self, f: F) -> TraitCandidate<T>
2635 let TraitCandidate { def_id, import_ids } = self;
2636 let import_ids = import_ids.into_iter().map(f).collect();
2637 TraitCandidate { def_id, import_ids }
2641 // Trait method resolution
2642 pub type TraitMap<ID = HirId> = NodeMap<Vec<TraitCandidate<ID>>>;
2644 // Map from the NodeId of a glob import to a list of items which are actually
2646 pub type GlobMap = NodeMap<FxHashSet<Name>>;
2648 #[derive(Copy, Clone, Debug)]
2649 pub enum Node<'hir> {
2650 Param(&'hir Param<'hir>),
2651 Item(&'hir Item<'hir>),
2652 ForeignItem(&'hir ForeignItem<'hir>),
2653 TraitItem(&'hir TraitItem<'hir>),
2654 ImplItem(&'hir ImplItem<'hir>),
2655 Variant(&'hir Variant<'hir>),
2656 Field(&'hir StructField<'hir>),
2657 AnonConst(&'hir AnonConst),
2658 Expr(&'hir Expr<'hir>),
2659 Stmt(&'hir Stmt<'hir>),
2660 PathSegment(&'hir PathSegment<'hir>),
2662 TraitRef(&'hir TraitRef<'hir>),
2663 Binding(&'hir Pat<'hir>),
2664 Pat(&'hir Pat<'hir>),
2665 Arm(&'hir Arm<'hir>),
2666 Block(&'hir Block<'hir>),
2667 Local(&'hir Local<'hir>),
2668 MacroDef(&'hir MacroDef<'hir>),
2670 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
2671 /// with synthesized constructors.
2672 Ctor(&'hir VariantData<'hir>),
2674 Lifetime(&'hir Lifetime),
2675 GenericParam(&'hir GenericParam<'hir>),
2676 Visibility(&'hir Visibility<'hir>),
2682 pub fn ident(&self) -> Option<Ident> {
2684 Node::TraitItem(TraitItem { ident, .. })
2685 | Node::ImplItem(ImplItem { ident, .. })
2686 | Node::ForeignItem(ForeignItem { ident, .. })
2687 | Node::Item(Item { ident, .. }) => Some(*ident),
2692 pub fn fn_decl(&self) -> Option<&FnDecl<'_>> {
2694 Node::TraitItem(TraitItem { kind: TraitItemKind::Method(fn_sig, _), .. })
2695 | Node::ImplItem(ImplItem { kind: ImplItemKind::Method(fn_sig, _), .. })
2696 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
2697 Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
2704 pub fn generics(&self) -> Option<&Generics<'_>> {
2706 Node::TraitItem(TraitItem { generics, .. })
2707 | Node::ImplItem(ImplItem { generics, .. })
2708 | Node::Item(Item { kind: ItemKind::Fn(_, generics, _), .. }) => Some(generics),