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 {
369 /// The AST represents all type param bounds as types.
370 /// `typeck::collect::compute_bounds` matches these against
371 /// the "special" built-in traits (see `middle::lang_items`) and
372 /// detects `Copy`, `Send` and `Sync`.
373 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
374 pub enum GenericBound<'hir> {
375 Trait(PolyTraitRef<'hir>, TraitBoundModifier),
379 impl GenericBound<'_> {
380 pub fn span(&self) -> Span {
382 &GenericBound::Trait(ref t, ..) => t.span,
383 &GenericBound::Outlives(ref l) => l.span,
388 pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
390 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
391 pub enum LifetimeParamKind {
392 // Indicates that the lifetime definition was explicitly declared (e.g., in
393 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
396 // Indicates that the lifetime definition was synthetically added
397 // as a result of an in-band lifetime usage (e.g., in
398 // `fn foo(x: &'a u8) -> &'a u8 { x }`).
401 // Indication that the lifetime was elided (e.g., in both cases in
402 // `fn foo(x: &u8) -> &'_ u8 { x }`).
405 // Indication that the lifetime name was somehow in error.
409 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
410 pub enum GenericParamKind<'hir> {
411 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
413 kind: LifetimeParamKind,
416 default: Option<&'hir Ty<'hir>>,
417 synthetic: Option<SyntheticTyParamKind>,
424 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
425 pub struct GenericParam<'hir> {
428 pub attrs: &'hir [Attribute],
429 pub bounds: GenericBounds<'hir>,
431 pub pure_wrt_drop: bool,
432 pub kind: GenericParamKind<'hir>,
436 pub struct GenericParamCount {
437 pub lifetimes: usize,
442 /// Represents lifetimes and type parameters attached to a declaration
443 /// of a function, enum, trait, etc.
444 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
445 pub struct Generics<'hir> {
446 pub params: &'hir [GenericParam<'hir>],
447 pub where_clause: WhereClause<'hir>,
451 impl Generics<'hir> {
452 pub const fn empty() -> Generics<'hir> {
455 where_clause: WhereClause { predicates: &[], span: DUMMY_SP },
460 pub fn own_counts(&self) -> GenericParamCount {
461 // We could cache this as a property of `GenericParamCount`, but
462 // the aim is to refactor this away entirely eventually and the
463 // presence of this method will be a constant reminder.
464 let mut own_counts: GenericParamCount = Default::default();
466 for param in self.params {
468 GenericParamKind::Lifetime { .. } => own_counts.lifetimes += 1,
469 GenericParamKind::Type { .. } => own_counts.types += 1,
470 GenericParamKind::Const { .. } => own_counts.consts += 1,
477 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'_>> {
478 for param in self.params {
479 if name == param.name.ident().name {
486 pub fn spans(&self) -> MultiSpan {
487 if self.params.is_empty() {
490 self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
495 /// Synthetic type parameters are converted to another form during lowering; this allows
496 /// us to track the original form they had, and is useful for error messages.
497 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
498 #[derive(HashStable_Generic)]
499 pub enum SyntheticTyParamKind {
503 /// A where-clause in a definition.
504 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
505 pub struct WhereClause<'hir> {
506 pub predicates: &'hir [WherePredicate<'hir>],
507 // Only valid if predicates isn't empty.
511 impl WhereClause<'_> {
512 pub fn span(&self) -> Option<Span> {
513 if self.predicates.is_empty() { None } else { Some(self.span) }
516 /// The `WhereClause` under normal circumstances points at either the predicates or the empty
517 /// space where the `where` clause should be. Only of use for diagnostic suggestions.
518 pub fn span_for_predicates_or_empty_place(&self) -> Span {
523 /// A single predicate in a where-clause.
524 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
525 pub enum WherePredicate<'hir> {
526 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
527 BoundPredicate(WhereBoundPredicate<'hir>),
528 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
529 RegionPredicate(WhereRegionPredicate<'hir>),
530 /// An equality predicate (unsupported).
531 EqPredicate(WhereEqPredicate<'hir>),
534 impl WherePredicate<'_> {
535 pub fn span(&self) -> Span {
537 &WherePredicate::BoundPredicate(ref p) => p.span,
538 &WherePredicate::RegionPredicate(ref p) => p.span,
539 &WherePredicate::EqPredicate(ref p) => p.span,
544 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
545 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
546 pub struct WhereBoundPredicate<'hir> {
548 /// Any generics from a `for` binding.
549 pub bound_generic_params: &'hir [GenericParam<'hir>],
550 /// The type being bounded.
551 pub bounded_ty: &'hir Ty<'hir>,
552 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
553 pub bounds: GenericBounds<'hir>,
556 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
557 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
558 pub struct WhereRegionPredicate<'hir> {
560 pub lifetime: Lifetime,
561 pub bounds: GenericBounds<'hir>,
564 /// An equality predicate (e.g., `T = int`); currently unsupported.
565 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
566 pub struct WhereEqPredicate<'hir> {
569 pub lhs_ty: &'hir Ty<'hir>,
570 pub rhs_ty: &'hir Ty<'hir>,
573 #[derive(RustcEncodable, RustcDecodable, Debug)]
574 pub struct ModuleItems {
575 // Use BTreeSets here so items are in the same order as in the
576 // list of all items in Crate
577 pub items: BTreeSet<HirId>,
578 pub trait_items: BTreeSet<TraitItemId>,
579 pub impl_items: BTreeSet<ImplItemId>,
582 /// The top-level data structure that stores the entire contents of
583 /// the crate currently being compiled.
585 /// For more details, see the [rustc guide].
587 /// [rustc guide]: https://rust-lang.github.io/rustc-guide/hir.html
588 #[derive(RustcEncodable, RustcDecodable, Debug)]
589 pub struct Crate<'hir> {
590 pub module: Mod<'hir>,
591 pub attrs: &'hir [Attribute],
593 pub exported_macros: &'hir [MacroDef<'hir>],
594 // Attributes from non-exported macros, kept only for collecting the library feature list.
595 pub non_exported_macro_attrs: &'hir [Attribute],
597 // N.B., we use a `BTreeMap` here so that `visit_all_items` iterates
598 // over the ids in increasing order. In principle it should not
599 // matter what order we visit things in, but in *practice* it
600 // does, because it can affect the order in which errors are
601 // detected, which in turn can make compile-fail tests yield
602 // slightly different results.
603 pub items: BTreeMap<HirId, Item<'hir>>,
605 pub trait_items: BTreeMap<TraitItemId, TraitItem<'hir>>,
606 pub impl_items: BTreeMap<ImplItemId, ImplItem<'hir>>,
607 pub bodies: BTreeMap<BodyId, Body<'hir>>,
608 pub trait_impls: BTreeMap<DefId, Vec<HirId>>,
610 /// A list of the body ids written out in the order in which they
611 /// appear in the crate. If you're going to process all the bodies
612 /// in the crate, you should iterate over this list rather than the keys
614 pub body_ids: Vec<BodyId>,
616 /// A list of modules written out in the order in which they
617 /// appear in the crate. This includes the main crate module.
618 pub modules: BTreeMap<HirId, ModuleItems>,
622 pub fn item(&self, id: HirId) -> &Item<'hir> {
626 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem<'hir> {
627 &self.trait_items[&id]
630 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem<'hir> {
631 &self.impl_items[&id]
634 pub fn body(&self, id: BodyId) -> &Body<'hir> {
640 /// Visits all items in the crate in some deterministic (but
641 /// unspecified) order. If you just need to process every item,
642 /// but don't care about nesting, this method is the best choice.
644 /// If you do care about nesting -- usually because your algorithm
645 /// follows lexical scoping rules -- then you want a different
646 /// approach. You should override `visit_nested_item` in your
647 /// visitor and then call `intravisit::walk_crate` instead.
648 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
650 V: itemlikevisit::ItemLikeVisitor<'hir>,
652 for (_, item) in &self.items {
653 visitor.visit_item(item);
656 for (_, trait_item) in &self.trait_items {
657 visitor.visit_trait_item(trait_item);
660 for (_, impl_item) in &self.impl_items {
661 visitor.visit_impl_item(impl_item);
665 /// A parallel version of `visit_all_item_likes`.
666 pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
668 V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send,
672 par_for_each_in(&self.items, |(_, item)| {
673 visitor.visit_item(item);
677 par_for_each_in(&self.trait_items, |(_, trait_item)| {
678 visitor.visit_trait_item(trait_item);
682 par_for_each_in(&self.impl_items, |(_, impl_item)| {
683 visitor.visit_impl_item(impl_item);
690 /// A macro definition, in this crate or imported from another.
692 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
693 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
694 pub struct MacroDef<'hir> {
696 pub vis: Visibility<'hir>,
697 pub attrs: &'hir [Attribute],
700 pub body: TokenStream,
704 /// A block of statements `{ .. }`, which may have a label (in this case the
705 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
706 /// the `rules` being anything but `DefaultBlock`.
707 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
708 pub struct Block<'hir> {
709 /// Statements in a block.
710 pub stmts: &'hir [Stmt<'hir>],
711 /// An expression at the end of the block
712 /// without a semicolon, if any.
713 pub expr: Option<&'hir Expr<'hir>>,
714 #[stable_hasher(ignore)]
716 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
717 pub rules: BlockCheckMode,
719 /// If true, then there may exist `break 'a` values that aim to
720 /// break out of this block early.
721 /// Used by `'label: {}` blocks and by `try {}` blocks.
722 pub targeted_by_break: bool,
725 #[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
726 pub struct Pat<'hir> {
727 #[stable_hasher(ignore)]
729 pub kind: PatKind<'hir>,
733 impl fmt::Debug for Pat<'_> {
734 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
739 print::to_string(print::NO_ANN, |s| s.print_pat(self))
745 // FIXME(#19596) this is a workaround, but there should be a better way
746 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'_>) -> bool) -> bool {
753 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
754 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
755 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
756 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
757 Slice(before, slice, after) => {
758 before.iter().chain(slice.iter()).chain(after.iter()).all(|p| p.walk_short_(it))
763 /// Walk the pattern in left-to-right order,
764 /// short circuiting (with `.all(..)`) if `false` is returned.
766 /// Note that when visiting e.g. `Tuple(ps)`,
767 /// if visiting `ps[0]` returns `false`,
768 /// then `ps[1]` will not be visited.
769 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'_>) -> bool) -> bool {
770 self.walk_short_(&mut it)
773 // FIXME(#19596) this is a workaround, but there should be a better way
774 fn walk_(&self, it: &mut impl FnMut(&Pat<'_>) -> bool) {
781 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
782 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
783 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
784 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
785 Slice(before, slice, after) => {
786 before.iter().chain(slice.iter()).chain(after.iter()).for_each(|p| p.walk_(it))
791 /// Walk the pattern in left-to-right order.
793 /// If `it(pat)` returns `false`, the children are not visited.
794 pub fn walk(&self, mut it: impl FnMut(&Pat<'_>) -> bool) {
798 /// Walk the pattern in left-to-right order.
800 /// If you always want to recurse, prefer this method over `walk`.
801 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
809 /// A single field in a struct pattern.
811 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
812 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
813 /// except `is_shorthand` is true.
814 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
815 pub struct FieldPat<'hir> {
816 #[stable_hasher(ignore)]
818 /// The identifier for the field.
819 #[stable_hasher(project(name))]
821 /// The pattern the field is destructured to.
822 pub pat: &'hir Pat<'hir>,
823 pub is_shorthand: bool,
827 /// Explicit binding annotations given in the HIR for a binding. Note
828 /// that this is not the final binding *mode* that we infer after type
830 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
831 pub enum BindingAnnotation {
832 /// No binding annotation given: this means that the final binding mode
833 /// will depend on whether we have skipped through a `&` reference
834 /// when matching. For example, the `x` in `Some(x)` will have binding
835 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
836 /// ultimately be inferred to be by-reference.
838 /// Note that implicit reference skipping is not implemented yet (#42640).
841 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
844 /// Annotated as `ref`, like `ref x`
847 /// Annotated as `ref mut x`.
851 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
857 impl fmt::Display for RangeEnd {
858 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
859 f.write_str(match self {
860 RangeEnd::Included => "..=",
861 RangeEnd::Excluded => "..",
866 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
867 pub enum PatKind<'hir> {
868 /// Represents a wildcard pattern (i.e., `_`).
871 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
872 /// The `HirId` is the canonical ID for the variable being bound,
873 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
874 /// which is the pattern ID of the first `x`.
875 Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
877 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
878 /// The `bool` is `true` in the presence of a `..`.
879 Struct(QPath<'hir>, &'hir [FieldPat<'hir>], bool),
881 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
882 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
883 /// `0 <= position <= subpats.len()`
884 TupleStruct(QPath<'hir>, &'hir [&'hir Pat<'hir>], Option<usize>),
886 /// An or-pattern `A | B | C`.
887 /// Invariant: `pats.len() >= 2`.
888 Or(&'hir [&'hir Pat<'hir>]),
890 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
893 /// A tuple pattern (e.g., `(a, b)`).
894 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
895 /// `0 <= position <= subpats.len()`
896 Tuple(&'hir [&'hir Pat<'hir>], Option<usize>),
899 Box(&'hir Pat<'hir>),
901 /// A reference pattern (e.g., `&mut (a, b)`).
902 Ref(&'hir Pat<'hir>, Mutability),
905 Lit(&'hir Expr<'hir>),
907 /// A range pattern (e.g., `1..=2` or `1..2`).
908 Range(&'hir Expr<'hir>, &'hir Expr<'hir>, RangeEnd),
910 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
912 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
913 /// If `slice` exists, then `after` can be non-empty.
915 /// The representation for e.g., `[a, b, .., c, d]` is:
917 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
919 Slice(&'hir [&'hir Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [&'hir Pat<'hir>]),
922 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
924 /// The `+` operator (addition).
926 /// The `-` operator (subtraction).
928 /// The `*` operator (multiplication).
930 /// The `/` operator (division).
932 /// The `%` operator (modulus).
934 /// The `&&` operator (logical and).
936 /// The `||` operator (logical or).
938 /// The `^` operator (bitwise xor).
940 /// The `&` operator (bitwise and).
942 /// The `|` operator (bitwise or).
944 /// The `<<` operator (shift left).
946 /// The `>>` operator (shift right).
948 /// The `==` operator (equality).
950 /// The `<` operator (less than).
952 /// The `<=` operator (less than or equal to).
954 /// The `!=` operator (not equal to).
956 /// The `>=` operator (greater than or equal to).
958 /// The `>` operator (greater than).
963 pub fn as_str(self) -> &'static str {
965 BinOpKind::Add => "+",
966 BinOpKind::Sub => "-",
967 BinOpKind::Mul => "*",
968 BinOpKind::Div => "/",
969 BinOpKind::Rem => "%",
970 BinOpKind::And => "&&",
971 BinOpKind::Or => "||",
972 BinOpKind::BitXor => "^",
973 BinOpKind::BitAnd => "&",
974 BinOpKind::BitOr => "|",
975 BinOpKind::Shl => "<<",
976 BinOpKind::Shr => ">>",
977 BinOpKind::Eq => "==",
978 BinOpKind::Lt => "<",
979 BinOpKind::Le => "<=",
980 BinOpKind::Ne => "!=",
981 BinOpKind::Ge => ">=",
982 BinOpKind::Gt => ">",
986 pub fn is_lazy(self) -> bool {
988 BinOpKind::And | BinOpKind::Or => true,
993 pub fn is_shift(self) -> bool {
995 BinOpKind::Shl | BinOpKind::Shr => true,
1000 pub fn is_comparison(self) -> bool {
1007 | BinOpKind::Ge => true,
1019 | BinOpKind::Shr => false,
1023 /// Returns `true` if the binary operator takes its arguments by value.
1024 pub fn is_by_value(self) -> bool {
1025 !self.is_comparison()
1029 impl Into<ast::BinOpKind> for BinOpKind {
1030 fn into(self) -> ast::BinOpKind {
1032 BinOpKind::Add => ast::BinOpKind::Add,
1033 BinOpKind::Sub => ast::BinOpKind::Sub,
1034 BinOpKind::Mul => ast::BinOpKind::Mul,
1035 BinOpKind::Div => ast::BinOpKind::Div,
1036 BinOpKind::Rem => ast::BinOpKind::Rem,
1037 BinOpKind::And => ast::BinOpKind::And,
1038 BinOpKind::Or => ast::BinOpKind::Or,
1039 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1040 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1041 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1042 BinOpKind::Shl => ast::BinOpKind::Shl,
1043 BinOpKind::Shr => ast::BinOpKind::Shr,
1044 BinOpKind::Eq => ast::BinOpKind::Eq,
1045 BinOpKind::Lt => ast::BinOpKind::Lt,
1046 BinOpKind::Le => ast::BinOpKind::Le,
1047 BinOpKind::Ne => ast::BinOpKind::Ne,
1048 BinOpKind::Ge => ast::BinOpKind::Ge,
1049 BinOpKind::Gt => ast::BinOpKind::Gt,
1054 pub type BinOp = Spanned<BinOpKind>;
1056 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1058 /// The `*` operator (deferencing).
1060 /// The `!` operator (logical negation).
1062 /// The `-` operator (negation).
1067 pub fn as_str(self) -> &'static str {
1069 Self::UnDeref => "*",
1075 /// Returns `true` if the unary operator takes its argument by value.
1076 pub fn is_by_value(self) -> bool {
1078 Self::UnNeg | Self::UnNot => true,
1085 #[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
1086 pub struct Stmt<'hir> {
1088 pub kind: StmtKind<'hir>,
1092 impl fmt::Debug for Stmt<'_> {
1093 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1098 print::to_string(print::NO_ANN, |s| s.print_stmt(self))
1103 /// The contents of a statement.
1104 #[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
1105 pub enum StmtKind<'hir> {
1106 /// A local (`let`) binding.
1107 Local(&'hir Local<'hir>),
1109 /// An item binding.
1112 /// An expression without a trailing semi-colon (must have unit type).
1113 Expr(&'hir Expr<'hir>),
1115 /// An expression with a trailing semi-colon (may have any type).
1116 Semi(&'hir Expr<'hir>),
1119 impl StmtKind<'hir> {
1120 pub fn attrs(&self) -> &'hir [Attribute] {
1122 StmtKind::Local(ref l) => &l.attrs,
1123 StmtKind::Item(_) => &[],
1124 StmtKind::Expr(ref e) | StmtKind::Semi(ref e) => &e.attrs,
1129 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1130 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1131 pub struct Local<'hir> {
1132 pub pat: &'hir Pat<'hir>,
1133 /// Type annotation, if any (otherwise the type will be inferred).
1134 pub ty: Option<&'hir Ty<'hir>>,
1135 /// Initializer expression to set the value, if any.
1136 pub init: Option<&'hir Expr<'hir>>,
1140 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1141 /// desugaring. Otherwise will be `Normal`.
1142 pub source: LocalSource,
1145 /// Represents a single arm of a `match` expression, e.g.
1146 /// `<pat> (if <guard>) => <body>`.
1147 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1148 pub struct Arm<'hir> {
1149 #[stable_hasher(ignore)]
1152 pub attrs: &'hir [Attribute],
1153 /// If this pattern and the optional guard matches, then `body` is evaluated.
1154 pub pat: &'hir Pat<'hir>,
1155 /// Optional guard clause.
1156 pub guard: Option<Guard<'hir>>,
1157 /// The expression the arm evaluates to if this arm matches.
1158 pub body: &'hir Expr<'hir>,
1161 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1162 pub enum Guard<'hir> {
1163 If(&'hir Expr<'hir>),
1166 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1167 pub struct Field<'hir> {
1168 #[stable_hasher(ignore)]
1171 pub expr: &'hir Expr<'hir>,
1173 pub is_shorthand: bool,
1176 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1177 pub enum BlockCheckMode {
1179 UnsafeBlock(UnsafeSource),
1180 PushUnsafeBlock(UnsafeSource),
1181 PopUnsafeBlock(UnsafeSource),
1184 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1185 pub enum UnsafeSource {
1190 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1195 /// The body of a function, closure, or constant value. In the case of
1196 /// a function, the body contains not only the function body itself
1197 /// (which is an expression), but also the argument patterns, since
1198 /// those are something that the caller doesn't really care about.
1203 /// fn foo((x, y): (u32, u32)) -> u32 {
1208 /// Here, the `Body` associated with `foo()` would contain:
1210 /// - an `params` array containing the `(x, y)` pattern
1211 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1212 /// - `generator_kind` would be `None`
1214 /// All bodies have an **owner**, which can be accessed via the HIR
1215 /// map using `body_owner_def_id()`.
1216 #[derive(RustcEncodable, RustcDecodable, Debug)]
1217 pub struct Body<'hir> {
1218 pub params: &'hir [Param<'hir>],
1219 pub value: Expr<'hir>,
1220 pub generator_kind: Option<GeneratorKind>,
1224 pub fn id(&self) -> BodyId {
1225 BodyId { hir_id: self.value.hir_id }
1228 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1233 /// The type of source expression that caused this generator to be created.
1234 #[derive(Clone, PartialEq, Eq, HashStable_Generic, RustcEncodable, RustcDecodable, Debug, Copy)]
1235 pub enum GeneratorKind {
1236 /// An explicit `async` block or the body of an async function.
1237 Async(AsyncGeneratorKind),
1239 /// A generator literal created via a `yield` inside a closure.
1243 impl fmt::Display for GeneratorKind {
1244 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1246 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1247 GeneratorKind::Gen => f.write_str("generator"),
1252 /// In the case of a generator created as part of an async construct,
1253 /// which kind of async construct caused it to be created?
1255 /// This helps error messages but is also used to drive coercions in
1256 /// type-checking (see #60424).
1257 #[derive(Clone, PartialEq, Eq, HashStable_Generic, RustcEncodable, RustcDecodable, Debug, Copy)]
1258 pub enum AsyncGeneratorKind {
1259 /// An explicit `async` block written by the user.
1262 /// An explicit `async` block written by the user.
1265 /// The `async` block generated as the body of an async function.
1269 impl fmt::Display for AsyncGeneratorKind {
1270 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1271 f.write_str(match self {
1272 AsyncGeneratorKind::Block => "`async` block",
1273 AsyncGeneratorKind::Closure => "`async` closure body",
1274 AsyncGeneratorKind::Fn => "`async fn` body",
1279 #[derive(Copy, Clone, Debug)]
1280 pub enum BodyOwnerKind {
1281 /// Functions and methods.
1287 /// Constants and associated constants.
1290 /// Initializer of a `static` item.
1294 impl BodyOwnerKind {
1295 pub fn is_fn_or_closure(self) -> bool {
1297 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1298 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1304 pub type Lit = Spanned<LitKind>;
1306 /// A constant (expression) that's not an item or associated item,
1307 /// but needs its own `DefId` for type-checking, const-eval, etc.
1308 /// These are usually found nested inside types (e.g., array lengths)
1309 /// or expressions (e.g., repeat counts), and also used to define
1310 /// explicit discriminant values for enum variants.
1311 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1312 pub struct AnonConst {
1318 #[derive(RustcEncodable, RustcDecodable)]
1319 pub struct Expr<'hir> {
1321 pub kind: ExprKind<'hir>,
1326 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1327 #[cfg(target_arch = "x86_64")]
1328 rustc_data_structures::static_assert_size!(Expr<'static>, 64);
1331 pub fn precedence(&self) -> ExprPrecedence {
1333 ExprKind::Box(_) => ExprPrecedence::Box,
1334 ExprKind::Array(_) => ExprPrecedence::Array,
1335 ExprKind::Call(..) => ExprPrecedence::Call,
1336 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1337 ExprKind::Tup(_) => ExprPrecedence::Tup,
1338 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1339 ExprKind::Unary(..) => ExprPrecedence::Unary,
1340 ExprKind::Lit(_) => ExprPrecedence::Lit,
1341 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1342 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1343 ExprKind::Loop(..) => ExprPrecedence::Loop,
1344 ExprKind::Match(..) => ExprPrecedence::Match,
1345 ExprKind::Closure(..) => ExprPrecedence::Closure,
1346 ExprKind::Block(..) => ExprPrecedence::Block,
1347 ExprKind::Assign(..) => ExprPrecedence::Assign,
1348 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1349 ExprKind::Field(..) => ExprPrecedence::Field,
1350 ExprKind::Index(..) => ExprPrecedence::Index,
1351 ExprKind::Path(..) => ExprPrecedence::Path,
1352 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1353 ExprKind::Break(..) => ExprPrecedence::Break,
1354 ExprKind::Continue(..) => ExprPrecedence::Continue,
1355 ExprKind::Ret(..) => ExprPrecedence::Ret,
1356 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1357 ExprKind::Struct(..) => ExprPrecedence::Struct,
1358 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1359 ExprKind::Yield(..) => ExprPrecedence::Yield,
1360 ExprKind::Err => ExprPrecedence::Err,
1364 // Whether this looks like a place expr, without checking for deref
1366 // This will return `true` in some potentially surprising cases such as
1367 // `CONSTANT.field`.
1368 pub fn is_syntactic_place_expr(&self) -> bool {
1369 self.is_place_expr(|_| true)
1372 // Whether this is a place expression.
1373 // `allow_projections_from` should return `true` if indexing a field or
1374 // index expression based on the given expression should be considered a
1375 // place expression.
1376 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1378 ExprKind::Path(QPath::Resolved(_, ref path)) => match path.res {
1379 Res::Local(..) | Res::Def(DefKind::Static, _) | Res::Err => true,
1383 // Type ascription inherits its place expression kind from its
1385 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1386 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1388 ExprKind::Unary(UnOp::UnDeref, _) => true,
1390 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1391 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1394 // Partially qualified paths in expressions can only legally
1395 // refer to associated items which are always rvalues.
1396 ExprKind::Path(QPath::TypeRelative(..))
1397 | ExprKind::Call(..)
1398 | ExprKind::MethodCall(..)
1399 | ExprKind::Struct(..)
1401 | ExprKind::Match(..)
1402 | ExprKind::Closure(..)
1403 | ExprKind::Block(..)
1404 | ExprKind::Repeat(..)
1405 | ExprKind::Array(..)
1406 | ExprKind::Break(..)
1407 | ExprKind::Continue(..)
1409 | ExprKind::Loop(..)
1410 | ExprKind::Assign(..)
1411 | ExprKind::InlineAsm(..)
1412 | ExprKind::AssignOp(..)
1414 | ExprKind::Unary(..)
1416 | ExprKind::AddrOf(..)
1417 | ExprKind::Binary(..)
1418 | ExprKind::Yield(..)
1419 | ExprKind::Cast(..)
1420 | ExprKind::DropTemps(..)
1421 | ExprKind::Err => false,
1425 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1426 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1427 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1428 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1429 /// beyond remembering to call this function before doing analysis on it.
1430 pub fn peel_drop_temps(&self) -> &Self {
1431 let mut expr = self;
1432 while let ExprKind::DropTemps(inner) = &expr.kind {
1439 impl fmt::Debug for Expr<'_> {
1440 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1445 print::to_string(print::NO_ANN, |s| s.print_expr(self))
1450 /// Checks if the specified expression is a built-in range literal.
1451 /// (See: `LoweringContext::lower_expr()`).
1453 /// FIXME(#60607): This function is a hack. If and when we have `QPath::Lang(...)`,
1454 /// we can use that instead as simpler, more reliable mechanism, as opposed to using `SourceMap`.
1455 pub fn is_range_literal(sm: &SourceMap, expr: &Expr<'_>) -> bool {
1456 // Returns whether the given path represents a (desugared) range,
1457 // either in std or core, i.e. has either a `::std::ops::Range` or
1458 // `::core::ops::Range` prefix.
1459 fn is_range_path(path: &Path<'_>) -> bool {
1460 let segs: Vec<_> = path.segments.iter().map(|seg| seg.ident.to_string()).collect();
1461 let segs: Vec<_> = segs.iter().map(|seg| &**seg).collect();
1463 // "{{root}}" is the equivalent of `::` prefix in `Path`.
1464 if let ["{{root}}", std_core, "ops", range] = segs.as_slice() {
1465 (*std_core == "std" || *std_core == "core") && range.starts_with("Range")
1471 // Check whether a span corresponding to a range expression is a
1472 // range literal, rather than an explicit struct or `new()` call.
1473 fn is_lit(sm: &SourceMap, span: &Span) -> bool {
1474 let end_point = sm.end_point(*span);
1476 if let Ok(end_string) = sm.span_to_snippet(end_point) {
1477 !(end_string.ends_with("}") || end_string.ends_with(")"))
1484 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1485 ExprKind::Struct(ref qpath, _, _) => {
1486 if let QPath::Resolved(None, ref path) = **qpath {
1487 return is_range_path(&path) && is_lit(sm, &expr.span);
1491 // `..` desugars to its struct path.
1492 ExprKind::Path(QPath::Resolved(None, ref path)) => {
1493 return is_range_path(&path) && is_lit(sm, &expr.span);
1496 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1497 ExprKind::Call(ref func, _) => {
1498 if let ExprKind::Path(QPath::TypeRelative(ref ty, ref segment)) = func.kind {
1499 if let TyKind::Path(QPath::Resolved(None, ref path)) = ty.kind {
1500 let new_call = segment.ident.name == sym::new;
1501 return is_range_path(&path) && is_lit(sm, &expr.span) && new_call;
1512 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1513 pub enum ExprKind<'hir> {
1514 /// A `box x` expression.
1515 Box(&'hir Expr<'hir>),
1516 /// An array (e.g., `[a, b, c, d]`).
1517 Array(&'hir [Expr<'hir>]),
1518 /// A function call.
1520 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1521 /// and the second field is the list of arguments.
1522 /// This also represents calling the constructor of
1523 /// tuple-like ADTs such as tuple structs and enum variants.
1524 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1525 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1527 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1528 /// (within the angle brackets).
1529 /// The first element of the vector of `Expr`s is the expression that evaluates
1530 /// to the object on which the method is being called on (the receiver),
1531 /// and the remaining elements are the rest of the arguments.
1532 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1533 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1535 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1536 /// the `hir_id` of the `MethodCall` node itself.
1538 /// [`type_dependent_def_id`]: ../ty/struct.TypeckTables.html#method.type_dependent_def_id
1539 MethodCall(&'hir PathSegment<'hir>, Span, &'hir [Expr<'hir>]),
1540 /// A tuple (e.g., `(a, b, c, d)`).
1541 Tup(&'hir [Expr<'hir>]),
1542 /// A binary operation (e.g., `a + b`, `a * b`).
1543 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1544 /// A unary operation (e.g., `!x`, `*x`).
1545 Unary(UnOp, &'hir Expr<'hir>),
1546 /// A literal (e.g., `1`, `"foo"`).
1548 /// A cast (e.g., `foo as f64`).
1549 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1550 /// A type reference (e.g., `Foo`).
1551 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1552 /// Wraps the expression in a terminating scope.
1553 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1555 /// This construct only exists to tweak the drop order in HIR lowering.
1556 /// An example of that is the desugaring of `for` loops.
1557 DropTemps(&'hir Expr<'hir>),
1558 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1560 /// I.e., `'label: loop { <block> }`.
1561 Loop(&'hir Block<'hir>, Option<Label>, LoopSource),
1562 /// A `match` block, with a source that indicates whether or not it is
1563 /// the result of a desugaring, and if so, which kind.
1564 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1565 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1567 /// The `Span` is the argument block `|...|`.
1569 /// This may also be a generator literal or an `async block` as indicated by the
1570 /// `Option<Movability>`.
1571 Closure(CaptureBy, &'hir FnDecl<'hir>, BodyId, Span, Option<Movability>),
1572 /// A block (e.g., `'label: { ... }`).
1573 Block(&'hir Block<'hir>, Option<Label>),
1575 /// An assignment (e.g., `a = foo()`).
1576 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1577 /// An assignment with an operator.
1580 AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1581 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1582 Field(&'hir Expr<'hir>, Ident),
1583 /// An indexing operation (`foo[2]`).
1584 Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1586 /// Path to a definition, possibly containing lifetime or type parameters.
1589 /// A referencing operation (i.e., `&a` or `&mut a`).
1590 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1591 /// A `break`, with an optional label to break.
1592 Break(Destination, Option<&'hir Expr<'hir>>),
1593 /// A `continue`, with an optional label.
1594 Continue(Destination),
1595 /// A `return`, with an optional value to be returned.
1596 Ret(Option<&'hir Expr<'hir>>),
1598 /// Inline assembly (from `asm!`), with its outputs and inputs.
1599 InlineAsm(&'hir InlineAsm<'hir>),
1601 /// A struct or struct-like variant literal expression.
1603 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1604 /// where `base` is the `Option<Expr>`.
1605 Struct(&'hir QPath<'hir>, &'hir [Field<'hir>], Option<&'hir Expr<'hir>>),
1607 /// An array literal constructed from one repeated element.
1609 /// E.g., `[1; 5]`. The first expression is the element
1610 /// to be repeated; the second is the number of times to repeat it.
1611 Repeat(&'hir Expr<'hir>, AnonConst),
1613 /// A suspension point for generators (i.e., `yield <expr>`).
1614 Yield(&'hir Expr<'hir>, YieldSource),
1616 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1620 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1622 /// To resolve the path to a `DefId`, call [`qpath_res`].
1624 /// [`qpath_res`]: ../ty/struct.TypeckTables.html#method.qpath_res
1625 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1626 pub enum QPath<'hir> {
1627 /// Path to a definition, optionally "fully-qualified" with a `Self`
1628 /// type, if the path points to an associated item in a trait.
1630 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1631 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1632 /// even though they both have the same two-segment `Clone::clone` `Path`.
1633 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
1635 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1636 /// Will be resolved by type-checking to an associated item.
1638 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1639 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1640 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1641 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
1644 /// Hints at the original code for a let statement.
1645 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1646 pub enum LocalSource {
1647 /// A `match _ { .. }`.
1649 /// A desugared `for _ in _ { .. }` loop.
1651 /// When lowering async functions, we create locals within the `async move` so that
1652 /// all parameters are dropped after the future is polled.
1654 /// ```ignore (pseudo-Rust)
1655 /// async fn foo(<pattern> @ x: Type) {
1657 /// let <pattern> = x;
1662 /// A desugared `<expr>.await`.
1666 /// Hints at the original code for a `match _ { .. }`.
1667 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1668 #[derive(HashStable_Generic)]
1669 pub enum MatchSource {
1670 /// A `match _ { .. }`.
1672 /// An `if _ { .. }` (optionally with `else { .. }`).
1673 IfDesugar { contains_else_clause: bool },
1674 /// An `if let _ = _ { .. }` (optionally with `else { .. }`).
1675 IfLetDesugar { contains_else_clause: bool },
1676 /// A `while _ { .. }` (which was desugared to a `loop { match _ { .. } }`).
1678 /// A `while let _ = _ { .. }` (which was desugared to a
1679 /// `loop { match _ { .. } }`).
1681 /// A desugared `for _ in _ { .. }` loop.
1683 /// A desugared `?` operator.
1685 /// A desugared `<expr>.await`.
1690 pub fn name(self) -> &'static str {
1694 IfDesugar { .. } | IfLetDesugar { .. } => "if",
1695 WhileDesugar | WhileLetDesugar => "while",
1696 ForLoopDesugar => "for",
1698 AwaitDesugar => ".await",
1703 /// The loop type that yielded an `ExprKind::Loop`.
1704 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1705 pub enum LoopSource {
1706 /// A `loop { .. }` loop.
1708 /// A `while _ { .. }` loop.
1710 /// A `while let _ = _ { .. }` loop.
1712 /// A `for _ in _ { .. }` loop.
1717 pub fn name(self) -> &'static str {
1719 LoopSource::Loop => "loop",
1720 LoopSource::While | LoopSource::WhileLet => "while",
1721 LoopSource::ForLoop => "for",
1726 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1727 pub enum LoopIdError {
1729 UnlabeledCfInWhileCondition,
1733 impl fmt::Display for LoopIdError {
1734 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1735 f.write_str(match self {
1736 LoopIdError::OutsideLoopScope => "not inside loop scope",
1737 LoopIdError::UnlabeledCfInWhileCondition => {
1738 "unlabeled control flow (break or continue) in while condition"
1740 LoopIdError::UnresolvedLabel => "label not found",
1745 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1746 pub struct Destination {
1747 // This is `Some(_)` iff there is an explicit user-specified `label
1748 pub label: Option<Label>,
1750 // These errors are caught and then reported during the diagnostics pass in
1751 // librustc_passes/loops.rs
1752 pub target_id: Result<HirId, LoopIdError>,
1755 /// The yield kind that caused an `ExprKind::Yield`.
1756 #[derive(Copy, Clone, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable, HashStable_Generic)]
1757 pub enum YieldSource {
1758 /// An `<expr>.await`.
1760 /// A plain `yield`.
1764 impl fmt::Display for YieldSource {
1765 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1766 f.write_str(match self {
1767 YieldSource::Await => "`await`",
1768 YieldSource::Yield => "`yield`",
1773 impl From<GeneratorKind> for YieldSource {
1774 fn from(kind: GeneratorKind) -> Self {
1776 // Guess based on the kind of the current generator.
1777 GeneratorKind::Gen => Self::Yield,
1778 GeneratorKind::Async(_) => Self::Await,
1783 // N.B., if you change this, you'll probably want to change the corresponding
1784 // type structure in middle/ty.rs as well.
1785 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1786 pub struct MutTy<'hir> {
1787 pub ty: &'hir Ty<'hir>,
1788 pub mutbl: Mutability,
1791 /// Represents a function's signature in a trait declaration,
1792 /// trait implementation, or a free function.
1793 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1794 pub struct FnSig<'hir> {
1795 pub header: FnHeader,
1796 pub decl: &'hir FnDecl<'hir>,
1799 // The bodies for items are stored "out of line", in a separate
1800 // hashmap in the `Crate`. Here we just record the node-id of the item
1801 // so it can fetched later.
1802 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1803 pub struct TraitItemId {
1807 /// Represents an item declaration within a trait declaration,
1808 /// possibly including a default implementation. A trait item is
1809 /// either required (meaning it doesn't have an implementation, just a
1810 /// signature) or provided (meaning it has a default implementation).
1811 #[derive(RustcEncodable, RustcDecodable, Debug)]
1812 pub struct TraitItem<'hir> {
1815 pub attrs: &'hir [Attribute],
1816 pub generics: Generics<'hir>,
1817 pub kind: TraitItemKind<'hir>,
1821 /// Represents a trait method's body (or just argument names).
1822 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1823 pub enum TraitMethod<'hir> {
1824 /// No default body in the trait, just a signature.
1825 Required(&'hir [Ident]),
1827 /// Both signature and body are provided in the trait.
1831 /// Represents a trait method or associated constant or type
1832 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1833 pub enum TraitItemKind<'hir> {
1834 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
1835 Const(&'hir Ty<'hir>, Option<BodyId>),
1836 /// A method with an optional body.
1837 Method(FnSig<'hir>, TraitMethod<'hir>),
1838 /// An associated type with (possibly empty) bounds and optional concrete
1840 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
1843 // The bodies for items are stored "out of line", in a separate
1844 // hashmap in the `Crate`. Here we just record the node-id of the item
1845 // so it can fetched later.
1846 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1847 pub struct ImplItemId {
1851 /// Represents anything within an `impl` block.
1852 #[derive(RustcEncodable, RustcDecodable, Debug)]
1853 pub struct ImplItem<'hir> {
1856 pub vis: Visibility<'hir>,
1857 pub defaultness: Defaultness,
1858 pub attrs: &'hir [Attribute],
1859 pub generics: Generics<'hir>,
1860 pub kind: ImplItemKind<'hir>,
1864 /// Represents various kinds of content within an `impl`.
1865 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1866 pub enum ImplItemKind<'hir> {
1867 /// An associated constant of the given type, set to the constant result
1868 /// of the expression.
1869 Const(&'hir Ty<'hir>, BodyId),
1870 /// A method implementation with the given signature and body.
1871 Method(FnSig<'hir>, BodyId),
1872 /// An associated type.
1873 TyAlias(&'hir Ty<'hir>),
1874 /// An associated `type = impl Trait`.
1875 OpaqueTy(GenericBounds<'hir>),
1878 /// Bind a type to an associated type (i.e., `A = Foo`).
1880 /// Bindings like `A: Debug` are represented as a special type `A =
1881 /// $::Debug` that is understood by the astconv code.
1883 /// FIXME(alexreg): why have a separate type for the binding case,
1884 /// wouldn't it be better to make the `ty` field an enum like the
1888 /// enum TypeBindingKind {
1893 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1894 pub struct TypeBinding<'hir> {
1896 #[stable_hasher(project(name))]
1898 pub kind: TypeBindingKind<'hir>,
1902 // Represents the two kinds of type bindings.
1903 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1904 pub enum TypeBindingKind<'hir> {
1905 /// E.g., `Foo<Bar: Send>`.
1906 Constraint { bounds: &'hir [GenericBound<'hir>] },
1907 /// E.g., `Foo<Bar = ()>`.
1908 Equality { ty: &'hir Ty<'hir> },
1911 impl TypeBinding<'_> {
1912 pub fn ty(&self) -> &Ty<'_> {
1914 TypeBindingKind::Equality { ref ty } => ty,
1915 _ => panic!("expected equality type binding for parenthesized generic args"),
1920 #[derive(RustcEncodable, RustcDecodable)]
1921 pub struct Ty<'hir> {
1923 pub kind: TyKind<'hir>,
1927 impl fmt::Debug for Ty<'_> {
1928 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1929 write!(f, "type({})", print::to_string(print::NO_ANN, |s| s.print_type(self)))
1933 /// Not represented directly in the AST; referred to by name through a `ty_path`.
1934 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1935 #[derive(HashStable_Generic)]
1945 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1946 pub struct BareFnTy<'hir> {
1947 pub unsafety: Unsafety,
1949 pub generic_params: &'hir [GenericParam<'hir>],
1950 pub decl: &'hir FnDecl<'hir>,
1951 pub param_names: &'hir [Ident],
1954 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1955 pub struct OpaqueTy<'hir> {
1956 pub generics: Generics<'hir>,
1957 pub bounds: GenericBounds<'hir>,
1958 pub impl_trait_fn: Option<DefId>,
1959 pub origin: OpaqueTyOrigin,
1962 /// From whence the opaque type came.
1963 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1964 pub enum OpaqueTyOrigin {
1965 /// `type Foo = impl Trait;`
1973 /// The various kinds of types recognized by the compiler.
1974 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1975 pub enum TyKind<'hir> {
1976 /// A variable length slice (i.e., `[T]`).
1977 Slice(&'hir Ty<'hir>),
1978 /// A fixed length array (i.e., `[T; n]`).
1979 Array(&'hir Ty<'hir>, AnonConst),
1980 /// A raw pointer (i.e., `*const T` or `*mut T`).
1982 /// A reference (i.e., `&'a T` or `&'a mut T`).
1983 Rptr(Lifetime, MutTy<'hir>),
1984 /// A bare function (e.g., `fn(usize) -> bool`).
1985 BareFn(&'hir BareFnTy<'hir>),
1986 /// The never type (`!`).
1988 /// A tuple (`(A, B, C, D, ...)`).
1989 Tup(&'hir [Ty<'hir>]),
1990 /// A path to a type definition (`module::module::...::Type`), or an
1991 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
1993 /// Type parameters may be stored in each `PathSegment`.
1995 /// A type definition itself. This is currently only used for the `type Foo = impl Trait`
1996 /// item that `impl Trait` in return position desugars to.
1998 /// The generic argument list contains the lifetimes (and in the future possibly parameters)
1999 /// that are actually bound on the `impl Trait`.
2000 Def(ItemId, &'hir [GenericArg<'hir>]),
2001 /// A trait object type `Bound1 + Bound2 + Bound3`
2002 /// where `Bound` is a trait or a lifetime.
2003 TraitObject(&'hir [PolyTraitRef<'hir>], Lifetime),
2006 /// `TyKind::Infer` means the type should be inferred instead of it having been
2007 /// specified. This can appear anywhere in a type.
2009 /// Placeholder for a type that has failed to be defined.
2013 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic, PartialEq)]
2014 pub struct InlineAsmOutput {
2015 pub constraint: Symbol,
2017 pub is_indirect: bool,
2021 // NOTE(eddyb) This is used within MIR as well, so unlike the rest of the HIR,
2022 // it needs to be `Clone` and use plain `Vec<T>` instead of arena-allocated slice.
2023 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic, PartialEq)]
2024 pub struct InlineAsmInner {
2026 pub asm_str_style: StrStyle,
2027 pub outputs: Vec<InlineAsmOutput>,
2028 pub inputs: Vec<Symbol>,
2029 pub clobbers: Vec<Symbol>,
2031 pub alignstack: bool,
2032 pub dialect: AsmDialect,
2035 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2036 pub struct InlineAsm<'hir> {
2037 pub inner: InlineAsmInner,
2038 pub outputs_exprs: &'hir [Expr<'hir>],
2039 pub inputs_exprs: &'hir [Expr<'hir>],
2042 /// Represents a parameter in a function header.
2043 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2044 pub struct Param<'hir> {
2045 pub attrs: &'hir [Attribute],
2047 pub pat: &'hir Pat<'hir>,
2051 /// Represents the header (not the body) of a function declaration.
2052 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2053 pub struct FnDecl<'hir> {
2054 /// The types of the function's parameters.
2056 /// Additional argument data is stored in the function's [body](Body::parameters).
2057 pub inputs: &'hir [Ty<'hir>],
2058 pub output: FunctionRetTy<'hir>,
2059 pub c_variadic: bool,
2060 /// Does the function have an implicit self?
2061 pub implicit_self: ImplicitSelfKind,
2064 /// Represents what type of implicit self a function has, if any.
2065 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2066 pub enum ImplicitSelfKind {
2067 /// Represents a `fn x(self);`.
2069 /// Represents a `fn x(mut self);`.
2071 /// Represents a `fn x(&self);`.
2073 /// Represents a `fn x(&mut self);`.
2075 /// Represents when a function does not have a self argument or
2076 /// when a function has a `self: X` argument.
2080 impl ImplicitSelfKind {
2081 /// Does this represent an implicit self?
2082 pub fn has_implicit_self(&self) -> bool {
2084 ImplicitSelfKind::None => false,
2107 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2108 pub enum Defaultness {
2109 Default { has_value: bool },
2114 pub fn has_value(&self) -> bool {
2116 Defaultness::Default { has_value, .. } => has_value,
2117 Defaultness::Final => true,
2121 pub fn is_final(&self) -> bool {
2122 *self == Defaultness::Final
2125 pub fn is_default(&self) -> bool {
2127 Defaultness::Default { .. } => true,
2133 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2134 pub enum FunctionRetTy<'hir> {
2135 /// Return type is not specified.
2137 /// Functions default to `()` and
2138 /// closures default to inference. Span points to where return
2139 /// type would be inserted.
2140 DefaultReturn(Span),
2141 /// Everything else.
2142 Return(&'hir Ty<'hir>),
2145 impl fmt::Display for FunctionRetTy<'_> {
2146 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2148 Self::Return(ref ty) => print::to_string(print::NO_ANN, |s| s.print_type(ty)).fmt(f),
2149 Self::DefaultReturn(_) => "()".fmt(f),
2154 impl FunctionRetTy<'_> {
2155 pub fn span(&self) -> Span {
2157 Self::DefaultReturn(span) => span,
2158 Self::Return(ref ty) => ty.span,
2163 #[derive(RustcEncodable, RustcDecodable, Debug)]
2164 pub struct Mod<'hir> {
2165 /// A span from the first token past `{` to the last token until `}`.
2166 /// For `mod foo;`, the inner span ranges from the first token
2167 /// to the last token in the external file.
2169 pub item_ids: &'hir [ItemId],
2172 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2173 pub struct ForeignMod<'hir> {
2175 pub items: &'hir [ForeignItem<'hir>],
2178 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2179 pub struct GlobalAsm {
2183 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2184 pub struct EnumDef<'hir> {
2185 pub variants: &'hir [Variant<'hir>],
2188 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2189 pub struct Variant<'hir> {
2190 /// Name of the variant.
2191 #[stable_hasher(project(name))]
2193 /// Attributes of the variant.
2194 pub attrs: &'hir [Attribute],
2195 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2197 /// Fields and constructor id of the variant.
2198 pub data: VariantData<'hir>,
2199 /// Explicit discriminant (e.g., `Foo = 1`).
2200 pub disr_expr: Option<AnonConst>,
2205 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2207 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2208 /// Also produced for each element of a list `use`, e.g.
2209 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2212 /// Glob import, e.g., `use foo::*`.
2215 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2216 /// an additional `use foo::{}` for performing checks such as
2217 /// unstable feature gating. May be removed in the future.
2221 /// References to traits in impls.
2223 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2224 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2225 /// trait being referred to but just a unique `HirId` that serves as a key
2226 /// within the resolution map.
2227 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2228 pub struct TraitRef<'hir> {
2229 pub path: &'hir Path<'hir>,
2230 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2231 #[stable_hasher(ignore)]
2232 pub hir_ref_id: HirId,
2236 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2237 pub fn trait_def_id(&self) -> DefId {
2238 match self.path.res {
2239 Res::Def(DefKind::Trait, did) => did,
2240 Res::Def(DefKind::TraitAlias, did) => did,
2244 _ => unreachable!(),
2249 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2250 pub struct PolyTraitRef<'hir> {
2251 /// The `'a` in `<'a> Foo<&'a T>`.
2252 pub bound_generic_params: &'hir [GenericParam<'hir>],
2254 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2255 pub trait_ref: TraitRef<'hir>,
2260 pub type Visibility<'hir> = Spanned<VisibilityKind<'hir>>;
2262 #[derive(RustcEncodable, RustcDecodable, Debug)]
2263 pub enum VisibilityKind<'hir> {
2266 Restricted { path: &'hir Path<'hir>, hir_id: HirId },
2270 impl VisibilityKind<'_> {
2271 pub fn is_pub(&self) -> bool {
2273 VisibilityKind::Public => true,
2278 pub fn is_pub_restricted(&self) -> bool {
2280 VisibilityKind::Public | VisibilityKind::Inherited => false,
2281 VisibilityKind::Crate(..) | VisibilityKind::Restricted { .. } => true,
2285 pub fn descr(&self) -> &'static str {
2287 VisibilityKind::Public => "public",
2288 VisibilityKind::Inherited => "private",
2289 VisibilityKind::Crate(..) => "crate-visible",
2290 VisibilityKind::Restricted { .. } => "restricted",
2295 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2296 pub struct StructField<'hir> {
2298 #[stable_hasher(project(name))]
2300 pub vis: Visibility<'hir>,
2302 pub ty: &'hir Ty<'hir>,
2303 pub attrs: &'hir [Attribute],
2306 impl StructField<'_> {
2307 // Still necessary in couple of places
2308 pub fn is_positional(&self) -> bool {
2309 let first = self.ident.as_str().as_bytes()[0];
2310 first >= b'0' && first <= b'9'
2314 /// Fields and constructor IDs of enum variants and structs.
2315 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2316 pub enum VariantData<'hir> {
2317 /// A struct variant.
2319 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2320 Struct(&'hir [StructField<'hir>], /* recovered */ bool),
2321 /// A tuple variant.
2323 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2324 Tuple(&'hir [StructField<'hir>], HirId),
2327 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2331 impl VariantData<'hir> {
2332 /// Return the fields of this variant.
2333 pub fn fields(&self) -> &'hir [StructField<'hir>] {
2335 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2340 /// Return the `HirId` of this variant's constructor, if it has one.
2341 pub fn ctor_hir_id(&self) -> Option<HirId> {
2343 VariantData::Struct(_, _) => None,
2344 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2349 // The bodies for items are stored "out of line", in a separate
2350 // hashmap in the `Crate`. Here we just record the node-id of the item
2351 // so it can fetched later.
2352 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2359 /// The name might be a dummy name in case of anonymous items
2360 #[derive(RustcEncodable, RustcDecodable, Debug)]
2361 pub struct Item<'hir> {
2364 pub attrs: &'hir [Attribute],
2365 pub kind: ItemKind<'hir>,
2366 pub vis: Visibility<'hir>,
2370 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2371 pub struct FnHeader {
2372 pub unsafety: Unsafety,
2373 pub constness: Constness,
2374 pub asyncness: IsAsync,
2379 pub fn is_const(&self) -> bool {
2380 match &self.constness {
2381 Constness::Const => true,
2387 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2388 pub enum ItemKind<'hir> {
2389 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2391 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2392 ExternCrate(Option<Name>),
2394 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2398 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2399 Use(&'hir Path<'hir>, UseKind),
2401 /// A `static` item.
2402 Static(&'hir Ty<'hir>, Mutability, BodyId),
2404 Const(&'hir Ty<'hir>, BodyId),
2405 /// A function declaration.
2406 Fn(FnSig<'hir>, Generics<'hir>, BodyId),
2409 /// An external module, e.g. `extern { .. }`.
2410 ForeignMod(ForeignMod<'hir>),
2411 /// Module-level inline assembly (from `global_asm!`).
2412 GlobalAsm(&'hir GlobalAsm),
2413 /// A type alias, e.g., `type Foo = Bar<u8>`.
2414 TyAlias(&'hir Ty<'hir>, Generics<'hir>),
2415 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2416 OpaqueTy(OpaqueTy<'hir>),
2417 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2418 Enum(EnumDef<'hir>, Generics<'hir>),
2419 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2420 Struct(VariantData<'hir>, Generics<'hir>),
2421 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2422 Union(VariantData<'hir>, Generics<'hir>),
2423 /// A trait definition.
2424 Trait(IsAuto, Unsafety, Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
2426 TraitAlias(Generics<'hir>, GenericBounds<'hir>),
2428 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2434 Option<TraitRef<'hir>>, // (optional) trait this impl implements
2435 &'hir Ty<'hir>, // self
2436 &'hir [ImplItemRef<'hir>],
2441 pub fn descriptive_variant(&self) -> &str {
2443 ItemKind::ExternCrate(..) => "extern crate",
2444 ItemKind::Use(..) => "use",
2445 ItemKind::Static(..) => "static item",
2446 ItemKind::Const(..) => "constant item",
2447 ItemKind::Fn(..) => "function",
2448 ItemKind::Mod(..) => "module",
2449 ItemKind::ForeignMod(..) => "foreign module",
2450 ItemKind::GlobalAsm(..) => "global asm",
2451 ItemKind::TyAlias(..) => "type alias",
2452 ItemKind::OpaqueTy(..) => "opaque type",
2453 ItemKind::Enum(..) => "enum",
2454 ItemKind::Struct(..) => "struct",
2455 ItemKind::Union(..) => "union",
2456 ItemKind::Trait(..) => "trait",
2457 ItemKind::TraitAlias(..) => "trait alias",
2458 ItemKind::Impl(..) => "impl",
2462 pub fn generics(&self) -> Option<&Generics<'_>> {
2464 ItemKind::Fn(_, ref generics, _)
2465 | ItemKind::TyAlias(_, ref generics)
2466 | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
2467 | ItemKind::Enum(_, ref generics)
2468 | ItemKind::Struct(_, ref generics)
2469 | ItemKind::Union(_, ref generics)
2470 | ItemKind::Trait(_, _, ref generics, _, _)
2471 | ItemKind::Impl(_, _, _, ref generics, _, _, _) => generics,
2477 /// A reference from an trait to one of its associated items. This
2478 /// contains the item's id, naturally, but also the item's name and
2479 /// some other high-level details (like whether it is an associated
2480 /// type or method, and whether it is public). This allows other
2481 /// passes to find the impl they want without loading the ID (which
2482 /// means fewer edges in the incremental compilation graph).
2483 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2484 pub struct TraitItemRef {
2485 pub id: TraitItemId,
2486 #[stable_hasher(project(name))]
2488 pub kind: AssocItemKind,
2490 pub defaultness: Defaultness,
2493 /// A reference from an impl to one of its associated items. This
2494 /// contains the item's ID, naturally, but also the item's name and
2495 /// some other high-level details (like whether it is an associated
2496 /// type or method, and whether it is public). This allows other
2497 /// passes to find the impl they want without loading the ID (which
2498 /// means fewer edges in the incremental compilation graph).
2499 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2500 pub struct ImplItemRef<'hir> {
2502 #[stable_hasher(project(name))]
2504 pub kind: AssocItemKind,
2506 pub vis: Visibility<'hir>,
2507 pub defaultness: Defaultness,
2510 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2511 pub enum AssocItemKind {
2513 Method { has_self: bool },
2518 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2519 pub struct ForeignItem<'hir> {
2520 #[stable_hasher(project(name))]
2522 pub attrs: &'hir [Attribute],
2523 pub kind: ForeignItemKind<'hir>,
2526 pub vis: Visibility<'hir>,
2529 /// An item within an `extern` block.
2530 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2531 pub enum ForeignItemKind<'hir> {
2532 /// A foreign function.
2533 Fn(&'hir FnDecl<'hir>, &'hir [Ident], Generics<'hir>),
2534 /// A foreign static item (`static ext: u8`).
2535 Static(&'hir Ty<'hir>, Mutability),
2540 impl ForeignItemKind<'hir> {
2541 pub fn descriptive_variant(&self) -> &str {
2543 ForeignItemKind::Fn(..) => "foreign function",
2544 ForeignItemKind::Static(..) => "foreign static item",
2545 ForeignItemKind::Type => "foreign type",
2550 /// A variable captured by a closure.
2551 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable, HashStable_Generic)]
2553 // First span where it is accessed (there can be multiple).
2557 pub type CaptureModeMap = NodeMap<CaptureBy>;
2559 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2560 // has length > 0 if the trait is found through an chain of imports, starting with the
2561 // import/use statement in the scope where the trait is used.
2562 #[derive(Clone, Debug)]
2563 pub struct TraitCandidate {
2565 pub import_ids: SmallVec<[NodeId; 1]>,
2568 // Trait method resolution
2569 pub type TraitMap = NodeMap<Vec<TraitCandidate>>;
2571 // Map from the NodeId of a glob import to a list of items which are actually
2573 pub type GlobMap = NodeMap<FxHashSet<Name>>;
2575 #[derive(Copy, Clone, Debug)]
2576 pub enum Node<'hir> {
2577 Param(&'hir Param<'hir>),
2578 Item(&'hir Item<'hir>),
2579 ForeignItem(&'hir ForeignItem<'hir>),
2580 TraitItem(&'hir TraitItem<'hir>),
2581 ImplItem(&'hir ImplItem<'hir>),
2582 Variant(&'hir Variant<'hir>),
2583 Field(&'hir StructField<'hir>),
2584 AnonConst(&'hir AnonConst),
2585 Expr(&'hir Expr<'hir>),
2586 Stmt(&'hir Stmt<'hir>),
2587 PathSegment(&'hir PathSegment<'hir>),
2589 TraitRef(&'hir TraitRef<'hir>),
2590 Binding(&'hir Pat<'hir>),
2591 Pat(&'hir Pat<'hir>),
2592 Arm(&'hir Arm<'hir>),
2593 Block(&'hir Block<'hir>),
2594 Local(&'hir Local<'hir>),
2595 MacroDef(&'hir MacroDef<'hir>),
2597 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
2598 /// with synthesized constructors.
2599 Ctor(&'hir VariantData<'hir>),
2601 Lifetime(&'hir Lifetime),
2602 GenericParam(&'hir GenericParam<'hir>),
2603 Visibility(&'hir Visibility<'hir>),
2609 pub fn ident(&self) -> Option<Ident> {
2611 Node::TraitItem(TraitItem { ident, .. })
2612 | Node::ImplItem(ImplItem { ident, .. })
2613 | Node::ForeignItem(ForeignItem { ident, .. })
2614 | Node::Item(Item { ident, .. }) => Some(*ident),