1 use crate::def::{DefKind, Res};
2 use crate::def_id::DefId;
3 crate use crate::hir_id::HirId;
4 use crate::itemlikevisit;
7 crate use BlockCheckMode::*;
8 crate use FunctionRetTy::*;
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_session::node_id::NodeMap;
16 use rustc_span::source_map::{SourceMap, Spanned};
17 use rustc_span::symbol::{kw, sym, Symbol};
18 use rustc_span::{MultiSpan, Span, DUMMY_SP};
19 use rustc_target::spec::abi::Abi;
20 use smallvec::SmallVec;
21 use std::collections::{BTreeMap, BTreeSet};
23 use syntax::ast::{self, AsmDialect, CrateSugar, Ident, Name, NodeId};
24 use syntax::ast::{AttrVec, Attribute, FloatTy, IntTy, Label, LitKind, StrStyle, UintTy};
25 pub use syntax::ast::{BorrowKind, ImplPolarity, IsAuto};
26 pub use syntax::ast::{CaptureBy, Constness, Movability, Mutability, Unsafety};
27 use syntax::tokenstream::TokenStream;
28 use syntax::util::parser::ExprPrecedence;
30 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, HashStable_Generic)]
35 /// Either "`'a`", referring to a named lifetime definition,
36 /// or "``" (i.e., `kw::Invalid`), for elision placeholders.
38 /// HIR lowering inserts these placeholders in type paths that
39 /// refer to type definitions needing lifetime parameters,
40 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
41 pub name: LifetimeName,
44 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
45 #[derive(HashStable_Generic)]
47 /// Some user-given name like `T` or `'x`.
50 /// Synthetic name generated when user elided a lifetime in an impl header.
52 /// E.g., the lifetimes in cases like these:
55 /// impl Foo<'_> for u32
57 /// in that case, we rewrite to
59 /// impl<'f> Foo for &'f u32
60 /// impl<'f> Foo<'f> for u32
62 /// where `'f` is something like `Fresh(0)`. The indices are
63 /// unique per impl, but not necessarily continuous.
66 /// Indicates an illegal name was given and an error has been
67 /// reported (so we should squelch other derived errors). Occurs
68 /// when, e.g., `'_` is used in the wrong place.
73 pub fn ident(&self) -> Ident {
75 ParamName::Plain(ident) => ident,
76 ParamName::Fresh(_) | ParamName::Error => {
77 Ident::with_dummy_span(kw::UnderscoreLifetime)
82 pub fn modern(&self) -> ParamName {
84 ParamName::Plain(ident) => ParamName::Plain(ident.modern()),
85 param_name => param_name,
90 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
91 #[derive(HashStable_Generic)]
92 pub enum LifetimeName {
93 /// User-given names or fresh (synthetic) names.
96 /// User wrote nothing (e.g., the lifetime in `&u32`).
99 /// Implicit lifetime in a context like `dyn Foo`. This is
100 /// distinguished from implicit lifetimes elsewhere because the
101 /// lifetime that they default to must appear elsewhere within the
102 /// enclosing type. This means that, in an `impl Trait` context, we
103 /// don't have to create a parameter for them. That is, `impl
104 /// Trait<Item = &u32>` expands to an opaque type like `type
105 /// Foo<'a> = impl Trait<Item = &'a u32>`, but `impl Trait<item =
106 /// dyn Bar>` expands to `type Foo = impl Trait<Item = dyn Bar +
107 /// 'static>`. The latter uses `ImplicitObjectLifetimeDefault` so
108 /// that surrounding code knows not to create a lifetime
110 ImplicitObjectLifetimeDefault,
112 /// Indicates an error during lowering (usually `'_` in wrong place)
113 /// that was already reported.
116 /// User wrote specifies `'_`.
119 /// User wrote `'static`.
124 pub fn ident(&self) -> Ident {
126 LifetimeName::ImplicitObjectLifetimeDefault
127 | LifetimeName::Implicit
128 | LifetimeName::Error => Ident::invalid(),
129 LifetimeName::Underscore => Ident::with_dummy_span(kw::UnderscoreLifetime),
130 LifetimeName::Static => Ident::with_dummy_span(kw::StaticLifetime),
131 LifetimeName::Param(param_name) => param_name.ident(),
135 pub fn is_elided(&self) -> bool {
137 LifetimeName::ImplicitObjectLifetimeDefault
138 | LifetimeName::Implicit
139 | LifetimeName::Underscore => true,
141 // It might seem surprising that `Fresh(_)` counts as
142 // *not* elided -- but this is because, as far as the code
143 // in the compiler is concerned -- `Fresh(_)` variants act
144 // equivalently to "some fresh name". They correspond to
145 // early-bound regions on an impl, in other words.
146 LifetimeName::Error | LifetimeName::Param(_) | LifetimeName::Static => false,
150 fn is_static(&self) -> bool {
151 self == &LifetimeName::Static
154 pub fn modern(&self) -> LifetimeName {
156 LifetimeName::Param(param_name) => LifetimeName::Param(param_name.modern()),
157 lifetime_name => lifetime_name,
162 impl fmt::Display for Lifetime {
163 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
164 self.name.ident().fmt(f)
168 impl fmt::Debug for Lifetime {
169 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
174 print::to_string(print::NO_ANN, |s| s.print_lifetime(self))
180 pub fn is_elided(&self) -> bool {
181 self.name.is_elided()
184 pub fn is_static(&self) -> bool {
185 self.name.is_static()
189 /// A `Path` is essentially Rust's notion of a name; for instance,
190 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
191 /// along with a bunch of supporting information.
192 #[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
193 pub struct Path<'hir> {
195 /// The resolution for the path.
197 /// The segments in the path: the things separated by `::`.
198 pub segments: &'hir [PathSegment<'hir>],
202 pub fn is_global(&self) -> bool {
203 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
207 impl fmt::Debug for Path<'_> {
208 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
209 write!(f, "path({})", self)
213 impl fmt::Display for Path<'_> {
214 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
215 write!(f, "{}", print::to_string(print::NO_ANN, |s| s.print_path(self, false)))
219 /// A segment of a path: an identifier, an optional lifetime, and a set of
221 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
222 pub struct PathSegment<'hir> {
223 /// The identifier portion of this path segment.
224 #[stable_hasher(project(name))]
226 // `id` and `res` are optional. We currently only use these in save-analysis,
227 // any path segments without these will not have save-analysis info and
228 // therefore will not have 'jump to def' in IDEs, but otherwise will not be
229 // affected. (In general, we don't bother to get the defs for synthesized
230 // segments, only for segments which have come from the AST).
231 pub hir_id: Option<HirId>,
232 pub res: Option<Res>,
234 /// Type/lifetime parameters attached to this path. They come in
235 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
236 /// this is more than just simple syntactic sugar; the use of
237 /// parens affects the region binding rules, so we preserve the
239 pub args: Option<&'hir GenericArgs<'hir>>,
241 /// Whether to infer remaining type parameters, if any.
242 /// This only applies to expression and pattern paths, and
243 /// out of those only the segments with no type parameters
244 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
245 pub infer_args: bool,
248 impl<'hir> PathSegment<'hir> {
249 /// Converts an identifier to the corresponding segment.
250 pub fn from_ident(ident: Ident) -> PathSegment<'hir> {
251 PathSegment { ident, hir_id: None, res: None, infer_args: true, args: None }
254 pub fn generic_args(&self) -> &GenericArgs<'hir> {
255 if let Some(ref args) = self.args {
258 const DUMMY: &GenericArgs<'_> = &GenericArgs::none();
264 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
265 pub struct ConstArg {
266 pub value: AnonConst,
270 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
271 pub enum GenericArg<'hir> {
277 impl GenericArg<'_> {
278 pub fn span(&self) -> Span {
280 GenericArg::Lifetime(l) => l.span,
281 GenericArg::Type(t) => t.span,
282 GenericArg::Const(c) => c.span,
286 pub fn id(&self) -> HirId {
288 GenericArg::Lifetime(l) => l.hir_id,
289 GenericArg::Type(t) => t.hir_id,
290 GenericArg::Const(c) => c.value.hir_id,
294 pub fn is_const(&self) -> bool {
296 GenericArg::Const(_) => true,
302 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
303 pub struct GenericArgs<'hir> {
304 /// The generic arguments for this path segment.
305 pub args: &'hir [GenericArg<'hir>],
306 /// Bindings (equality constraints) on associated types, if present.
307 /// E.g., `Foo<A = Bar>`.
308 pub bindings: &'hir [TypeBinding<'hir>],
309 /// Were arguments written in parenthesized form `Fn(T) -> U`?
310 /// This is required mostly for pretty-printing and diagnostics,
311 /// but also for changing lifetime elision rules to be "function-like".
312 pub parenthesized: bool,
315 impl GenericArgs<'_> {
316 pub const fn none() -> Self {
317 Self { args: &[], bindings: &[], parenthesized: false }
320 pub fn is_empty(&self) -> bool {
321 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
324 pub fn inputs(&self) -> &[Ty<'_>] {
325 if self.parenthesized {
326 for arg in self.args {
328 GenericArg::Lifetime(_) => {}
329 GenericArg::Type(ref ty) => {
330 if let TyKind::Tup(ref tys) = ty.kind {
335 GenericArg::Const(_) => {}
339 panic!("GenericArgs::inputs: not a `Fn(T) -> U`");
342 pub fn own_counts(&self) -> GenericParamCount {
343 // We could cache this as a property of `GenericParamCount`, but
344 // the aim is to refactor this away entirely eventually and the
345 // presence of this method will be a constant reminder.
346 let mut own_counts: GenericParamCount = Default::default();
348 for arg in self.args {
350 GenericArg::Lifetime(_) => own_counts.lifetimes += 1,
351 GenericArg::Type(_) => own_counts.types += 1,
352 GenericArg::Const(_) => own_counts.consts += 1,
360 /// A modifier on a bound, currently this is only used for `?Sized`, where the
361 /// modifier is `Maybe`. Negative bounds should also be handled here.
362 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
363 #[derive(HashStable_Generic)]
364 pub enum TraitBoundModifier {
370 /// The AST represents all type param bounds as types.
371 /// `typeck::collect::compute_bounds` matches these against
372 /// the "special" built-in traits (see `middle::lang_items`) and
373 /// detects `Copy`, `Send` and `Sync`.
374 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
375 pub enum GenericBound<'hir> {
376 Trait(PolyTraitRef<'hir>, TraitBoundModifier),
380 impl GenericBound<'_> {
381 pub fn trait_def_id(&self) -> Option<DefId> {
383 GenericBound::Trait(data, _) => Some(data.trait_ref.trait_def_id()),
388 pub fn span(&self) -> Span {
390 &GenericBound::Trait(ref t, ..) => t.span,
391 &GenericBound::Outlives(ref l) => l.span,
396 pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
398 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
399 pub enum LifetimeParamKind {
400 // Indicates that the lifetime definition was explicitly declared (e.g., in
401 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
404 // Indicates that the lifetime definition was synthetically added
405 // as a result of an in-band lifetime usage (e.g., in
406 // `fn foo(x: &'a u8) -> &'a u8 { x }`).
409 // Indication that the lifetime was elided (e.g., in both cases in
410 // `fn foo(x: &u8) -> &'_ u8 { x }`).
413 // Indication that the lifetime name was somehow in error.
417 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
418 pub enum GenericParamKind<'hir> {
419 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
421 kind: LifetimeParamKind,
424 default: Option<&'hir Ty<'hir>>,
425 synthetic: Option<SyntheticTyParamKind>,
432 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
433 pub struct GenericParam<'hir> {
436 pub attrs: &'hir [Attribute],
437 pub bounds: GenericBounds<'hir>,
439 pub pure_wrt_drop: bool,
440 pub kind: GenericParamKind<'hir>,
444 pub struct GenericParamCount {
445 pub lifetimes: usize,
450 /// Represents lifetimes and type parameters attached to a declaration
451 /// of a function, enum, trait, etc.
452 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
453 pub struct Generics<'hir> {
454 pub params: &'hir [GenericParam<'hir>],
455 pub where_clause: WhereClause<'hir>,
459 impl Generics<'hir> {
460 pub const fn empty() -> Generics<'hir> {
463 where_clause: WhereClause { predicates: &[], span: DUMMY_SP },
468 pub fn own_counts(&self) -> GenericParamCount {
469 // We could cache this as a property of `GenericParamCount`, but
470 // the aim is to refactor this away entirely eventually and the
471 // presence of this method will be a constant reminder.
472 let mut own_counts: GenericParamCount = Default::default();
474 for param in self.params {
476 GenericParamKind::Lifetime { .. } => own_counts.lifetimes += 1,
477 GenericParamKind::Type { .. } => own_counts.types += 1,
478 GenericParamKind::Const { .. } => own_counts.consts += 1,
485 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'_>> {
486 for param in self.params {
487 if name == param.name.ident().name {
494 pub fn spans(&self) -> MultiSpan {
495 if self.params.is_empty() {
498 self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
503 /// Synthetic type parameters are converted to another form during lowering; this allows
504 /// us to track the original form they had, and is useful for error messages.
505 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
506 #[derive(HashStable_Generic)]
507 pub enum SyntheticTyParamKind {
511 /// A where-clause in a definition.
512 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
513 pub struct WhereClause<'hir> {
514 pub predicates: &'hir [WherePredicate<'hir>],
515 // Only valid if predicates isn't empty.
519 impl WhereClause<'_> {
520 pub fn span(&self) -> Option<Span> {
521 if self.predicates.is_empty() { None } else { Some(self.span) }
524 /// The `WhereClause` under normal circumstances points at either the predicates or the empty
525 /// space where the `where` clause should be. Only of use for diagnostic suggestions.
526 pub fn span_for_predicates_or_empty_place(&self) -> Span {
531 /// A single predicate in a where-clause.
532 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
533 pub enum WherePredicate<'hir> {
534 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
535 BoundPredicate(WhereBoundPredicate<'hir>),
536 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
537 RegionPredicate(WhereRegionPredicate<'hir>),
538 /// An equality predicate (unsupported).
539 EqPredicate(WhereEqPredicate<'hir>),
542 impl WherePredicate<'_> {
543 pub fn span(&self) -> Span {
545 &WherePredicate::BoundPredicate(ref p) => p.span,
546 &WherePredicate::RegionPredicate(ref p) => p.span,
547 &WherePredicate::EqPredicate(ref p) => p.span,
552 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
553 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
554 pub struct WhereBoundPredicate<'hir> {
556 /// Any generics from a `for` binding.
557 pub bound_generic_params: &'hir [GenericParam<'hir>],
558 /// The type being bounded.
559 pub bounded_ty: &'hir Ty<'hir>,
560 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
561 pub bounds: GenericBounds<'hir>,
564 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
565 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
566 pub struct WhereRegionPredicate<'hir> {
568 pub lifetime: Lifetime,
569 pub bounds: GenericBounds<'hir>,
572 /// An equality predicate (e.g., `T = int`); currently unsupported.
573 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
574 pub struct WhereEqPredicate<'hir> {
577 pub lhs_ty: &'hir Ty<'hir>,
578 pub rhs_ty: &'hir Ty<'hir>,
581 #[derive(RustcEncodable, RustcDecodable, Debug)]
582 pub struct ModuleItems {
583 // Use BTreeSets here so items are in the same order as in the
584 // list of all items in Crate
585 pub items: BTreeSet<HirId>,
586 pub trait_items: BTreeSet<TraitItemId>,
587 pub impl_items: BTreeSet<ImplItemId>,
590 /// The top-level data structure that stores the entire contents of
591 /// the crate currently being compiled.
593 /// For more details, see the [rustc guide].
595 /// [rustc guide]: https://rust-lang.github.io/rustc-guide/hir.html
596 #[derive(RustcEncodable, RustcDecodable, Debug)]
597 pub struct Crate<'hir> {
598 pub module: Mod<'hir>,
599 pub attrs: &'hir [Attribute],
601 pub exported_macros: &'hir [MacroDef<'hir>],
602 // Attributes from non-exported macros, kept only for collecting the library feature list.
603 pub non_exported_macro_attrs: &'hir [Attribute],
605 // N.B., we use a `BTreeMap` here so that `visit_all_items` iterates
606 // over the ids in increasing order. In principle it should not
607 // matter what order we visit things in, but in *practice* it
608 // does, because it can affect the order in which errors are
609 // detected, which in turn can make compile-fail tests yield
610 // slightly different results.
611 pub items: BTreeMap<HirId, Item<'hir>>,
613 pub trait_items: BTreeMap<TraitItemId, TraitItem<'hir>>,
614 pub impl_items: BTreeMap<ImplItemId, ImplItem<'hir>>,
615 pub bodies: BTreeMap<BodyId, Body<'hir>>,
616 pub trait_impls: BTreeMap<DefId, Vec<HirId>>,
618 /// A list of the body ids written out in the order in which they
619 /// appear in the crate. If you're going to process all the bodies
620 /// in the crate, you should iterate over this list rather than the keys
622 pub body_ids: Vec<BodyId>,
624 /// A list of modules written out in the order in which they
625 /// appear in the crate. This includes the main crate module.
626 pub modules: BTreeMap<HirId, ModuleItems>,
630 pub fn item(&self, id: HirId) -> &Item<'hir> {
634 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem<'hir> {
635 &self.trait_items[&id]
638 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem<'hir> {
639 &self.impl_items[&id]
642 pub fn body(&self, id: BodyId) -> &Body<'hir> {
648 /// Visits all items in the crate in some deterministic (but
649 /// unspecified) order. If you just need to process every item,
650 /// but don't care about nesting, this method is the best choice.
652 /// If you do care about nesting -- usually because your algorithm
653 /// follows lexical scoping rules -- then you want a different
654 /// approach. You should override `visit_nested_item` in your
655 /// visitor and then call `intravisit::walk_crate` instead.
656 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
658 V: itemlikevisit::ItemLikeVisitor<'hir>,
660 for (_, item) in &self.items {
661 visitor.visit_item(item);
664 for (_, trait_item) in &self.trait_items {
665 visitor.visit_trait_item(trait_item);
668 for (_, impl_item) in &self.impl_items {
669 visitor.visit_impl_item(impl_item);
673 /// A parallel version of `visit_all_item_likes`.
674 pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
676 V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send,
680 par_for_each_in(&self.items, |(_, item)| {
681 visitor.visit_item(item);
685 par_for_each_in(&self.trait_items, |(_, trait_item)| {
686 visitor.visit_trait_item(trait_item);
690 par_for_each_in(&self.impl_items, |(_, impl_item)| {
691 visitor.visit_impl_item(impl_item);
698 /// A macro definition, in this crate or imported from another.
700 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
701 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
702 pub struct MacroDef<'hir> {
704 pub vis: Visibility<'hir>,
705 pub attrs: &'hir [Attribute],
708 pub body: TokenStream,
712 /// A block of statements `{ .. }`, which may have a label (in this case the
713 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
714 /// the `rules` being anything but `DefaultBlock`.
715 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
716 pub struct Block<'hir> {
717 /// Statements in a block.
718 pub stmts: &'hir [Stmt<'hir>],
719 /// An expression at the end of the block
720 /// without a semicolon, if any.
721 pub expr: Option<&'hir Expr<'hir>>,
722 #[stable_hasher(ignore)]
724 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
725 pub rules: BlockCheckMode,
727 /// If true, then there may exist `break 'a` values that aim to
728 /// break out of this block early.
729 /// Used by `'label: {}` blocks and by `try {}` blocks.
730 pub targeted_by_break: bool,
733 #[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
734 pub struct Pat<'hir> {
735 #[stable_hasher(ignore)]
737 pub kind: PatKind<'hir>,
741 impl fmt::Debug for Pat<'_> {
742 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
747 print::to_string(print::NO_ANN, |s| s.print_pat(self))
753 // FIXME(#19596) this is a workaround, but there should be a better way
754 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'_>) -> bool) -> bool {
761 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
762 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
763 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
764 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
765 Slice(before, slice, after) => {
766 before.iter().chain(slice.iter()).chain(after.iter()).all(|p| p.walk_short_(it))
771 /// Walk the pattern in left-to-right order,
772 /// short circuiting (with `.all(..)`) if `false` is returned.
774 /// Note that when visiting e.g. `Tuple(ps)`,
775 /// if visiting `ps[0]` returns `false`,
776 /// then `ps[1]` will not be visited.
777 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'_>) -> bool) -> bool {
778 self.walk_short_(&mut it)
781 // FIXME(#19596) this is a workaround, but there should be a better way
782 fn walk_(&self, it: &mut impl FnMut(&Pat<'_>) -> bool) {
789 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
790 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
791 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
792 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
793 Slice(before, slice, after) => {
794 before.iter().chain(slice.iter()).chain(after.iter()).for_each(|p| p.walk_(it))
799 /// Walk the pattern in left-to-right order.
801 /// If `it(pat)` returns `false`, the children are not visited.
802 pub fn walk(&self, mut it: impl FnMut(&Pat<'_>) -> bool) {
806 /// Walk the pattern in left-to-right order.
808 /// If you always want to recurse, prefer this method over `walk`.
809 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
817 /// A single field in a struct pattern.
819 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
820 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
821 /// except `is_shorthand` is true.
822 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
823 pub struct FieldPat<'hir> {
824 #[stable_hasher(ignore)]
826 /// The identifier for the field.
827 #[stable_hasher(project(name))]
829 /// The pattern the field is destructured to.
830 pub pat: &'hir Pat<'hir>,
831 pub is_shorthand: bool,
835 /// Explicit binding annotations given in the HIR for a binding. Note
836 /// that this is not the final binding *mode* that we infer after type
838 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
839 pub enum BindingAnnotation {
840 /// No binding annotation given: this means that the final binding mode
841 /// will depend on whether we have skipped through a `&` reference
842 /// when matching. For example, the `x` in `Some(x)` will have binding
843 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
844 /// ultimately be inferred to be by-reference.
846 /// Note that implicit reference skipping is not implemented yet (#42640).
849 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
852 /// Annotated as `ref`, like `ref x`
855 /// Annotated as `ref mut x`.
859 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
865 impl fmt::Display for RangeEnd {
866 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
867 f.write_str(match self {
868 RangeEnd::Included => "..=",
869 RangeEnd::Excluded => "..",
874 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
875 pub enum PatKind<'hir> {
876 /// Represents a wildcard pattern (i.e., `_`).
879 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
880 /// The `HirId` is the canonical ID for the variable being bound,
881 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
882 /// which is the pattern ID of the first `x`.
883 Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
885 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
886 /// The `bool` is `true` in the presence of a `..`.
887 Struct(QPath<'hir>, &'hir [FieldPat<'hir>], bool),
889 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
890 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
891 /// `0 <= position <= subpats.len()`
892 TupleStruct(QPath<'hir>, &'hir [&'hir Pat<'hir>], Option<usize>),
894 /// An or-pattern `A | B | C`.
895 /// Invariant: `pats.len() >= 2`.
896 Or(&'hir [&'hir Pat<'hir>]),
898 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
901 /// A tuple pattern (e.g., `(a, b)`).
902 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
903 /// `0 <= position <= subpats.len()`
904 Tuple(&'hir [&'hir Pat<'hir>], Option<usize>),
907 Box(&'hir Pat<'hir>),
909 /// A reference pattern (e.g., `&mut (a, b)`).
910 Ref(&'hir Pat<'hir>, Mutability),
913 Lit(&'hir Expr<'hir>),
915 /// A range pattern (e.g., `1..=2` or `1..2`).
916 Range(Option<&'hir Expr<'hir>>, Option<&'hir Expr<'hir>>, RangeEnd),
918 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
920 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
921 /// If `slice` exists, then `after` can be non-empty.
923 /// The representation for e.g., `[a, b, .., c, d]` is:
925 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
927 Slice(&'hir [&'hir Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [&'hir Pat<'hir>]),
930 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
932 /// The `+` operator (addition).
934 /// The `-` operator (subtraction).
936 /// The `*` operator (multiplication).
938 /// The `/` operator (division).
940 /// The `%` operator (modulus).
942 /// The `&&` operator (logical and).
944 /// The `||` operator (logical or).
946 /// The `^` operator (bitwise xor).
948 /// The `&` operator (bitwise and).
950 /// The `|` operator (bitwise or).
952 /// The `<<` operator (shift left).
954 /// The `>>` operator (shift right).
956 /// The `==` operator (equality).
958 /// The `<` operator (less than).
960 /// The `<=` operator (less than or equal to).
962 /// The `!=` operator (not equal to).
964 /// The `>=` operator (greater than or equal to).
966 /// The `>` operator (greater than).
971 pub fn as_str(self) -> &'static str {
973 BinOpKind::Add => "+",
974 BinOpKind::Sub => "-",
975 BinOpKind::Mul => "*",
976 BinOpKind::Div => "/",
977 BinOpKind::Rem => "%",
978 BinOpKind::And => "&&",
979 BinOpKind::Or => "||",
980 BinOpKind::BitXor => "^",
981 BinOpKind::BitAnd => "&",
982 BinOpKind::BitOr => "|",
983 BinOpKind::Shl => "<<",
984 BinOpKind::Shr => ">>",
985 BinOpKind::Eq => "==",
986 BinOpKind::Lt => "<",
987 BinOpKind::Le => "<=",
988 BinOpKind::Ne => "!=",
989 BinOpKind::Ge => ">=",
990 BinOpKind::Gt => ">",
994 pub fn is_lazy(self) -> bool {
996 BinOpKind::And | BinOpKind::Or => true,
1001 pub fn is_shift(self) -> bool {
1003 BinOpKind::Shl | BinOpKind::Shr => true,
1008 pub fn is_comparison(self) -> bool {
1015 | BinOpKind::Ge => true,
1027 | BinOpKind::Shr => false,
1031 /// Returns `true` if the binary operator takes its arguments by value.
1032 pub fn is_by_value(self) -> bool {
1033 !self.is_comparison()
1037 impl Into<ast::BinOpKind> for BinOpKind {
1038 fn into(self) -> ast::BinOpKind {
1040 BinOpKind::Add => ast::BinOpKind::Add,
1041 BinOpKind::Sub => ast::BinOpKind::Sub,
1042 BinOpKind::Mul => ast::BinOpKind::Mul,
1043 BinOpKind::Div => ast::BinOpKind::Div,
1044 BinOpKind::Rem => ast::BinOpKind::Rem,
1045 BinOpKind::And => ast::BinOpKind::And,
1046 BinOpKind::Or => ast::BinOpKind::Or,
1047 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1048 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1049 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1050 BinOpKind::Shl => ast::BinOpKind::Shl,
1051 BinOpKind::Shr => ast::BinOpKind::Shr,
1052 BinOpKind::Eq => ast::BinOpKind::Eq,
1053 BinOpKind::Lt => ast::BinOpKind::Lt,
1054 BinOpKind::Le => ast::BinOpKind::Le,
1055 BinOpKind::Ne => ast::BinOpKind::Ne,
1056 BinOpKind::Ge => ast::BinOpKind::Ge,
1057 BinOpKind::Gt => ast::BinOpKind::Gt,
1062 pub type BinOp = Spanned<BinOpKind>;
1064 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1066 /// The `*` operator (deferencing).
1068 /// The `!` operator (logical negation).
1070 /// The `-` operator (negation).
1075 pub fn as_str(self) -> &'static str {
1077 Self::UnDeref => "*",
1083 /// Returns `true` if the unary operator takes its argument by value.
1084 pub fn is_by_value(self) -> bool {
1086 Self::UnNeg | Self::UnNot => true,
1093 #[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
1094 pub struct Stmt<'hir> {
1096 pub kind: StmtKind<'hir>,
1100 impl fmt::Debug for Stmt<'_> {
1101 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1106 print::to_string(print::NO_ANN, |s| s.print_stmt(self))
1111 /// The contents of a statement.
1112 #[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
1113 pub enum StmtKind<'hir> {
1114 /// A local (`let`) binding.
1115 Local(&'hir Local<'hir>),
1117 /// An item binding.
1120 /// An expression without a trailing semi-colon (must have unit type).
1121 Expr(&'hir Expr<'hir>),
1123 /// An expression with a trailing semi-colon (may have any type).
1124 Semi(&'hir Expr<'hir>),
1127 impl StmtKind<'hir> {
1128 pub fn attrs(&self) -> &'hir [Attribute] {
1130 StmtKind::Local(ref l) => &l.attrs,
1131 StmtKind::Item(_) => &[],
1132 StmtKind::Expr(ref e) | StmtKind::Semi(ref e) => &e.attrs,
1137 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1138 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1139 pub struct Local<'hir> {
1140 pub pat: &'hir Pat<'hir>,
1141 /// Type annotation, if any (otherwise the type will be inferred).
1142 pub ty: Option<&'hir Ty<'hir>>,
1143 /// Initializer expression to set the value, if any.
1144 pub init: Option<&'hir Expr<'hir>>,
1148 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1149 /// desugaring. Otherwise will be `Normal`.
1150 pub source: LocalSource,
1153 /// Represents a single arm of a `match` expression, e.g.
1154 /// `<pat> (if <guard>) => <body>`.
1155 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1156 pub struct Arm<'hir> {
1157 #[stable_hasher(ignore)]
1160 pub attrs: &'hir [Attribute],
1161 /// If this pattern and the optional guard matches, then `body` is evaluated.
1162 pub pat: &'hir Pat<'hir>,
1163 /// Optional guard clause.
1164 pub guard: Option<Guard<'hir>>,
1165 /// The expression the arm evaluates to if this arm matches.
1166 pub body: &'hir Expr<'hir>,
1169 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1170 pub enum Guard<'hir> {
1171 If(&'hir Expr<'hir>),
1174 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1175 pub struct Field<'hir> {
1176 #[stable_hasher(ignore)]
1179 pub expr: &'hir Expr<'hir>,
1181 pub is_shorthand: bool,
1184 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1185 pub enum BlockCheckMode {
1187 UnsafeBlock(UnsafeSource),
1188 PushUnsafeBlock(UnsafeSource),
1189 PopUnsafeBlock(UnsafeSource),
1192 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1193 pub enum UnsafeSource {
1198 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1203 /// The body of a function, closure, or constant value. In the case of
1204 /// a function, the body contains not only the function body itself
1205 /// (which is an expression), but also the argument patterns, since
1206 /// those are something that the caller doesn't really care about.
1211 /// fn foo((x, y): (u32, u32)) -> u32 {
1216 /// Here, the `Body` associated with `foo()` would contain:
1218 /// - an `params` array containing the `(x, y)` pattern
1219 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1220 /// - `generator_kind` would be `None`
1222 /// All bodies have an **owner**, which can be accessed via the HIR
1223 /// map using `body_owner_def_id()`.
1224 #[derive(RustcEncodable, RustcDecodable, Debug)]
1225 pub struct Body<'hir> {
1226 pub params: &'hir [Param<'hir>],
1227 pub value: Expr<'hir>,
1228 pub generator_kind: Option<GeneratorKind>,
1232 pub fn id(&self) -> BodyId {
1233 BodyId { hir_id: self.value.hir_id }
1236 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1241 /// The type of source expression that caused this generator to be created.
1242 #[derive(Clone, PartialEq, Eq, HashStable_Generic, RustcEncodable, RustcDecodable, Debug, Copy)]
1243 pub enum GeneratorKind {
1244 /// An explicit `async` block or the body of an async function.
1245 Async(AsyncGeneratorKind),
1247 /// A generator literal created via a `yield` inside a closure.
1251 impl fmt::Display for GeneratorKind {
1252 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1254 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1255 GeneratorKind::Gen => f.write_str("generator"),
1260 /// In the case of a generator created as part of an async construct,
1261 /// which kind of async construct caused it to be created?
1263 /// This helps error messages but is also used to drive coercions in
1264 /// type-checking (see #60424).
1265 #[derive(Clone, PartialEq, Eq, HashStable_Generic, RustcEncodable, RustcDecodable, Debug, Copy)]
1266 pub enum AsyncGeneratorKind {
1267 /// An explicit `async` block written by the user.
1270 /// An explicit `async` block written by the user.
1273 /// The `async` block generated as the body of an async function.
1277 impl fmt::Display for AsyncGeneratorKind {
1278 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1279 f.write_str(match self {
1280 AsyncGeneratorKind::Block => "`async` block",
1281 AsyncGeneratorKind::Closure => "`async` closure body",
1282 AsyncGeneratorKind::Fn => "`async fn` body",
1287 #[derive(Copy, Clone, Debug)]
1288 pub enum BodyOwnerKind {
1289 /// Functions and methods.
1295 /// Constants and associated constants.
1298 /// Initializer of a `static` item.
1302 impl BodyOwnerKind {
1303 pub fn is_fn_or_closure(self) -> bool {
1305 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1306 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1312 pub type Lit = Spanned<LitKind>;
1314 /// A constant (expression) that's not an item or associated item,
1315 /// but needs its own `DefId` for type-checking, const-eval, etc.
1316 /// These are usually found nested inside types (e.g., array lengths)
1317 /// or expressions (e.g., repeat counts), and also used to define
1318 /// explicit discriminant values for enum variants.
1319 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1320 pub struct AnonConst {
1326 #[derive(RustcEncodable, RustcDecodable)]
1327 pub struct Expr<'hir> {
1329 pub kind: ExprKind<'hir>,
1334 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1335 #[cfg(target_arch = "x86_64")]
1336 rustc_data_structures::static_assert_size!(Expr<'static>, 64);
1339 pub fn precedence(&self) -> ExprPrecedence {
1341 ExprKind::Box(_) => ExprPrecedence::Box,
1342 ExprKind::Array(_) => ExprPrecedence::Array,
1343 ExprKind::Call(..) => ExprPrecedence::Call,
1344 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1345 ExprKind::Tup(_) => ExprPrecedence::Tup,
1346 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1347 ExprKind::Unary(..) => ExprPrecedence::Unary,
1348 ExprKind::Lit(_) => ExprPrecedence::Lit,
1349 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1350 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1351 ExprKind::Loop(..) => ExprPrecedence::Loop,
1352 ExprKind::Match(..) => ExprPrecedence::Match,
1353 ExprKind::Closure(..) => ExprPrecedence::Closure,
1354 ExprKind::Block(..) => ExprPrecedence::Block,
1355 ExprKind::Assign(..) => ExprPrecedence::Assign,
1356 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1357 ExprKind::Field(..) => ExprPrecedence::Field,
1358 ExprKind::Index(..) => ExprPrecedence::Index,
1359 ExprKind::Path(..) => ExprPrecedence::Path,
1360 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1361 ExprKind::Break(..) => ExprPrecedence::Break,
1362 ExprKind::Continue(..) => ExprPrecedence::Continue,
1363 ExprKind::Ret(..) => ExprPrecedence::Ret,
1364 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1365 ExprKind::Struct(..) => ExprPrecedence::Struct,
1366 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1367 ExprKind::Yield(..) => ExprPrecedence::Yield,
1368 ExprKind::Err => ExprPrecedence::Err,
1372 // Whether this looks like a place expr, without checking for deref
1374 // This will return `true` in some potentially surprising cases such as
1375 // `CONSTANT.field`.
1376 pub fn is_syntactic_place_expr(&self) -> bool {
1377 self.is_place_expr(|_| true)
1380 // Whether this is a place expression.
1381 // `allow_projections_from` should return `true` if indexing a field or
1382 // index expression based on the given expression should be considered a
1383 // place expression.
1384 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1386 ExprKind::Path(QPath::Resolved(_, ref path)) => match path.res {
1387 Res::Local(..) | Res::Def(DefKind::Static, _) | Res::Err => true,
1391 // Type ascription inherits its place expression kind from its
1393 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1394 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1396 ExprKind::Unary(UnOp::UnDeref, _) => true,
1398 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1399 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1402 // Partially qualified paths in expressions can only legally
1403 // refer to associated items which are always rvalues.
1404 ExprKind::Path(QPath::TypeRelative(..))
1405 | ExprKind::Call(..)
1406 | ExprKind::MethodCall(..)
1407 | ExprKind::Struct(..)
1409 | ExprKind::Match(..)
1410 | ExprKind::Closure(..)
1411 | ExprKind::Block(..)
1412 | ExprKind::Repeat(..)
1413 | ExprKind::Array(..)
1414 | ExprKind::Break(..)
1415 | ExprKind::Continue(..)
1417 | ExprKind::Loop(..)
1418 | ExprKind::Assign(..)
1419 | ExprKind::InlineAsm(..)
1420 | ExprKind::AssignOp(..)
1422 | ExprKind::Unary(..)
1424 | ExprKind::AddrOf(..)
1425 | ExprKind::Binary(..)
1426 | ExprKind::Yield(..)
1427 | ExprKind::Cast(..)
1428 | ExprKind::DropTemps(..)
1429 | ExprKind::Err => false,
1433 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1434 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1435 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1436 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1437 /// beyond remembering to call this function before doing analysis on it.
1438 pub fn peel_drop_temps(&self) -> &Self {
1439 let mut expr = self;
1440 while let ExprKind::DropTemps(inner) = &expr.kind {
1447 impl fmt::Debug for Expr<'_> {
1448 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1453 print::to_string(print::NO_ANN, |s| s.print_expr(self))
1458 /// Checks if the specified expression is a built-in range literal.
1459 /// (See: `LoweringContext::lower_expr()`).
1461 /// FIXME(#60607): This function is a hack. If and when we have `QPath::Lang(...)`,
1462 /// we can use that instead as simpler, more reliable mechanism, as opposed to using `SourceMap`.
1463 pub fn is_range_literal(sm: &SourceMap, expr: &Expr<'_>) -> bool {
1464 // Returns whether the given path represents a (desugared) range,
1465 // either in std or core, i.e. has either a `::std::ops::Range` or
1466 // `::core::ops::Range` prefix.
1467 fn is_range_path(path: &Path<'_>) -> bool {
1468 let segs: Vec<_> = path.segments.iter().map(|seg| seg.ident.to_string()).collect();
1469 let segs: Vec<_> = segs.iter().map(|seg| &**seg).collect();
1471 // "{{root}}" is the equivalent of `::` prefix in `Path`.
1472 if let ["{{root}}", std_core, "ops", range] = segs.as_slice() {
1473 (*std_core == "std" || *std_core == "core") && range.starts_with("Range")
1479 // Check whether a span corresponding to a range expression is a
1480 // range literal, rather than an explicit struct or `new()` call.
1481 fn is_lit(sm: &SourceMap, span: &Span) -> bool {
1482 let end_point = sm.end_point(*span);
1484 if let Ok(end_string) = sm.span_to_snippet(end_point) {
1485 !(end_string.ends_with("}") || end_string.ends_with(")"))
1492 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1493 ExprKind::Struct(ref qpath, _, _) => {
1494 if let QPath::Resolved(None, ref path) = **qpath {
1495 return is_range_path(&path) && is_lit(sm, &expr.span);
1499 // `..` desugars to its struct path.
1500 ExprKind::Path(QPath::Resolved(None, ref path)) => {
1501 return is_range_path(&path) && is_lit(sm, &expr.span);
1504 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1505 ExprKind::Call(ref func, _) => {
1506 if let ExprKind::Path(QPath::TypeRelative(ref ty, ref segment)) = func.kind {
1507 if let TyKind::Path(QPath::Resolved(None, ref path)) = ty.kind {
1508 let new_call = segment.ident.name == sym::new;
1509 return is_range_path(&path) && is_lit(sm, &expr.span) && new_call;
1520 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1521 pub enum ExprKind<'hir> {
1522 /// A `box x` expression.
1523 Box(&'hir Expr<'hir>),
1524 /// An array (e.g., `[a, b, c, d]`).
1525 Array(&'hir [Expr<'hir>]),
1526 /// A function call.
1528 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1529 /// and the second field is the list of arguments.
1530 /// This also represents calling the constructor of
1531 /// tuple-like ADTs such as tuple structs and enum variants.
1532 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1533 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1535 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1536 /// (within the angle brackets).
1537 /// The first element of the vector of `Expr`s is the expression that evaluates
1538 /// to the object on which the method is being called on (the receiver),
1539 /// and the remaining elements are the rest of the arguments.
1540 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1541 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1543 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1544 /// the `hir_id` of the `MethodCall` node itself.
1546 /// [`type_dependent_def_id`]: ../ty/struct.TypeckTables.html#method.type_dependent_def_id
1547 MethodCall(&'hir PathSegment<'hir>, Span, &'hir [Expr<'hir>]),
1548 /// A tuple (e.g., `(a, b, c, d)`).
1549 Tup(&'hir [Expr<'hir>]),
1550 /// A binary operation (e.g., `a + b`, `a * b`).
1551 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1552 /// A unary operation (e.g., `!x`, `*x`).
1553 Unary(UnOp, &'hir Expr<'hir>),
1554 /// A literal (e.g., `1`, `"foo"`).
1556 /// A cast (e.g., `foo as f64`).
1557 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1558 /// A type reference (e.g., `Foo`).
1559 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1560 /// Wraps the expression in a terminating scope.
1561 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1563 /// This construct only exists to tweak the drop order in HIR lowering.
1564 /// An example of that is the desugaring of `for` loops.
1565 DropTemps(&'hir Expr<'hir>),
1566 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1568 /// I.e., `'label: loop { <block> }`.
1569 Loop(&'hir Block<'hir>, Option<Label>, LoopSource),
1570 /// A `match` block, with a source that indicates whether or not it is
1571 /// the result of a desugaring, and if so, which kind.
1572 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1573 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1575 /// The `Span` is the argument block `|...|`.
1577 /// This may also be a generator literal or an `async block` as indicated by the
1578 /// `Option<Movability>`.
1579 Closure(CaptureBy, &'hir FnDecl<'hir>, BodyId, Span, Option<Movability>),
1580 /// A block (e.g., `'label: { ... }`).
1581 Block(&'hir Block<'hir>, Option<Label>),
1583 /// An assignment (e.g., `a = foo()`).
1584 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1585 /// An assignment with an operator.
1588 AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1589 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1590 Field(&'hir Expr<'hir>, Ident),
1591 /// An indexing operation (`foo[2]`).
1592 Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1594 /// Path to a definition, possibly containing lifetime or type parameters.
1597 /// A referencing operation (i.e., `&a` or `&mut a`).
1598 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1599 /// A `break`, with an optional label to break.
1600 Break(Destination, Option<&'hir Expr<'hir>>),
1601 /// A `continue`, with an optional label.
1602 Continue(Destination),
1603 /// A `return`, with an optional value to be returned.
1604 Ret(Option<&'hir Expr<'hir>>),
1606 /// Inline assembly (from `asm!`), with its outputs and inputs.
1607 InlineAsm(&'hir InlineAsm<'hir>),
1609 /// A struct or struct-like variant literal expression.
1611 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1612 /// where `base` is the `Option<Expr>`.
1613 Struct(&'hir QPath<'hir>, &'hir [Field<'hir>], Option<&'hir Expr<'hir>>),
1615 /// An array literal constructed from one repeated element.
1617 /// E.g., `[1; 5]`. The first expression is the element
1618 /// to be repeated; the second is the number of times to repeat it.
1619 Repeat(&'hir Expr<'hir>, AnonConst),
1621 /// A suspension point for generators (i.e., `yield <expr>`).
1622 Yield(&'hir Expr<'hir>, YieldSource),
1624 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1628 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1630 /// To resolve the path to a `DefId`, call [`qpath_res`].
1632 /// [`qpath_res`]: ../ty/struct.TypeckTables.html#method.qpath_res
1633 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1634 pub enum QPath<'hir> {
1635 /// Path to a definition, optionally "fully-qualified" with a `Self`
1636 /// type, if the path points to an associated item in a trait.
1638 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1639 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1640 /// even though they both have the same two-segment `Clone::clone` `Path`.
1641 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
1643 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1644 /// Will be resolved by type-checking to an associated item.
1646 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1647 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1648 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1649 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
1652 /// Hints at the original code for a let statement.
1653 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1654 pub enum LocalSource {
1655 /// A `match _ { .. }`.
1657 /// A desugared `for _ in _ { .. }` loop.
1659 /// When lowering async functions, we create locals within the `async move` so that
1660 /// all parameters are dropped after the future is polled.
1662 /// ```ignore (pseudo-Rust)
1663 /// async fn foo(<pattern> @ x: Type) {
1665 /// let <pattern> = x;
1670 /// A desugared `<expr>.await`.
1674 /// Hints at the original code for a `match _ { .. }`.
1675 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1676 #[derive(HashStable_Generic)]
1677 pub enum MatchSource {
1678 /// A `match _ { .. }`.
1680 /// An `if _ { .. }` (optionally with `else { .. }`).
1681 IfDesugar { contains_else_clause: bool },
1682 /// An `if let _ = _ { .. }` (optionally with `else { .. }`).
1683 IfLetDesugar { contains_else_clause: bool },
1684 /// A `while _ { .. }` (which was desugared to a `loop { match _ { .. } }`).
1686 /// A `while let _ = _ { .. }` (which was desugared to a
1687 /// `loop { match _ { .. } }`).
1689 /// A desugared `for _ in _ { .. }` loop.
1691 /// A desugared `?` operator.
1693 /// A desugared `<expr>.await`.
1698 pub fn name(self) -> &'static str {
1702 IfDesugar { .. } | IfLetDesugar { .. } => "if",
1703 WhileDesugar | WhileLetDesugar => "while",
1704 ForLoopDesugar => "for",
1706 AwaitDesugar => ".await",
1711 /// The loop type that yielded an `ExprKind::Loop`.
1712 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1713 pub enum LoopSource {
1714 /// A `loop { .. }` loop.
1716 /// A `while _ { .. }` loop.
1718 /// A `while let _ = _ { .. }` loop.
1720 /// A `for _ in _ { .. }` loop.
1725 pub fn name(self) -> &'static str {
1727 LoopSource::Loop => "loop",
1728 LoopSource::While | LoopSource::WhileLet => "while",
1729 LoopSource::ForLoop => "for",
1734 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1735 pub enum LoopIdError {
1737 UnlabeledCfInWhileCondition,
1741 impl fmt::Display for LoopIdError {
1742 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1743 f.write_str(match self {
1744 LoopIdError::OutsideLoopScope => "not inside loop scope",
1745 LoopIdError::UnlabeledCfInWhileCondition => {
1746 "unlabeled control flow (break or continue) in while condition"
1748 LoopIdError::UnresolvedLabel => "label not found",
1753 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1754 pub struct Destination {
1755 // This is `Some(_)` iff there is an explicit user-specified `label
1756 pub label: Option<Label>,
1758 // These errors are caught and then reported during the diagnostics pass in
1759 // librustc_passes/loops.rs
1760 pub target_id: Result<HirId, LoopIdError>,
1763 /// The yield kind that caused an `ExprKind::Yield`.
1764 #[derive(Copy, Clone, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable, HashStable_Generic)]
1765 pub enum YieldSource {
1766 /// An `<expr>.await`.
1768 /// A plain `yield`.
1772 impl fmt::Display for YieldSource {
1773 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1774 f.write_str(match self {
1775 YieldSource::Await => "`await`",
1776 YieldSource::Yield => "`yield`",
1781 impl From<GeneratorKind> for YieldSource {
1782 fn from(kind: GeneratorKind) -> Self {
1784 // Guess based on the kind of the current generator.
1785 GeneratorKind::Gen => Self::Yield,
1786 GeneratorKind::Async(_) => Self::Await,
1791 // N.B., if you change this, you'll probably want to change the corresponding
1792 // type structure in middle/ty.rs as well.
1793 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1794 pub struct MutTy<'hir> {
1795 pub ty: &'hir Ty<'hir>,
1796 pub mutbl: Mutability,
1799 /// Represents a function's signature in a trait declaration,
1800 /// trait implementation, or a free function.
1801 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1802 pub struct FnSig<'hir> {
1803 pub header: FnHeader,
1804 pub decl: &'hir FnDecl<'hir>,
1807 // The bodies for items are stored "out of line", in a separate
1808 // hashmap in the `Crate`. Here we just record the node-id of the item
1809 // so it can fetched later.
1810 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1811 pub struct TraitItemId {
1815 /// Represents an item declaration within a trait declaration,
1816 /// possibly including a default implementation. A trait item is
1817 /// either required (meaning it doesn't have an implementation, just a
1818 /// signature) or provided (meaning it has a default implementation).
1819 #[derive(RustcEncodable, RustcDecodable, Debug)]
1820 pub struct TraitItem<'hir> {
1823 pub attrs: &'hir [Attribute],
1824 pub generics: Generics<'hir>,
1825 pub kind: TraitItemKind<'hir>,
1829 /// Represents a trait method's body (or just argument names).
1830 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1831 pub enum TraitMethod<'hir> {
1832 /// No default body in the trait, just a signature.
1833 Required(&'hir [Ident]),
1835 /// Both signature and body are provided in the trait.
1839 /// Represents a trait method or associated constant or type
1840 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1841 pub enum TraitItemKind<'hir> {
1842 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
1843 Const(&'hir Ty<'hir>, Option<BodyId>),
1844 /// A method with an optional body.
1845 Method(FnSig<'hir>, TraitMethod<'hir>),
1846 /// An associated type with (possibly empty) bounds and optional concrete
1848 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
1851 // The bodies for items are stored "out of line", in a separate
1852 // hashmap in the `Crate`. Here we just record the node-id of the item
1853 // so it can fetched later.
1854 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1855 pub struct ImplItemId {
1859 /// Represents anything within an `impl` block.
1860 #[derive(RustcEncodable, RustcDecodable, Debug)]
1861 pub struct ImplItem<'hir> {
1864 pub vis: Visibility<'hir>,
1865 pub defaultness: Defaultness,
1866 pub attrs: &'hir [Attribute],
1867 pub generics: Generics<'hir>,
1868 pub kind: ImplItemKind<'hir>,
1872 /// Represents various kinds of content within an `impl`.
1873 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1874 pub enum ImplItemKind<'hir> {
1875 /// An associated constant of the given type, set to the constant result
1876 /// of the expression.
1877 Const(&'hir Ty<'hir>, BodyId),
1878 /// A method implementation with the given signature and body.
1879 Method(FnSig<'hir>, BodyId),
1880 /// An associated type.
1881 TyAlias(&'hir Ty<'hir>),
1882 /// An associated `type = impl Trait`.
1883 OpaqueTy(GenericBounds<'hir>),
1886 // The name of the associated type for `Fn` return types.
1887 pub const FN_OUTPUT_NAME: Symbol = sym::Output;
1889 /// Bind a type to an associated type (i.e., `A = Foo`).
1891 /// Bindings like `A: Debug` are represented as a special type `A =
1892 /// $::Debug` that is understood by the astconv code.
1894 /// FIXME(alexreg): why have a separate type for the binding case,
1895 /// wouldn't it be better to make the `ty` field an enum like the
1899 /// enum TypeBindingKind {
1904 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1905 pub struct TypeBinding<'hir> {
1907 #[stable_hasher(project(name))]
1909 pub kind: TypeBindingKind<'hir>,
1913 // Represents the two kinds of type bindings.
1914 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1915 pub enum TypeBindingKind<'hir> {
1916 /// E.g., `Foo<Bar: Send>`.
1917 Constraint { bounds: &'hir [GenericBound<'hir>] },
1918 /// E.g., `Foo<Bar = ()>`.
1919 Equality { ty: &'hir Ty<'hir> },
1922 impl TypeBinding<'_> {
1923 pub fn ty(&self) -> &Ty<'_> {
1925 TypeBindingKind::Equality { ref ty } => ty,
1926 _ => panic!("expected equality type binding for parenthesized generic args"),
1931 #[derive(RustcEncodable, RustcDecodable)]
1932 pub struct Ty<'hir> {
1934 pub kind: TyKind<'hir>,
1938 impl fmt::Debug for Ty<'_> {
1939 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1940 write!(f, "type({})", print::to_string(print::NO_ANN, |s| s.print_type(self)))
1944 /// Not represented directly in the AST; referred to by name through a `ty_path`.
1945 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1946 #[derive(HashStable_Generic)]
1956 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1957 pub struct BareFnTy<'hir> {
1958 pub unsafety: Unsafety,
1960 pub generic_params: &'hir [GenericParam<'hir>],
1961 pub decl: &'hir FnDecl<'hir>,
1962 pub param_names: &'hir [Ident],
1965 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1966 pub struct OpaqueTy<'hir> {
1967 pub generics: Generics<'hir>,
1968 pub bounds: GenericBounds<'hir>,
1969 pub impl_trait_fn: Option<DefId>,
1970 pub origin: OpaqueTyOrigin,
1973 /// From whence the opaque type came.
1974 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1975 pub enum OpaqueTyOrigin {
1976 /// `type Foo = impl Trait;`
1984 /// The various kinds of types recognized by the compiler.
1985 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1986 pub enum TyKind<'hir> {
1987 /// A variable length slice (i.e., `[T]`).
1988 Slice(&'hir Ty<'hir>),
1989 /// A fixed length array (i.e., `[T; n]`).
1990 Array(&'hir Ty<'hir>, AnonConst),
1991 /// A raw pointer (i.e., `*const T` or `*mut T`).
1993 /// A reference (i.e., `&'a T` or `&'a mut T`).
1994 Rptr(Lifetime, MutTy<'hir>),
1995 /// A bare function (e.g., `fn(usize) -> bool`).
1996 BareFn(&'hir BareFnTy<'hir>),
1997 /// The never type (`!`).
1999 /// A tuple (`(A, B, C, D, ...)`).
2000 Tup(&'hir [Ty<'hir>]),
2001 /// A path to a type definition (`module::module::...::Type`), or an
2002 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2004 /// Type parameters may be stored in each `PathSegment`.
2006 /// A type definition itself. This is currently only used for the `type Foo = impl Trait`
2007 /// item that `impl Trait` in return position desugars to.
2009 /// The generic argument list contains the lifetimes (and in the future possibly parameters)
2010 /// that are actually bound on the `impl Trait`.
2011 Def(ItemId, &'hir [GenericArg<'hir>]),
2012 /// A trait object type `Bound1 + Bound2 + Bound3`
2013 /// where `Bound` is a trait or a lifetime.
2014 TraitObject(&'hir [PolyTraitRef<'hir>], Lifetime),
2017 /// `TyKind::Infer` means the type should be inferred instead of it having been
2018 /// specified. This can appear anywhere in a type.
2020 /// Placeholder for a type that has failed to be defined.
2024 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic, PartialEq)]
2025 pub struct InlineAsmOutput {
2026 pub constraint: Symbol,
2028 pub is_indirect: bool,
2032 // NOTE(eddyb) This is used within MIR as well, so unlike the rest of the HIR,
2033 // it needs to be `Clone` and use plain `Vec<T>` instead of arena-allocated slice.
2034 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic, PartialEq)]
2035 pub struct InlineAsmInner {
2037 pub asm_str_style: StrStyle,
2038 pub outputs: Vec<InlineAsmOutput>,
2039 pub inputs: Vec<Symbol>,
2040 pub clobbers: Vec<Symbol>,
2042 pub alignstack: bool,
2043 pub dialect: AsmDialect,
2046 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2047 pub struct InlineAsm<'hir> {
2048 pub inner: InlineAsmInner,
2049 pub outputs_exprs: &'hir [Expr<'hir>],
2050 pub inputs_exprs: &'hir [Expr<'hir>],
2053 /// Represents a parameter in a function header.
2054 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2055 pub struct Param<'hir> {
2056 pub attrs: &'hir [Attribute],
2058 pub pat: &'hir Pat<'hir>,
2062 /// Represents the header (not the body) of a function declaration.
2063 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2064 pub struct FnDecl<'hir> {
2065 /// The types of the function's parameters.
2067 /// Additional argument data is stored in the function's [body](Body::parameters).
2068 pub inputs: &'hir [Ty<'hir>],
2069 pub output: FunctionRetTy<'hir>,
2070 pub c_variadic: bool,
2071 /// Does the function have an implicit self?
2072 pub implicit_self: ImplicitSelfKind,
2075 /// Represents what type of implicit self a function has, if any.
2076 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2077 pub enum ImplicitSelfKind {
2078 /// Represents a `fn x(self);`.
2080 /// Represents a `fn x(mut self);`.
2082 /// Represents a `fn x(&self);`.
2084 /// Represents a `fn x(&mut self);`.
2086 /// Represents when a function does not have a self argument or
2087 /// when a function has a `self: X` argument.
2091 impl ImplicitSelfKind {
2092 /// Does this represent an implicit self?
2093 pub fn has_implicit_self(&self) -> bool {
2095 ImplicitSelfKind::None => false,
2118 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2119 pub enum Defaultness {
2120 Default { has_value: bool },
2125 pub fn has_value(&self) -> bool {
2127 Defaultness::Default { has_value, .. } => has_value,
2128 Defaultness::Final => true,
2132 pub fn is_final(&self) -> bool {
2133 *self == Defaultness::Final
2136 pub fn is_default(&self) -> bool {
2138 Defaultness::Default { .. } => true,
2144 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2145 pub enum FunctionRetTy<'hir> {
2146 /// Return type is not specified.
2148 /// Functions default to `()` and
2149 /// closures default to inference. Span points to where return
2150 /// type would be inserted.
2151 DefaultReturn(Span),
2152 /// Everything else.
2153 Return(&'hir Ty<'hir>),
2156 impl fmt::Display for FunctionRetTy<'_> {
2157 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2159 Self::Return(ref ty) => print::to_string(print::NO_ANN, |s| s.print_type(ty)).fmt(f),
2160 Self::DefaultReturn(_) => "()".fmt(f),
2165 impl FunctionRetTy<'_> {
2166 pub fn span(&self) -> Span {
2168 Self::DefaultReturn(span) => span,
2169 Self::Return(ref ty) => ty.span,
2174 #[derive(RustcEncodable, RustcDecodable, Debug)]
2175 pub struct Mod<'hir> {
2176 /// A span from the first token past `{` to the last token until `}`.
2177 /// For `mod foo;`, the inner span ranges from the first token
2178 /// to the last token in the external file.
2180 pub item_ids: &'hir [ItemId],
2183 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2184 pub struct ForeignMod<'hir> {
2186 pub items: &'hir [ForeignItem<'hir>],
2189 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2190 pub struct GlobalAsm {
2194 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2195 pub struct EnumDef<'hir> {
2196 pub variants: &'hir [Variant<'hir>],
2199 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2200 pub struct Variant<'hir> {
2201 /// Name of the variant.
2202 #[stable_hasher(project(name))]
2204 /// Attributes of the variant.
2205 pub attrs: &'hir [Attribute],
2206 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2208 /// Fields and constructor id of the variant.
2209 pub data: VariantData<'hir>,
2210 /// Explicit discriminant (e.g., `Foo = 1`).
2211 pub disr_expr: Option<AnonConst>,
2216 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2218 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2219 /// Also produced for each element of a list `use`, e.g.
2220 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2223 /// Glob import, e.g., `use foo::*`.
2226 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2227 /// an additional `use foo::{}` for performing checks such as
2228 /// unstable feature gating. May be removed in the future.
2232 /// References to traits in impls.
2234 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2235 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2236 /// trait being referred to but just a unique `HirId` that serves as a key
2237 /// within the resolution map.
2238 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2239 pub struct TraitRef<'hir> {
2240 pub path: &'hir Path<'hir>,
2241 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2242 #[stable_hasher(ignore)]
2243 pub hir_ref_id: HirId,
2247 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2248 pub fn trait_def_id(&self) -> DefId {
2249 match self.path.res {
2250 Res::Def(DefKind::Trait, did) => did,
2251 Res::Def(DefKind::TraitAlias, did) => did,
2255 _ => unreachable!(),
2260 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2261 pub struct PolyTraitRef<'hir> {
2262 /// The `'a` in `<'a> Foo<&'a T>`.
2263 pub bound_generic_params: &'hir [GenericParam<'hir>],
2265 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2266 pub trait_ref: TraitRef<'hir>,
2271 pub type Visibility<'hir> = Spanned<VisibilityKind<'hir>>;
2273 #[derive(RustcEncodable, RustcDecodable, Debug)]
2274 pub enum VisibilityKind<'hir> {
2277 Restricted { path: &'hir Path<'hir>, hir_id: HirId },
2281 impl VisibilityKind<'_> {
2282 pub fn is_pub(&self) -> bool {
2284 VisibilityKind::Public => true,
2289 pub fn is_pub_restricted(&self) -> bool {
2291 VisibilityKind::Public | VisibilityKind::Inherited => false,
2292 VisibilityKind::Crate(..) | VisibilityKind::Restricted { .. } => true,
2296 pub fn descr(&self) -> &'static str {
2298 VisibilityKind::Public => "public",
2299 VisibilityKind::Inherited => "private",
2300 VisibilityKind::Crate(..) => "crate-visible",
2301 VisibilityKind::Restricted { .. } => "restricted",
2306 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2307 pub struct StructField<'hir> {
2309 #[stable_hasher(project(name))]
2311 pub vis: Visibility<'hir>,
2313 pub ty: &'hir Ty<'hir>,
2314 pub attrs: &'hir [Attribute],
2317 impl StructField<'_> {
2318 // Still necessary in couple of places
2319 pub fn is_positional(&self) -> bool {
2320 let first = self.ident.as_str().as_bytes()[0];
2321 first >= b'0' && first <= b'9'
2325 /// Fields and constructor IDs of enum variants and structs.
2326 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2327 pub enum VariantData<'hir> {
2328 /// A struct variant.
2330 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2331 Struct(&'hir [StructField<'hir>], /* recovered */ bool),
2332 /// A tuple variant.
2334 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2335 Tuple(&'hir [StructField<'hir>], HirId),
2338 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2342 impl VariantData<'hir> {
2343 /// Return the fields of this variant.
2344 pub fn fields(&self) -> &'hir [StructField<'hir>] {
2346 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2351 /// Return the `HirId` of this variant's constructor, if it has one.
2352 pub fn ctor_hir_id(&self) -> Option<HirId> {
2354 VariantData::Struct(_, _) => None,
2355 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2360 // The bodies for items are stored "out of line", in a separate
2361 // hashmap in the `Crate`. Here we just record the node-id of the item
2362 // so it can fetched later.
2363 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2370 /// The name might be a dummy name in case of anonymous items
2371 #[derive(RustcEncodable, RustcDecodable, Debug)]
2372 pub struct Item<'hir> {
2375 pub attrs: &'hir [Attribute],
2376 pub kind: ItemKind<'hir>,
2377 pub vis: Visibility<'hir>,
2381 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2382 pub struct FnHeader {
2383 pub unsafety: Unsafety,
2384 pub constness: Constness,
2385 pub asyncness: IsAsync,
2390 pub fn is_const(&self) -> bool {
2391 match &self.constness {
2392 Constness::Const => true,
2398 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2399 pub enum ItemKind<'hir> {
2400 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2402 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2403 ExternCrate(Option<Name>),
2405 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2409 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2410 Use(&'hir Path<'hir>, UseKind),
2412 /// A `static` item.
2413 Static(&'hir Ty<'hir>, Mutability, BodyId),
2415 Const(&'hir Ty<'hir>, BodyId),
2416 /// A function declaration.
2417 Fn(FnSig<'hir>, Generics<'hir>, BodyId),
2420 /// An external module, e.g. `extern { .. }`.
2421 ForeignMod(ForeignMod<'hir>),
2422 /// Module-level inline assembly (from `global_asm!`).
2423 GlobalAsm(&'hir GlobalAsm),
2424 /// A type alias, e.g., `type Foo = Bar<u8>`.
2425 TyAlias(&'hir Ty<'hir>, Generics<'hir>),
2426 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2427 OpaqueTy(OpaqueTy<'hir>),
2428 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2429 Enum(EnumDef<'hir>, Generics<'hir>),
2430 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2431 Struct(VariantData<'hir>, Generics<'hir>),
2432 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2433 Union(VariantData<'hir>, Generics<'hir>),
2434 /// A trait definition.
2435 Trait(IsAuto, Unsafety, Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
2437 TraitAlias(Generics<'hir>, GenericBounds<'hir>),
2439 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2442 polarity: ImplPolarity,
2443 defaultness: Defaultness,
2444 constness: Constness,
2445 generics: Generics<'hir>,
2447 /// The trait being implemented, if any.
2448 of_trait: Option<TraitRef<'hir>>,
2450 self_ty: &'hir Ty<'hir>,
2451 items: &'hir [ImplItemRef<'hir>],
2456 pub fn descriptive_variant(&self) -> &str {
2458 ItemKind::ExternCrate(..) => "extern crate",
2459 ItemKind::Use(..) => "use",
2460 ItemKind::Static(..) => "static item",
2461 ItemKind::Const(..) => "constant item",
2462 ItemKind::Fn(..) => "function",
2463 ItemKind::Mod(..) => "module",
2464 ItemKind::ForeignMod(..) => "foreign module",
2465 ItemKind::GlobalAsm(..) => "global asm",
2466 ItemKind::TyAlias(..) => "type alias",
2467 ItemKind::OpaqueTy(..) => "opaque type",
2468 ItemKind::Enum(..) => "enum",
2469 ItemKind::Struct(..) => "struct",
2470 ItemKind::Union(..) => "union",
2471 ItemKind::Trait(..) => "trait",
2472 ItemKind::TraitAlias(..) => "trait alias",
2473 ItemKind::Impl { .. } => "impl",
2477 pub fn generics(&self) -> Option<&Generics<'_>> {
2479 ItemKind::Fn(_, ref generics, _)
2480 | ItemKind::TyAlias(_, ref generics)
2481 | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
2482 | ItemKind::Enum(_, ref generics)
2483 | ItemKind::Struct(_, ref generics)
2484 | ItemKind::Union(_, ref generics)
2485 | ItemKind::Trait(_, _, ref generics, _, _)
2486 | ItemKind::Impl { ref generics, .. } => generics,
2492 /// A reference from an trait to one of its associated items. This
2493 /// contains the item's id, naturally, but also the item's name and
2494 /// some other high-level details (like whether it is an associated
2495 /// type or method, and whether it is public). This allows other
2496 /// passes to find the impl they want without loading the ID (which
2497 /// means fewer edges in the incremental compilation graph).
2498 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2499 pub struct TraitItemRef {
2500 pub id: TraitItemId,
2501 #[stable_hasher(project(name))]
2503 pub kind: AssocItemKind,
2505 pub defaultness: Defaultness,
2508 /// A reference from an impl to one of its associated items. This
2509 /// contains the item's ID, naturally, but also the item's name and
2510 /// some other high-level details (like whether it is an associated
2511 /// type or method, and whether it is public). This allows other
2512 /// passes to find the impl they want without loading the ID (which
2513 /// means fewer edges in the incremental compilation graph).
2514 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2515 pub struct ImplItemRef<'hir> {
2517 #[stable_hasher(project(name))]
2519 pub kind: AssocItemKind,
2521 pub vis: Visibility<'hir>,
2522 pub defaultness: Defaultness,
2525 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2526 pub enum AssocItemKind {
2528 Method { has_self: bool },
2533 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2534 pub struct ForeignItem<'hir> {
2535 #[stable_hasher(project(name))]
2537 pub attrs: &'hir [Attribute],
2538 pub kind: ForeignItemKind<'hir>,
2541 pub vis: Visibility<'hir>,
2544 /// An item within an `extern` block.
2545 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2546 pub enum ForeignItemKind<'hir> {
2547 /// A foreign function.
2548 Fn(&'hir FnDecl<'hir>, &'hir [Ident], Generics<'hir>),
2549 /// A foreign static item (`static ext: u8`).
2550 Static(&'hir Ty<'hir>, Mutability),
2555 impl ForeignItemKind<'hir> {
2556 pub fn descriptive_variant(&self) -> &str {
2558 ForeignItemKind::Fn(..) => "foreign function",
2559 ForeignItemKind::Static(..) => "foreign static item",
2560 ForeignItemKind::Type => "foreign type",
2565 /// A variable captured by a closure.
2566 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable, HashStable_Generic)]
2568 // First span where it is accessed (there can be multiple).
2572 pub type CaptureModeMap = NodeMap<CaptureBy>;
2574 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2575 // has length > 0 if the trait is found through an chain of imports, starting with the
2576 // import/use statement in the scope where the trait is used.
2577 #[derive(Clone, Debug)]
2578 pub struct TraitCandidate {
2580 pub import_ids: SmallVec<[NodeId; 1]>,
2583 // Trait method resolution
2584 pub type TraitMap = NodeMap<Vec<TraitCandidate>>;
2586 // Map from the NodeId of a glob import to a list of items which are actually
2588 pub type GlobMap = NodeMap<FxHashSet<Name>>;
2590 #[derive(Copy, Clone, Debug)]
2591 pub enum Node<'hir> {
2592 Param(&'hir Param<'hir>),
2593 Item(&'hir Item<'hir>),
2594 ForeignItem(&'hir ForeignItem<'hir>),
2595 TraitItem(&'hir TraitItem<'hir>),
2596 ImplItem(&'hir ImplItem<'hir>),
2597 Variant(&'hir Variant<'hir>),
2598 Field(&'hir StructField<'hir>),
2599 AnonConst(&'hir AnonConst),
2600 Expr(&'hir Expr<'hir>),
2601 Stmt(&'hir Stmt<'hir>),
2602 PathSegment(&'hir PathSegment<'hir>),
2604 TraitRef(&'hir TraitRef<'hir>),
2605 Binding(&'hir Pat<'hir>),
2606 Pat(&'hir Pat<'hir>),
2607 Arm(&'hir Arm<'hir>),
2608 Block(&'hir Block<'hir>),
2609 Local(&'hir Local<'hir>),
2610 MacroDef(&'hir MacroDef<'hir>),
2612 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
2613 /// with synthesized constructors.
2614 Ctor(&'hir VariantData<'hir>),
2616 Lifetime(&'hir Lifetime),
2617 GenericParam(&'hir GenericParam<'hir>),
2618 Visibility(&'hir Visibility<'hir>),
2624 pub fn ident(&self) -> Option<Ident> {
2626 Node::TraitItem(TraitItem { ident, .. })
2627 | Node::ImplItem(ImplItem { ident, .. })
2628 | Node::ForeignItem(ForeignItem { ident, .. })
2629 | Node::Item(Item { ident, .. }) => Some(*ident),