1 use crate::def::{DefKind, Namespace, Res};
2 use crate::def_id::DefId;
3 crate use crate::hir_id::HirId;
4 use crate::itemlikevisit;
6 use rustc_ast::ast::{self, CrateSugar, Ident, LlvmAsmDialect, Name};
7 use rustc_ast::ast::{AttrVec, Attribute, FloatTy, IntTy, Label, LitKind, StrStyle, UintTy};
8 pub use rustc_ast::ast::{BorrowKind, ImplPolarity, IsAuto};
9 pub use rustc_ast::ast::{CaptureBy, Movability, Mutability};
10 use rustc_ast::node_id::NodeMap;
11 use rustc_ast::util::parser::ExprPrecedence;
12 use rustc_data_structures::fx::FxHashSet;
13 use rustc_data_structures::sync::{par_for_each_in, Send, Sync};
14 use rustc_macros::HashStable_Generic;
15 use rustc_span::source_map::{SourceMap, Spanned};
16 use rustc_span::symbol::{kw, sym, Symbol};
17 use rustc_span::{MultiSpan, Span, DUMMY_SP};
18 use rustc_target::spec::abi::Abi;
20 use smallvec::SmallVec;
21 use std::collections::{BTreeMap, BTreeSet};
24 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, HashStable_Generic)]
29 /// Either "`'a`", referring to a named lifetime definition,
30 /// or "``" (i.e., `kw::Invalid`), for elision placeholders.
32 /// HIR lowering inserts these placeholders in type paths that
33 /// refer to type definitions needing lifetime parameters,
34 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
35 pub name: LifetimeName,
38 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
39 #[derive(HashStable_Generic)]
41 /// Some user-given name like `T` or `'x`.
44 /// Synthetic name generated when user elided a lifetime in an impl header.
46 /// E.g., the lifetimes in cases like these:
49 /// impl Foo<'_> for u32
51 /// in that case, we rewrite to
53 /// impl<'f> Foo for &'f u32
54 /// impl<'f> Foo<'f> for u32
56 /// where `'f` is something like `Fresh(0)`. The indices are
57 /// unique per impl, but not necessarily continuous.
60 /// Indicates an illegal name was given and an error has been
61 /// reported (so we should squelch other derived errors). Occurs
62 /// when, e.g., `'_` is used in the wrong place.
67 pub fn ident(&self) -> Ident {
69 ParamName::Plain(ident) => ident,
70 ParamName::Fresh(_) | ParamName::Error => {
71 Ident::with_dummy_span(kw::UnderscoreLifetime)
76 pub fn normalize_to_macros_2_0(&self) -> ParamName {
78 ParamName::Plain(ident) => ParamName::Plain(ident.normalize_to_macros_2_0()),
79 param_name => param_name,
84 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
85 #[derive(HashStable_Generic)]
86 pub enum LifetimeName {
87 /// User-given names or fresh (synthetic) names.
90 /// User wrote nothing (e.g., the lifetime in `&u32`).
93 /// Implicit lifetime in a context like `dyn Foo`. This is
94 /// distinguished from implicit lifetimes elsewhere because the
95 /// lifetime that they default to must appear elsewhere within the
96 /// enclosing type. This means that, in an `impl Trait` context, we
97 /// don't have to create a parameter for them. That is, `impl
98 /// Trait<Item = &u32>` expands to an opaque type like `type
99 /// Foo<'a> = impl Trait<Item = &'a u32>`, but `impl Trait<item =
100 /// dyn Bar>` expands to `type Foo = impl Trait<Item = dyn Bar +
101 /// 'static>`. The latter uses `ImplicitObjectLifetimeDefault` so
102 /// that surrounding code knows not to create a lifetime
104 ImplicitObjectLifetimeDefault,
106 /// Indicates an error during lowering (usually `'_` in wrong place)
107 /// that was already reported.
110 /// User wrote specifies `'_`.
113 /// User wrote `'static`.
118 pub fn ident(&self) -> Ident {
120 LifetimeName::ImplicitObjectLifetimeDefault
121 | LifetimeName::Implicit
122 | LifetimeName::Error => Ident::invalid(),
123 LifetimeName::Underscore => Ident::with_dummy_span(kw::UnderscoreLifetime),
124 LifetimeName::Static => Ident::with_dummy_span(kw::StaticLifetime),
125 LifetimeName::Param(param_name) => param_name.ident(),
129 pub fn is_elided(&self) -> bool {
131 LifetimeName::ImplicitObjectLifetimeDefault
132 | LifetimeName::Implicit
133 | LifetimeName::Underscore => true,
135 // It might seem surprising that `Fresh(_)` counts as
136 // *not* elided -- but this is because, as far as the code
137 // in the compiler is concerned -- `Fresh(_)` variants act
138 // equivalently to "some fresh name". They correspond to
139 // early-bound regions on an impl, in other words.
140 LifetimeName::Error | LifetimeName::Param(_) | LifetimeName::Static => false,
144 fn is_static(&self) -> bool {
145 self == &LifetimeName::Static
148 pub fn normalize_to_macros_2_0(&self) -> LifetimeName {
150 LifetimeName::Param(param_name) => {
151 LifetimeName::Param(param_name.normalize_to_macros_2_0())
153 lifetime_name => lifetime_name,
158 impl fmt::Display for Lifetime {
159 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160 self.name.ident().fmt(f)
164 impl fmt::Debug for Lifetime {
165 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166 write!(f, "lifetime({}: {})", self.hir_id, self.name.ident())
171 pub fn is_elided(&self) -> bool {
172 self.name.is_elided()
175 pub fn is_static(&self) -> bool {
176 self.name.is_static()
180 /// A `Path` is essentially Rust's notion of a name; for instance,
181 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
182 /// along with a bunch of supporting information.
183 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
184 pub struct Path<'hir> {
186 /// The resolution for the path.
188 /// The segments in the path: the things separated by `::`.
189 pub segments: &'hir [PathSegment<'hir>],
193 pub fn is_global(&self) -> bool {
194 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
198 /// A segment of a path: an identifier, an optional lifetime, and a set of
200 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
201 pub struct PathSegment<'hir> {
202 /// The identifier portion of this path segment.
203 #[stable_hasher(project(name))]
205 // `id` and `res` are optional. We currently only use these in save-analysis,
206 // any path segments without these will not have save-analysis info and
207 // therefore will not have 'jump to def' in IDEs, but otherwise will not be
208 // affected. (In general, we don't bother to get the defs for synthesized
209 // segments, only for segments which have come from the AST).
210 pub hir_id: Option<HirId>,
211 pub res: Option<Res>,
213 /// Type/lifetime parameters attached to this path. They come in
214 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
215 /// this is more than just simple syntactic sugar; the use of
216 /// parens affects the region binding rules, so we preserve the
218 pub args: Option<&'hir GenericArgs<'hir>>,
220 /// Whether to infer remaining type parameters, if any.
221 /// This only applies to expression and pattern paths, and
222 /// out of those only the segments with no type parameters
223 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
224 pub infer_args: bool,
227 impl<'hir> PathSegment<'hir> {
228 /// Converts an identifier to the corresponding segment.
229 pub fn from_ident(ident: Ident) -> PathSegment<'hir> {
230 PathSegment { ident, hir_id: None, res: None, infer_args: true, args: None }
233 pub fn generic_args(&self) -> &GenericArgs<'hir> {
234 if let Some(ref args) = self.args {
237 const DUMMY: &GenericArgs<'_> = &GenericArgs::none();
243 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
244 pub struct ConstArg {
245 pub value: AnonConst,
249 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
250 pub enum GenericArg<'hir> {
256 impl GenericArg<'_> {
257 pub fn span(&self) -> Span {
259 GenericArg::Lifetime(l) => l.span,
260 GenericArg::Type(t) => t.span,
261 GenericArg::Const(c) => c.span,
265 pub fn id(&self) -> HirId {
267 GenericArg::Lifetime(l) => l.hir_id,
268 GenericArg::Type(t) => t.hir_id,
269 GenericArg::Const(c) => c.value.hir_id,
273 pub fn is_const(&self) -> bool {
275 GenericArg::Const(_) => true,
280 pub fn descr(&self) -> &'static str {
282 GenericArg::Lifetime(_) => "lifetime",
283 GenericArg::Type(_) => "type",
284 GenericArg::Const(_) => "constant",
289 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
290 pub struct GenericArgs<'hir> {
291 /// The generic arguments for this path segment.
292 pub args: &'hir [GenericArg<'hir>],
293 /// Bindings (equality constraints) on associated types, if present.
294 /// E.g., `Foo<A = Bar>`.
295 pub bindings: &'hir [TypeBinding<'hir>],
296 /// Were arguments written in parenthesized form `Fn(T) -> U`?
297 /// This is required mostly for pretty-printing and diagnostics,
298 /// but also for changing lifetime elision rules to be "function-like".
299 pub parenthesized: bool,
302 impl GenericArgs<'_> {
303 pub const fn none() -> Self {
304 Self { args: &[], bindings: &[], parenthesized: false }
307 pub fn is_empty(&self) -> bool {
308 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
311 pub fn inputs(&self) -> &[Ty<'_>] {
312 if self.parenthesized {
313 for arg in self.args {
315 GenericArg::Lifetime(_) => {}
316 GenericArg::Type(ref ty) => {
317 if let TyKind::Tup(ref tys) = ty.kind {
322 GenericArg::Const(_) => {}
326 panic!("GenericArgs::inputs: not a `Fn(T) -> U`");
329 pub fn own_counts(&self) -> GenericParamCount {
330 // We could cache this as a property of `GenericParamCount`, but
331 // the aim is to refactor this away entirely eventually and the
332 // presence of this method will be a constant reminder.
333 let mut own_counts: GenericParamCount = Default::default();
335 for arg in self.args {
337 GenericArg::Lifetime(_) => own_counts.lifetimes += 1,
338 GenericArg::Type(_) => own_counts.types += 1,
339 GenericArg::Const(_) => own_counts.consts += 1,
347 /// A modifier on a bound, currently this is only used for `?Sized`, where the
348 /// modifier is `Maybe`. Negative bounds should also be handled here.
349 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
350 #[derive(HashStable_Generic)]
351 pub enum TraitBoundModifier {
357 /// The AST represents all type param bounds as types.
358 /// `typeck::collect::compute_bounds` matches these against
359 /// the "special" built-in traits (see `middle::lang_items`) and
360 /// detects `Copy`, `Send` and `Sync`.
361 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
362 pub enum GenericBound<'hir> {
363 Trait(PolyTraitRef<'hir>, TraitBoundModifier),
367 impl GenericBound<'_> {
368 pub fn trait_ref(&self) -> Option<&TraitRef<'_>> {
370 GenericBound::Trait(data, _) => Some(&data.trait_ref),
375 pub fn span(&self) -> Span {
377 &GenericBound::Trait(ref t, ..) => t.span,
378 &GenericBound::Outlives(ref l) => l.span,
383 pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
385 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
386 pub enum LifetimeParamKind {
387 // Indicates that the lifetime definition was explicitly declared (e.g., in
388 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
391 // Indicates that the lifetime definition was synthetically added
392 // as a result of an in-band lifetime usage (e.g., in
393 // `fn foo(x: &'a u8) -> &'a u8 { x }`).
396 // Indication that the lifetime was elided (e.g., in both cases in
397 // `fn foo(x: &u8) -> &'_ u8 { x }`).
400 // Indication that the lifetime name was somehow in error.
404 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
405 pub enum GenericParamKind<'hir> {
406 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
408 kind: LifetimeParamKind,
411 default: Option<&'hir Ty<'hir>>,
412 synthetic: Option<SyntheticTyParamKind>,
419 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
420 pub struct GenericParam<'hir> {
423 pub attrs: &'hir [Attribute],
424 pub bounds: GenericBounds<'hir>,
426 pub pure_wrt_drop: bool,
427 pub kind: GenericParamKind<'hir>,
430 impl GenericParam<'hir> {
431 pub fn bounds_span(&self) -> Option<Span> {
432 self.bounds.iter().fold(None, |span, bound| {
433 let span = span.map(|s| s.to(bound.span())).unwrap_or_else(|| bound.span());
441 pub struct GenericParamCount {
442 pub lifetimes: usize,
447 /// Represents lifetimes and type parameters attached to a declaration
448 /// of a function, enum, trait, etc.
449 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
450 pub struct Generics<'hir> {
451 pub params: &'hir [GenericParam<'hir>],
452 pub where_clause: WhereClause<'hir>,
456 impl Generics<'hir> {
457 pub const fn empty() -> Generics<'hir> {
460 where_clause: WhereClause { predicates: &[], span: DUMMY_SP },
465 pub fn own_counts(&self) -> GenericParamCount {
466 // We could cache this as a property of `GenericParamCount`, but
467 // the aim is to refactor this away entirely eventually and the
468 // presence of this method will be a constant reminder.
469 let mut own_counts: GenericParamCount = Default::default();
471 for param in self.params {
473 GenericParamKind::Lifetime { .. } => own_counts.lifetimes += 1,
474 GenericParamKind::Type { .. } => own_counts.types += 1,
475 GenericParamKind::Const { .. } => own_counts.consts += 1,
482 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'_>> {
483 for param in self.params {
484 if name == param.name.ident().name {
491 pub fn spans(&self) -> MultiSpan {
492 if self.params.is_empty() {
495 self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
500 /// Synthetic type parameters are converted to another form during lowering; this allows
501 /// us to track the original form they had, and is useful for error messages.
502 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
503 #[derive(HashStable_Generic)]
504 pub enum SyntheticTyParamKind {
508 /// A where-clause in a definition.
509 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
510 pub struct WhereClause<'hir> {
511 pub predicates: &'hir [WherePredicate<'hir>],
512 // Only valid if predicates aren't empty.
516 impl WhereClause<'_> {
517 pub fn span(&self) -> Option<Span> {
518 if self.predicates.is_empty() { None } else { Some(self.span) }
521 /// The `WhereClause` under normal circumstances points at either the predicates or the empty
522 /// space where the `where` clause should be. Only of use for diagnostic suggestions.
523 pub fn span_for_predicates_or_empty_place(&self) -> Span {
528 /// A single predicate in a where-clause.
529 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
530 pub enum WherePredicate<'hir> {
531 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
532 BoundPredicate(WhereBoundPredicate<'hir>),
533 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
534 RegionPredicate(WhereRegionPredicate<'hir>),
535 /// An equality predicate (unsupported).
536 EqPredicate(WhereEqPredicate<'hir>),
539 impl WherePredicate<'_> {
540 pub fn span(&self) -> Span {
542 &WherePredicate::BoundPredicate(ref p) => p.span,
543 &WherePredicate::RegionPredicate(ref p) => p.span,
544 &WherePredicate::EqPredicate(ref p) => p.span,
549 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
550 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
551 pub struct WhereBoundPredicate<'hir> {
553 /// Any generics from a `for` binding.
554 pub bound_generic_params: &'hir [GenericParam<'hir>],
555 /// The type being bounded.
556 pub bounded_ty: &'hir Ty<'hir>,
557 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
558 pub bounds: GenericBounds<'hir>,
561 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
562 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
563 pub struct WhereRegionPredicate<'hir> {
565 pub lifetime: Lifetime,
566 pub bounds: GenericBounds<'hir>,
569 /// An equality predicate (e.g., `T = int`); currently unsupported.
570 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
571 pub struct WhereEqPredicate<'hir> {
574 pub lhs_ty: &'hir Ty<'hir>,
575 pub rhs_ty: &'hir Ty<'hir>,
578 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
579 pub struct ModuleItems {
580 // Use BTreeSets here so items are in the same order as in the
581 // list of all items in Crate
582 pub items: BTreeSet<HirId>,
583 pub trait_items: BTreeSet<TraitItemId>,
584 pub impl_items: BTreeSet<ImplItemId>,
587 /// A type representing only the top-level module.
588 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
589 pub struct CrateItem<'hir> {
590 pub module: Mod<'hir>,
591 pub attrs: &'hir [Attribute],
595 /// The top-level data structure that stores the entire contents of
596 /// the crate currently being compiled.
598 /// For more details, see the [rustc dev guide].
600 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
601 #[derive(RustcEncodable, RustcDecodable, Debug)]
602 pub struct Crate<'hir> {
603 pub item: CrateItem<'hir>,
604 pub exported_macros: &'hir [MacroDef<'hir>],
605 // Attributes from non-exported macros, kept only for collecting the library feature list.
606 pub non_exported_macro_attrs: &'hir [Attribute],
608 // N.B., we use a `BTreeMap` here so that `visit_all_items` iterates
609 // over the ids in increasing order. In principle it should not
610 // matter what order we visit things in, but in *practice* it
611 // does, because it can affect the order in which errors are
612 // detected, which in turn can make compile-fail tests yield
613 // slightly different results.
614 pub items: BTreeMap<HirId, Item<'hir>>,
616 pub trait_items: BTreeMap<TraitItemId, TraitItem<'hir>>,
617 pub impl_items: BTreeMap<ImplItemId, ImplItem<'hir>>,
618 pub bodies: BTreeMap<BodyId, Body<'hir>>,
619 pub trait_impls: BTreeMap<DefId, Vec<HirId>>,
621 /// A list of the body ids written out in the order in which they
622 /// appear in the crate. If you're going to process all the bodies
623 /// in the crate, you should iterate over this list rather than the keys
625 pub body_ids: Vec<BodyId>,
627 /// A list of modules written out in the order in which they
628 /// appear in the crate. This includes the main crate module.
629 pub modules: BTreeMap<HirId, ModuleItems>,
630 /// A list of proc macro HirIds, written out in the order in which
631 /// they are declared in the static array generated by proc_macro_harness.
632 pub proc_macros: Vec<HirId>,
636 pub fn item(&self, id: HirId) -> &Item<'hir> {
640 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem<'hir> {
641 &self.trait_items[&id]
644 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem<'hir> {
645 &self.impl_items[&id]
648 pub fn body(&self, id: BodyId) -> &Body<'hir> {
654 /// Visits all items in the crate in some deterministic (but
655 /// unspecified) order. If you just need to process every item,
656 /// but don't care about nesting, this method is the best choice.
658 /// If you do care about nesting -- usually because your algorithm
659 /// follows lexical scoping rules -- then you want a different
660 /// approach. You should override `visit_nested_item` in your
661 /// visitor and then call `intravisit::walk_crate` instead.
662 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
664 V: itemlikevisit::ItemLikeVisitor<'hir>,
666 for item in self.items.values() {
667 visitor.visit_item(item);
670 for trait_item in self.trait_items.values() {
671 visitor.visit_trait_item(trait_item);
674 for impl_item in self.impl_items.values() {
675 visitor.visit_impl_item(impl_item);
679 /// A parallel version of `visit_all_item_likes`.
680 pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
682 V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send,
686 par_for_each_in(&self.items, |(_, item)| {
687 visitor.visit_item(item);
691 par_for_each_in(&self.trait_items, |(_, trait_item)| {
692 visitor.visit_trait_item(trait_item);
696 par_for_each_in(&self.impl_items, |(_, impl_item)| {
697 visitor.visit_impl_item(impl_item);
704 /// A macro definition, in this crate or imported from another.
706 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
707 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
708 pub struct MacroDef<'hir> {
710 pub vis: Visibility<'hir>,
711 pub attrs: &'hir [Attribute],
714 pub ast: ast::MacroDef,
717 /// A block of statements `{ .. }`, which may have a label (in this case the
718 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
719 /// the `rules` being anything but `DefaultBlock`.
720 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
721 pub struct Block<'hir> {
722 /// Statements in a block.
723 pub stmts: &'hir [Stmt<'hir>],
724 /// An expression at the end of the block
725 /// without a semicolon, if any.
726 pub expr: Option<&'hir Expr<'hir>>,
727 #[stable_hasher(ignore)]
729 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
730 pub rules: BlockCheckMode,
732 /// If true, then there may exist `break 'a` values that aim to
733 /// break out of this block early.
734 /// Used by `'label: {}` blocks and by `try {}` blocks.
735 pub targeted_by_break: bool,
738 #[derive(Debug, RustcEncodable, RustcDecodable, HashStable_Generic)]
739 pub struct Pat<'hir> {
740 #[stable_hasher(ignore)]
742 pub kind: PatKind<'hir>,
747 // FIXME(#19596) this is a workaround, but there should be a better way
748 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'_>) -> bool) -> bool {
755 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
756 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
757 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
758 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
759 Slice(before, slice, after) => {
760 before.iter().chain(slice.iter()).chain(after.iter()).all(|p| p.walk_short_(it))
765 /// Walk the pattern in left-to-right order,
766 /// short circuiting (with `.all(..)`) if `false` is returned.
768 /// Note that when visiting e.g. `Tuple(ps)`,
769 /// if visiting `ps[0]` returns `false`,
770 /// then `ps[1]` will not be visited.
771 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'_>) -> bool) -> bool {
772 self.walk_short_(&mut it)
775 // FIXME(#19596) this is a workaround, but there should be a better way
776 fn walk_(&self, it: &mut impl FnMut(&Pat<'_>) -> bool) {
783 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
784 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
785 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
786 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
787 Slice(before, slice, after) => {
788 before.iter().chain(slice.iter()).chain(after.iter()).for_each(|p| p.walk_(it))
793 /// Walk the pattern in left-to-right order.
795 /// If `it(pat)` returns `false`, the children are not visited.
796 pub fn walk(&self, mut it: impl FnMut(&Pat<'_>) -> bool) {
800 /// Walk the pattern in left-to-right order.
802 /// If you always want to recurse, prefer this method over `walk`.
803 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
811 /// A single field in a struct pattern.
813 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
814 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
815 /// except `is_shorthand` is true.
816 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
817 pub struct FieldPat<'hir> {
818 #[stable_hasher(ignore)]
820 /// The identifier for the field.
821 #[stable_hasher(project(name))]
823 /// The pattern the field is destructured to.
824 pub pat: &'hir Pat<'hir>,
825 pub is_shorthand: bool,
829 /// Explicit binding annotations given in the HIR for a binding. Note
830 /// that this is not the final binding *mode* that we infer after type
832 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
833 pub enum BindingAnnotation {
834 /// No binding annotation given: this means that the final binding mode
835 /// will depend on whether we have skipped through a `&` reference
836 /// when matching. For example, the `x` in `Some(x)` will have binding
837 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
838 /// ultimately be inferred to be by-reference.
840 /// Note that implicit reference skipping is not implemented yet (#42640).
843 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
846 /// Annotated as `ref`, like `ref x`
849 /// Annotated as `ref mut x`.
853 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
859 impl fmt::Display for RangeEnd {
860 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
861 f.write_str(match self {
862 RangeEnd::Included => "..=",
863 RangeEnd::Excluded => "..",
868 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
869 pub enum PatKind<'hir> {
870 /// Represents a wildcard pattern (i.e., `_`).
873 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
874 /// The `HirId` is the canonical ID for the variable being bound,
875 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
876 /// which is the pattern ID of the first `x`.
877 Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
879 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
880 /// The `bool` is `true` in the presence of a `..`.
881 Struct(QPath<'hir>, &'hir [FieldPat<'hir>], bool),
883 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
884 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
885 /// `0 <= position <= subpats.len()`
886 TupleStruct(QPath<'hir>, &'hir [&'hir Pat<'hir>], Option<usize>),
888 /// An or-pattern `A | B | C`.
889 /// Invariant: `pats.len() >= 2`.
890 Or(&'hir [&'hir Pat<'hir>]),
892 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
895 /// A tuple pattern (e.g., `(a, b)`).
896 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
897 /// `0 <= position <= subpats.len()`
898 Tuple(&'hir [&'hir Pat<'hir>], Option<usize>),
901 Box(&'hir Pat<'hir>),
903 /// A reference pattern (e.g., `&mut (a, b)`).
904 Ref(&'hir Pat<'hir>, Mutability),
907 Lit(&'hir Expr<'hir>),
909 /// A range pattern (e.g., `1..=2` or `1..2`).
910 Range(Option<&'hir Expr<'hir>>, Option<&'hir Expr<'hir>>, RangeEnd),
912 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
914 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
915 /// If `slice` exists, then `after` can be non-empty.
917 /// The representation for e.g., `[a, b, .., c, d]` is:
919 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
921 Slice(&'hir [&'hir Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [&'hir Pat<'hir>]),
924 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
926 /// The `+` operator (addition).
928 /// The `-` operator (subtraction).
930 /// The `*` operator (multiplication).
932 /// The `/` operator (division).
934 /// The `%` operator (modulus).
936 /// The `&&` operator (logical and).
938 /// The `||` operator (logical or).
940 /// The `^` operator (bitwise xor).
942 /// The `&` operator (bitwise and).
944 /// The `|` operator (bitwise or).
946 /// The `<<` operator (shift left).
948 /// The `>>` operator (shift right).
950 /// The `==` operator (equality).
952 /// The `<` operator (less than).
954 /// The `<=` operator (less than or equal to).
956 /// The `!=` operator (not equal to).
958 /// The `>=` operator (greater than or equal to).
960 /// The `>` operator (greater than).
965 pub fn as_str(self) -> &'static str {
967 BinOpKind::Add => "+",
968 BinOpKind::Sub => "-",
969 BinOpKind::Mul => "*",
970 BinOpKind::Div => "/",
971 BinOpKind::Rem => "%",
972 BinOpKind::And => "&&",
973 BinOpKind::Or => "||",
974 BinOpKind::BitXor => "^",
975 BinOpKind::BitAnd => "&",
976 BinOpKind::BitOr => "|",
977 BinOpKind::Shl => "<<",
978 BinOpKind::Shr => ">>",
979 BinOpKind::Eq => "==",
980 BinOpKind::Lt => "<",
981 BinOpKind::Le => "<=",
982 BinOpKind::Ne => "!=",
983 BinOpKind::Ge => ">=",
984 BinOpKind::Gt => ">",
988 pub fn is_lazy(self) -> bool {
990 BinOpKind::And | BinOpKind::Or => true,
995 pub fn is_shift(self) -> bool {
997 BinOpKind::Shl | BinOpKind::Shr => true,
1002 pub fn is_comparison(self) -> bool {
1009 | BinOpKind::Ge => true,
1021 | BinOpKind::Shr => false,
1025 /// Returns `true` if the binary operator takes its arguments by value.
1026 pub fn is_by_value(self) -> bool {
1027 !self.is_comparison()
1031 impl Into<ast::BinOpKind> for BinOpKind {
1032 fn into(self) -> ast::BinOpKind {
1034 BinOpKind::Add => ast::BinOpKind::Add,
1035 BinOpKind::Sub => ast::BinOpKind::Sub,
1036 BinOpKind::Mul => ast::BinOpKind::Mul,
1037 BinOpKind::Div => ast::BinOpKind::Div,
1038 BinOpKind::Rem => ast::BinOpKind::Rem,
1039 BinOpKind::And => ast::BinOpKind::And,
1040 BinOpKind::Or => ast::BinOpKind::Or,
1041 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1042 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1043 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1044 BinOpKind::Shl => ast::BinOpKind::Shl,
1045 BinOpKind::Shr => ast::BinOpKind::Shr,
1046 BinOpKind::Eq => ast::BinOpKind::Eq,
1047 BinOpKind::Lt => ast::BinOpKind::Lt,
1048 BinOpKind::Le => ast::BinOpKind::Le,
1049 BinOpKind::Ne => ast::BinOpKind::Ne,
1050 BinOpKind::Ge => ast::BinOpKind::Ge,
1051 BinOpKind::Gt => ast::BinOpKind::Gt,
1056 pub type BinOp = Spanned<BinOpKind>;
1058 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1060 /// The `*` operator (deferencing).
1062 /// The `!` operator (logical negation).
1064 /// The `-` operator (negation).
1069 pub fn as_str(self) -> &'static str {
1071 Self::UnDeref => "*",
1077 /// Returns `true` if the unary operator takes its argument by value.
1078 pub fn is_by_value(self) -> bool {
1080 Self::UnNeg | Self::UnNot => true,
1087 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1088 pub struct Stmt<'hir> {
1090 pub kind: StmtKind<'hir>,
1094 /// The contents of a statement.
1095 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1096 pub enum StmtKind<'hir> {
1097 /// A local (`let`) binding.
1098 Local(&'hir Local<'hir>),
1100 /// An item binding.
1103 /// An expression without a trailing semi-colon (must have unit type).
1104 Expr(&'hir Expr<'hir>),
1106 /// An expression with a trailing semi-colon (may have any type).
1107 Semi(&'hir Expr<'hir>),
1110 impl StmtKind<'hir> {
1111 pub fn attrs(&self) -> &'hir [Attribute] {
1113 StmtKind::Local(ref l) => &l.attrs,
1114 StmtKind::Item(_) => &[],
1115 StmtKind::Expr(ref e) | StmtKind::Semi(ref e) => &e.attrs,
1120 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1121 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1122 pub struct Local<'hir> {
1123 pub pat: &'hir Pat<'hir>,
1124 /// Type annotation, if any (otherwise the type will be inferred).
1125 pub ty: Option<&'hir Ty<'hir>>,
1126 /// Initializer expression to set the value, if any.
1127 pub init: Option<&'hir Expr<'hir>>,
1131 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1132 /// desugaring. Otherwise will be `Normal`.
1133 pub source: LocalSource,
1136 /// Represents a single arm of a `match` expression, e.g.
1137 /// `<pat> (if <guard>) => <body>`.
1138 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1139 pub struct Arm<'hir> {
1140 #[stable_hasher(ignore)]
1143 pub attrs: &'hir [Attribute],
1144 /// If this pattern and the optional guard matches, then `body` is evaluated.
1145 pub pat: &'hir Pat<'hir>,
1146 /// Optional guard clause.
1147 pub guard: Option<Guard<'hir>>,
1148 /// The expression the arm evaluates to if this arm matches.
1149 pub body: &'hir Expr<'hir>,
1152 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1153 pub enum Guard<'hir> {
1154 If(&'hir Expr<'hir>),
1157 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1158 pub struct Field<'hir> {
1159 #[stable_hasher(ignore)]
1162 pub expr: &'hir Expr<'hir>,
1164 pub is_shorthand: bool,
1167 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1168 pub enum BlockCheckMode {
1170 UnsafeBlock(UnsafeSource),
1171 PushUnsafeBlock(UnsafeSource),
1172 PopUnsafeBlock(UnsafeSource),
1175 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1176 pub enum UnsafeSource {
1181 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1186 /// The body of a function, closure, or constant value. In the case of
1187 /// a function, the body contains not only the function body itself
1188 /// (which is an expression), but also the argument patterns, since
1189 /// those are something that the caller doesn't really care about.
1194 /// fn foo((x, y): (u32, u32)) -> u32 {
1199 /// Here, the `Body` associated with `foo()` would contain:
1201 /// - an `params` array containing the `(x, y)` pattern
1202 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1203 /// - `generator_kind` would be `None`
1205 /// All bodies have an **owner**, which can be accessed via the HIR
1206 /// map using `body_owner_def_id()`.
1207 #[derive(RustcEncodable, RustcDecodable, Debug)]
1208 pub struct Body<'hir> {
1209 pub params: &'hir [Param<'hir>],
1210 pub value: Expr<'hir>,
1211 pub generator_kind: Option<GeneratorKind>,
1215 pub fn id(&self) -> BodyId {
1216 BodyId { hir_id: self.value.hir_id }
1219 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1224 /// The type of source expression that caused this generator to be created.
1225 #[derive(Clone, PartialEq, Eq, HashStable_Generic, RustcEncodable, RustcDecodable, Debug, Copy)]
1226 pub enum GeneratorKind {
1227 /// An explicit `async` block or the body of an async function.
1228 Async(AsyncGeneratorKind),
1230 /// A generator literal created via a `yield` inside a closure.
1234 impl fmt::Display for GeneratorKind {
1235 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1237 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1238 GeneratorKind::Gen => f.write_str("generator"),
1243 /// In the case of a generator created as part of an async construct,
1244 /// which kind of async construct caused it to be created?
1246 /// This helps error messages but is also used to drive coercions in
1247 /// type-checking (see #60424).
1248 #[derive(Clone, PartialEq, Eq, HashStable_Generic, RustcEncodable, RustcDecodable, Debug, Copy)]
1249 pub enum AsyncGeneratorKind {
1250 /// An explicit `async` block written by the user.
1253 /// An explicit `async` block written by the user.
1256 /// The `async` block generated as the body of an async function.
1260 impl fmt::Display for AsyncGeneratorKind {
1261 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1262 f.write_str(match self {
1263 AsyncGeneratorKind::Block => "`async` block",
1264 AsyncGeneratorKind::Closure => "`async` closure body",
1265 AsyncGeneratorKind::Fn => "`async fn` body",
1270 #[derive(Copy, Clone, Debug)]
1271 pub enum BodyOwnerKind {
1272 /// Functions and methods.
1278 /// Constants and associated constants.
1281 /// Initializer of a `static` item.
1285 impl BodyOwnerKind {
1286 pub fn is_fn_or_closure(self) -> bool {
1288 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1289 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1295 pub type Lit = Spanned<LitKind>;
1297 /// A constant (expression) that's not an item or associated item,
1298 /// but needs its own `DefId` for type-checking, const-eval, etc.
1299 /// These are usually found nested inside types (e.g., array lengths)
1300 /// or expressions (e.g., repeat counts), and also used to define
1301 /// explicit discriminant values for enum variants.
1302 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1303 pub struct AnonConst {
1309 #[derive(Debug, RustcEncodable, RustcDecodable)]
1310 pub struct Expr<'hir> {
1312 pub kind: ExprKind<'hir>,
1317 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1318 #[cfg(target_arch = "x86_64")]
1319 rustc_data_structures::static_assert_size!(Expr<'static>, 64);
1322 pub fn precedence(&self) -> ExprPrecedence {
1324 ExprKind::Box(_) => ExprPrecedence::Box,
1325 ExprKind::Array(_) => ExprPrecedence::Array,
1326 ExprKind::Call(..) => ExprPrecedence::Call,
1327 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1328 ExprKind::Tup(_) => ExprPrecedence::Tup,
1329 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1330 ExprKind::Unary(..) => ExprPrecedence::Unary,
1331 ExprKind::Lit(_) => ExprPrecedence::Lit,
1332 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1333 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1334 ExprKind::Loop(..) => ExprPrecedence::Loop,
1335 ExprKind::Match(..) => ExprPrecedence::Match,
1336 ExprKind::Closure(..) => ExprPrecedence::Closure,
1337 ExprKind::Block(..) => ExprPrecedence::Block,
1338 ExprKind::Assign(..) => ExprPrecedence::Assign,
1339 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1340 ExprKind::Field(..) => ExprPrecedence::Field,
1341 ExprKind::Index(..) => ExprPrecedence::Index,
1342 ExprKind::Path(..) => ExprPrecedence::Path,
1343 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1344 ExprKind::Break(..) => ExprPrecedence::Break,
1345 ExprKind::Continue(..) => ExprPrecedence::Continue,
1346 ExprKind::Ret(..) => ExprPrecedence::Ret,
1347 ExprKind::LlvmInlineAsm(..) => ExprPrecedence::InlineAsm,
1348 ExprKind::Struct(..) => ExprPrecedence::Struct,
1349 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1350 ExprKind::Yield(..) => ExprPrecedence::Yield,
1351 ExprKind::Err => ExprPrecedence::Err,
1355 // Whether this looks like a place expr, without checking for deref
1357 // This will return `true` in some potentially surprising cases such as
1358 // `CONSTANT.field`.
1359 pub fn is_syntactic_place_expr(&self) -> bool {
1360 self.is_place_expr(|_| true)
1363 // Whether this is a place expression.
1364 // `allow_projections_from` should return `true` if indexing a field or
1365 // index expression based on the given expression should be considered a
1366 // place expression.
1367 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1369 ExprKind::Path(QPath::Resolved(_, ref path)) => match path.res {
1370 Res::Local(..) | Res::Def(DefKind::Static, _) | Res::Err => true,
1374 // Type ascription inherits its place expression kind from its
1376 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1377 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1379 ExprKind::Unary(UnOp::UnDeref, _) => true,
1381 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1382 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1385 // Partially qualified paths in expressions can only legally
1386 // refer to associated items which are always rvalues.
1387 ExprKind::Path(QPath::TypeRelative(..))
1388 | ExprKind::Call(..)
1389 | ExprKind::MethodCall(..)
1390 | ExprKind::Struct(..)
1392 | ExprKind::Match(..)
1393 | ExprKind::Closure(..)
1394 | ExprKind::Block(..)
1395 | ExprKind::Repeat(..)
1396 | ExprKind::Array(..)
1397 | ExprKind::Break(..)
1398 | ExprKind::Continue(..)
1400 | ExprKind::Loop(..)
1401 | ExprKind::Assign(..)
1402 | ExprKind::LlvmInlineAsm(..)
1403 | ExprKind::AssignOp(..)
1405 | ExprKind::Unary(..)
1407 | ExprKind::AddrOf(..)
1408 | ExprKind::Binary(..)
1409 | ExprKind::Yield(..)
1410 | ExprKind::Cast(..)
1411 | ExprKind::DropTemps(..)
1412 | ExprKind::Err => false,
1416 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1417 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1418 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1419 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1420 /// beyond remembering to call this function before doing analysis on it.
1421 pub fn peel_drop_temps(&self) -> &Self {
1422 let mut expr = self;
1423 while let ExprKind::DropTemps(inner) = &expr.kind {
1430 /// Checks if the specified expression is a built-in range literal.
1431 /// (See: `LoweringContext::lower_expr()`).
1433 /// FIXME(#60607): This function is a hack. If and when we have `QPath::Lang(...)`,
1434 /// we can use that instead as simpler, more reliable mechanism, as opposed to using `SourceMap`.
1435 pub fn is_range_literal(sm: &SourceMap, expr: &Expr<'_>) -> bool {
1436 // Returns whether the given path represents a (desugared) range,
1437 // either in std or core, i.e. has either a `::std::ops::Range` or
1438 // `::core::ops::Range` prefix.
1439 fn is_range_path(path: &Path<'_>) -> bool {
1440 let segs: Vec<_> = path.segments.iter().map(|seg| seg.ident.to_string()).collect();
1441 let segs: Vec<_> = segs.iter().map(|seg| &**seg).collect();
1443 // "{{root}}" is the equivalent of `::` prefix in `Path`.
1444 if let ["{{root}}", std_core, "ops", range] = segs.as_slice() {
1445 (*std_core == "std" || *std_core == "core") && range.starts_with("Range")
1451 // Check whether a span corresponding to a range expression is a
1452 // range literal, rather than an explicit struct or `new()` call.
1453 fn is_lit(sm: &SourceMap, span: &Span) -> bool {
1454 let end_point = sm.end_point(*span);
1456 if let Ok(end_string) = sm.span_to_snippet(end_point) {
1457 !(end_string.ends_with('}') || end_string.ends_with(')'))
1464 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1465 ExprKind::Struct(ref qpath, _, _) => {
1466 if let QPath::Resolved(None, ref path) = **qpath {
1467 return is_range_path(&path) && is_lit(sm, &expr.span);
1471 // `..` desugars to its struct path.
1472 ExprKind::Path(QPath::Resolved(None, ref path)) => {
1473 return is_range_path(&path) && is_lit(sm, &expr.span);
1476 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1477 ExprKind::Call(ref func, _) => {
1478 if let ExprKind::Path(QPath::TypeRelative(ref ty, ref segment)) = func.kind {
1479 if let TyKind::Path(QPath::Resolved(None, ref path)) = ty.kind {
1480 let new_call = segment.ident.name == sym::new;
1481 return is_range_path(&path) && is_lit(sm, &expr.span) && new_call;
1492 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1493 pub enum ExprKind<'hir> {
1494 /// A `box x` expression.
1495 Box(&'hir Expr<'hir>),
1496 /// An array (e.g., `[a, b, c, d]`).
1497 Array(&'hir [Expr<'hir>]),
1498 /// A function call.
1500 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1501 /// and the second field is the list of arguments.
1502 /// This also represents calling the constructor of
1503 /// tuple-like ADTs such as tuple structs and enum variants.
1504 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1505 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1507 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1508 /// (within the angle brackets).
1509 /// The first element of the vector of `Expr`s is the expression that evaluates
1510 /// to the object on which the method is being called on (the receiver),
1511 /// and the remaining elements are the rest of the arguments.
1512 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1513 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1515 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1516 /// the `hir_id` of the `MethodCall` node itself.
1518 /// [`type_dependent_def_id`]: ../ty/struct.TypeckTables.html#method.type_dependent_def_id
1519 MethodCall(&'hir PathSegment<'hir>, Span, &'hir [Expr<'hir>]),
1520 /// A tuple (e.g., `(a, b, c, d)`).
1521 Tup(&'hir [Expr<'hir>]),
1522 /// A binary operation (e.g., `a + b`, `a * b`).
1523 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1524 /// A unary operation (e.g., `!x`, `*x`).
1525 Unary(UnOp, &'hir Expr<'hir>),
1526 /// A literal (e.g., `1`, `"foo"`).
1528 /// A cast (e.g., `foo as f64`).
1529 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1530 /// A type reference (e.g., `Foo`).
1531 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1532 /// Wraps the expression in a terminating scope.
1533 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1535 /// This construct only exists to tweak the drop order in HIR lowering.
1536 /// An example of that is the desugaring of `for` loops.
1537 DropTemps(&'hir Expr<'hir>),
1538 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1540 /// I.e., `'label: loop { <block> }`.
1541 Loop(&'hir Block<'hir>, Option<Label>, LoopSource),
1542 /// A `match` block, with a source that indicates whether or not it is
1543 /// the result of a desugaring, and if so, which kind.
1544 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1545 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1547 /// The `Span` is the argument block `|...|`.
1549 /// This may also be a generator literal or an `async block` as indicated by the
1550 /// `Option<Movability>`.
1551 Closure(CaptureBy, &'hir FnDecl<'hir>, BodyId, Span, Option<Movability>),
1552 /// A block (e.g., `'label: { ... }`).
1553 Block(&'hir Block<'hir>, Option<Label>),
1555 /// An assignment (e.g., `a = foo()`).
1556 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1557 /// An assignment with an operator.
1560 AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1561 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1562 Field(&'hir Expr<'hir>, Ident),
1563 /// An indexing operation (`foo[2]`).
1564 Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1566 /// Path to a definition, possibly containing lifetime or type parameters.
1569 /// A referencing operation (i.e., `&a` or `&mut a`).
1570 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1571 /// A `break`, with an optional label to break.
1572 Break(Destination, Option<&'hir Expr<'hir>>),
1573 /// A `continue`, with an optional label.
1574 Continue(Destination),
1575 /// A `return`, with an optional value to be returned.
1576 Ret(Option<&'hir Expr<'hir>>),
1578 /// Inline assembly (from `llvm_asm!`), with its outputs and inputs.
1579 LlvmInlineAsm(&'hir LlvmInlineAsm<'hir>),
1581 /// A struct or struct-like variant literal expression.
1583 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1584 /// where `base` is the `Option<Expr>`.
1585 Struct(&'hir QPath<'hir>, &'hir [Field<'hir>], Option<&'hir Expr<'hir>>),
1587 /// An array literal constructed from one repeated element.
1589 /// E.g., `[1; 5]`. The first expression is the element
1590 /// to be repeated; the second is the number of times to repeat it.
1591 Repeat(&'hir Expr<'hir>, AnonConst),
1593 /// A suspension point for generators (i.e., `yield <expr>`).
1594 Yield(&'hir Expr<'hir>, YieldSource),
1596 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1600 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1602 /// To resolve the path to a `DefId`, call [`qpath_res`].
1604 /// [`qpath_res`]: ../ty/struct.TypeckTables.html#method.qpath_res
1605 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1606 pub enum QPath<'hir> {
1607 /// Path to a definition, optionally "fully-qualified" with a `Self`
1608 /// type, if the path points to an associated item in a trait.
1610 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1611 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1612 /// even though they both have the same two-segment `Clone::clone` `Path`.
1613 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
1615 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1616 /// Will be resolved by type-checking to an associated item.
1618 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1619 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1620 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1621 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
1624 /// Hints at the original code for a let statement.
1625 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1626 pub enum LocalSource {
1627 /// A `match _ { .. }`.
1629 /// A desugared `for _ in _ { .. }` loop.
1631 /// When lowering async functions, we create locals within the `async move` so that
1632 /// all parameters are dropped after the future is polled.
1634 /// ```ignore (pseudo-Rust)
1635 /// async fn foo(<pattern> @ x: Type) {
1637 /// let <pattern> = x;
1642 /// A desugared `<expr>.await`.
1646 /// Hints at the original code for a `match _ { .. }`.
1647 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1648 #[derive(HashStable_Generic)]
1649 pub enum MatchSource {
1650 /// A `match _ { .. }`.
1652 /// An `if _ { .. }` (optionally with `else { .. }`).
1653 IfDesugar { contains_else_clause: bool },
1654 /// An `if let _ = _ { .. }` (optionally with `else { .. }`).
1655 IfLetDesugar { contains_else_clause: bool },
1656 /// A `while _ { .. }` (which was desugared to a `loop { match _ { .. } }`).
1658 /// A `while let _ = _ { .. }` (which was desugared to a
1659 /// `loop { match _ { .. } }`).
1661 /// A desugared `for _ in _ { .. }` loop.
1663 /// A desugared `?` operator.
1665 /// A desugared `<expr>.await`.
1670 pub fn name(self) -> &'static str {
1674 IfDesugar { .. } | IfLetDesugar { .. } => "if",
1675 WhileDesugar | WhileLetDesugar => "while",
1676 ForLoopDesugar => "for",
1678 AwaitDesugar => ".await",
1683 /// The loop type that yielded an `ExprKind::Loop`.
1684 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1685 pub enum LoopSource {
1686 /// A `loop { .. }` loop.
1688 /// A `while _ { .. }` loop.
1690 /// A `while let _ = _ { .. }` loop.
1692 /// A `for _ in _ { .. }` loop.
1697 pub fn name(self) -> &'static str {
1699 LoopSource::Loop => "loop",
1700 LoopSource::While | LoopSource::WhileLet => "while",
1701 LoopSource::ForLoop => "for",
1706 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1707 pub enum LoopIdError {
1709 UnlabeledCfInWhileCondition,
1713 impl fmt::Display for LoopIdError {
1714 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1715 f.write_str(match self {
1716 LoopIdError::OutsideLoopScope => "not inside loop scope",
1717 LoopIdError::UnlabeledCfInWhileCondition => {
1718 "unlabeled control flow (break or continue) in while condition"
1720 LoopIdError::UnresolvedLabel => "label not found",
1725 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1726 pub struct Destination {
1727 // This is `Some(_)` iff there is an explicit user-specified `label
1728 pub label: Option<Label>,
1730 // These errors are caught and then reported during the diagnostics pass in
1731 // librustc_passes/loops.rs
1732 pub target_id: Result<HirId, LoopIdError>,
1735 /// The yield kind that caused an `ExprKind::Yield`.
1736 #[derive(Copy, Clone, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable, HashStable_Generic)]
1737 pub enum YieldSource {
1738 /// An `<expr>.await`.
1740 /// A plain `yield`.
1744 impl fmt::Display for YieldSource {
1745 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1746 f.write_str(match self {
1747 YieldSource::Await => "`await`",
1748 YieldSource::Yield => "`yield`",
1753 impl From<GeneratorKind> for YieldSource {
1754 fn from(kind: GeneratorKind) -> Self {
1756 // Guess based on the kind of the current generator.
1757 GeneratorKind::Gen => Self::Yield,
1758 GeneratorKind::Async(_) => Self::Await,
1763 // N.B., if you change this, you'll probably want to change the corresponding
1764 // type structure in middle/ty.rs as well.
1765 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1766 pub struct MutTy<'hir> {
1767 pub ty: &'hir Ty<'hir>,
1768 pub mutbl: Mutability,
1771 /// Represents a function's signature in a trait declaration,
1772 /// trait implementation, or a free function.
1773 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1774 pub struct FnSig<'hir> {
1775 pub header: FnHeader,
1776 pub decl: &'hir FnDecl<'hir>,
1779 // The bodies for items are stored "out of line", in a separate
1780 // hashmap in the `Crate`. Here we just record the node-id of the item
1781 // so it can fetched later.
1782 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1783 pub struct TraitItemId {
1787 /// Represents an item declaration within a trait declaration,
1788 /// possibly including a default implementation. A trait item is
1789 /// either required (meaning it doesn't have an implementation, just a
1790 /// signature) or provided (meaning it has a default implementation).
1791 #[derive(RustcEncodable, RustcDecodable, Debug)]
1792 pub struct TraitItem<'hir> {
1795 pub attrs: &'hir [Attribute],
1796 pub generics: Generics<'hir>,
1797 pub kind: TraitItemKind<'hir>,
1801 /// Represents a trait method's body (or just argument names).
1802 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1803 pub enum TraitFn<'hir> {
1804 /// No default body in the trait, just a signature.
1805 Required(&'hir [Ident]),
1807 /// Both signature and body are provided in the trait.
1811 /// Represents a trait method or associated constant or type
1812 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1813 pub enum TraitItemKind<'hir> {
1814 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
1815 Const(&'hir Ty<'hir>, Option<BodyId>),
1816 /// An associated function with an optional body.
1817 Fn(FnSig<'hir>, TraitFn<'hir>),
1818 /// An associated type with (possibly empty) bounds and optional concrete
1820 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
1823 // The bodies for items are stored "out of line", in a separate
1824 // hashmap in the `Crate`. Here we just record the node-id of the item
1825 // so it can fetched later.
1826 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1827 pub struct ImplItemId {
1831 /// Represents anything within an `impl` block.
1832 #[derive(RustcEncodable, RustcDecodable, Debug)]
1833 pub struct ImplItem<'hir> {
1836 pub vis: Visibility<'hir>,
1837 pub defaultness: Defaultness,
1838 pub attrs: &'hir [Attribute],
1839 pub generics: Generics<'hir>,
1840 pub kind: ImplItemKind<'hir>,
1844 /// Represents various kinds of content within an `impl`.
1845 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1846 pub enum ImplItemKind<'hir> {
1847 /// An associated constant of the given type, set to the constant result
1848 /// of the expression.
1849 Const(&'hir Ty<'hir>, BodyId),
1850 /// An associated function implementation with the given signature and body.
1851 Fn(FnSig<'hir>, BodyId),
1852 /// An associated type.
1853 TyAlias(&'hir Ty<'hir>),
1854 /// An associated `type = impl Trait`.
1855 OpaqueTy(GenericBounds<'hir>),
1858 impl ImplItemKind<'_> {
1859 pub fn namespace(&self) -> Namespace {
1861 ImplItemKind::OpaqueTy(..) | ImplItemKind::TyAlias(..) => Namespace::TypeNS,
1862 ImplItemKind::Const(..) | ImplItemKind::Fn(..) => Namespace::ValueNS,
1867 // The name of the associated type for `Fn` return types.
1868 pub const FN_OUTPUT_NAME: Symbol = sym::Output;
1870 /// Bind a type to an associated type (i.e., `A = Foo`).
1872 /// Bindings like `A: Debug` are represented as a special type `A =
1873 /// $::Debug` that is understood by the astconv code.
1875 /// FIXME(alexreg): why have a separate type for the binding case,
1876 /// wouldn't it be better to make the `ty` field an enum like the
1880 /// enum TypeBindingKind {
1885 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1886 pub struct TypeBinding<'hir> {
1888 #[stable_hasher(project(name))]
1890 pub kind: TypeBindingKind<'hir>,
1894 // Represents the two kinds of type bindings.
1895 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1896 pub enum TypeBindingKind<'hir> {
1897 /// E.g., `Foo<Bar: Send>`.
1898 Constraint { bounds: &'hir [GenericBound<'hir>] },
1899 /// E.g., `Foo<Bar = ()>`.
1900 Equality { ty: &'hir Ty<'hir> },
1903 impl TypeBinding<'_> {
1904 pub fn ty(&self) -> &Ty<'_> {
1906 TypeBindingKind::Equality { ref ty } => ty,
1907 _ => panic!("expected equality type binding for parenthesized generic args"),
1912 #[derive(Debug, RustcEncodable, RustcDecodable)]
1913 pub struct Ty<'hir> {
1915 pub kind: TyKind<'hir>,
1919 /// Not represented directly in the AST; referred to by name through a `ty_path`.
1920 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1921 #[derive(HashStable_Generic)]
1931 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1932 pub struct BareFnTy<'hir> {
1933 pub unsafety: Unsafety,
1935 pub generic_params: &'hir [GenericParam<'hir>],
1936 pub decl: &'hir FnDecl<'hir>,
1937 pub param_names: &'hir [Ident],
1940 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1941 pub struct OpaqueTy<'hir> {
1942 pub generics: Generics<'hir>,
1943 pub bounds: GenericBounds<'hir>,
1944 pub impl_trait_fn: Option<DefId>,
1945 pub origin: OpaqueTyOrigin,
1948 /// From whence the opaque type came.
1949 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1950 pub enum OpaqueTyOrigin {
1951 /// `type Foo = impl Trait;`
1957 /// Impl trait in bindings, consts, statics, bounds.
1961 /// The various kinds of types recognized by the compiler.
1962 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1963 pub enum TyKind<'hir> {
1964 /// A variable length slice (i.e., `[T]`).
1965 Slice(&'hir Ty<'hir>),
1966 /// A fixed length array (i.e., `[T; n]`).
1967 Array(&'hir Ty<'hir>, AnonConst),
1968 /// A raw pointer (i.e., `*const T` or `*mut T`).
1970 /// A reference (i.e., `&'a T` or `&'a mut T`).
1971 Rptr(Lifetime, MutTy<'hir>),
1972 /// A bare function (e.g., `fn(usize) -> bool`).
1973 BareFn(&'hir BareFnTy<'hir>),
1974 /// The never type (`!`).
1976 /// A tuple (`(A, B, C, D, ...)`).
1977 Tup(&'hir [Ty<'hir>]),
1978 /// A path to a type definition (`module::module::...::Type`), or an
1979 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
1981 /// Type parameters may be stored in each `PathSegment`.
1983 /// A type definition itself. This is currently only used for the `type Foo = impl Trait`
1984 /// item that `impl Trait` in return position desugars to.
1986 /// The generic argument list contains the lifetimes (and in the future possibly parameters)
1987 /// that are actually bound on the `impl Trait`.
1988 Def(ItemId, &'hir [GenericArg<'hir>]),
1989 /// A trait object type `Bound1 + Bound2 + Bound3`
1990 /// where `Bound` is a trait or a lifetime.
1991 TraitObject(&'hir [PolyTraitRef<'hir>], Lifetime),
1994 /// `TyKind::Infer` means the type should be inferred instead of it having been
1995 /// specified. This can appear anywhere in a type.
1997 /// Placeholder for a type that has failed to be defined.
2001 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic, PartialEq)]
2002 pub struct LlvmInlineAsmOutput {
2003 pub constraint: Symbol,
2005 pub is_indirect: bool,
2009 // NOTE(eddyb) This is used within MIR as well, so unlike the rest of the HIR,
2010 // it needs to be `Clone` and use plain `Vec<T>` instead of arena-allocated slice.
2011 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic, PartialEq)]
2012 pub struct LlvmInlineAsmInner {
2014 pub asm_str_style: StrStyle,
2015 pub outputs: Vec<LlvmInlineAsmOutput>,
2016 pub inputs: Vec<Symbol>,
2017 pub clobbers: Vec<Symbol>,
2019 pub alignstack: bool,
2020 pub dialect: LlvmAsmDialect,
2023 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2024 pub struct LlvmInlineAsm<'hir> {
2025 pub inner: LlvmInlineAsmInner,
2026 pub outputs_exprs: &'hir [Expr<'hir>],
2027 pub inputs_exprs: &'hir [Expr<'hir>],
2030 /// Represents a parameter in a function header.
2031 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2032 pub struct Param<'hir> {
2033 pub attrs: &'hir [Attribute],
2035 pub pat: &'hir Pat<'hir>,
2039 /// Represents the header (not the body) of a function declaration.
2040 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2041 pub struct FnDecl<'hir> {
2042 /// The types of the function's parameters.
2044 /// Additional argument data is stored in the function's [body](Body::parameters).
2045 pub inputs: &'hir [Ty<'hir>],
2046 pub output: FnRetTy<'hir>,
2047 pub c_variadic: bool,
2048 /// Does the function have an implicit self?
2049 pub implicit_self: ImplicitSelfKind,
2052 /// Represents what type of implicit self a function has, if any.
2053 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2054 pub enum ImplicitSelfKind {
2055 /// Represents a `fn x(self);`.
2057 /// Represents a `fn x(mut self);`.
2059 /// Represents a `fn x(&self);`.
2061 /// Represents a `fn x(&mut self);`.
2063 /// Represents when a function does not have a self argument or
2064 /// when a function has a `self: X` argument.
2068 impl ImplicitSelfKind {
2069 /// Does this represent an implicit self?
2070 pub fn has_implicit_self(&self) -> bool {
2072 ImplicitSelfKind::None => false,
2078 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
2079 #[derive(HashStable_Generic)]
2085 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2086 pub enum Defaultness {
2087 Default { has_value: bool },
2092 pub fn has_value(&self) -> bool {
2094 Defaultness::Default { has_value } => has_value,
2095 Defaultness::Final => true,
2099 pub fn is_final(&self) -> bool {
2100 *self == Defaultness::Final
2103 pub fn is_default(&self) -> bool {
2105 Defaultness::Default { .. } => true,
2111 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2112 pub enum FnRetTy<'hir> {
2113 /// Return type is not specified.
2115 /// Functions default to `()` and
2116 /// closures default to inference. Span points to where return
2117 /// type would be inserted.
2118 DefaultReturn(Span),
2119 /// Everything else.
2120 Return(&'hir Ty<'hir>),
2124 pub fn span(&self) -> Span {
2126 Self::DefaultReturn(span) => span,
2127 Self::Return(ref ty) => ty.span,
2132 #[derive(RustcEncodable, RustcDecodable, Debug)]
2133 pub struct Mod<'hir> {
2134 /// A span from the first token past `{` to the last token until `}`.
2135 /// For `mod foo;`, the inner span ranges from the first token
2136 /// to the last token in the external file.
2138 pub item_ids: &'hir [ItemId],
2141 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2142 pub struct ForeignMod<'hir> {
2144 pub items: &'hir [ForeignItem<'hir>],
2147 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2148 pub struct GlobalAsm {
2152 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2153 pub struct EnumDef<'hir> {
2154 pub variants: &'hir [Variant<'hir>],
2157 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2158 pub struct Variant<'hir> {
2159 /// Name of the variant.
2160 #[stable_hasher(project(name))]
2162 /// Attributes of the variant.
2163 pub attrs: &'hir [Attribute],
2164 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2166 /// Fields and constructor id of the variant.
2167 pub data: VariantData<'hir>,
2168 /// Explicit discriminant (e.g., `Foo = 1`).
2169 pub disr_expr: Option<AnonConst>,
2174 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2176 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2177 /// Also produced for each element of a list `use`, e.g.
2178 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2181 /// Glob import, e.g., `use foo::*`.
2184 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2185 /// an additional `use foo::{}` for performing checks such as
2186 /// unstable feature gating. May be removed in the future.
2190 /// References to traits in impls.
2192 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2193 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2194 /// trait being referred to but just a unique `HirId` that serves as a key
2195 /// within the resolution map.
2196 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2197 pub struct TraitRef<'hir> {
2198 pub path: &'hir Path<'hir>,
2199 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2200 #[stable_hasher(ignore)]
2201 pub hir_ref_id: HirId,
2205 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2206 pub fn trait_def_id(&self) -> Option<DefId> {
2207 match self.path.res {
2208 Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
2210 _ => unreachable!(),
2215 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2216 pub struct PolyTraitRef<'hir> {
2217 /// The `'a` in `for<'a> Foo<&'a T>`.
2218 pub bound_generic_params: &'hir [GenericParam<'hir>],
2220 /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
2221 pub trait_ref: TraitRef<'hir>,
2226 pub type Visibility<'hir> = Spanned<VisibilityKind<'hir>>;
2228 #[derive(RustcEncodable, RustcDecodable, Debug)]
2229 pub enum VisibilityKind<'hir> {
2232 Restricted { path: &'hir Path<'hir>, hir_id: HirId },
2236 impl VisibilityKind<'_> {
2237 pub fn is_pub(&self) -> bool {
2239 VisibilityKind::Public => true,
2244 pub fn is_pub_restricted(&self) -> bool {
2246 VisibilityKind::Public | VisibilityKind::Inherited => false,
2247 VisibilityKind::Crate(..) | VisibilityKind::Restricted { .. } => true,
2251 pub fn descr(&self) -> &'static str {
2253 VisibilityKind::Public => "public",
2254 VisibilityKind::Inherited => "private",
2255 VisibilityKind::Crate(..) => "crate-visible",
2256 VisibilityKind::Restricted { .. } => "restricted",
2261 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2262 pub struct StructField<'hir> {
2264 #[stable_hasher(project(name))]
2266 pub vis: Visibility<'hir>,
2268 pub ty: &'hir Ty<'hir>,
2269 pub attrs: &'hir [Attribute],
2272 impl StructField<'_> {
2273 // Still necessary in couple of places
2274 pub fn is_positional(&self) -> bool {
2275 let first = self.ident.as_str().as_bytes()[0];
2276 first >= b'0' && first <= b'9'
2280 /// Fields and constructor IDs of enum variants and structs.
2281 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2282 pub enum VariantData<'hir> {
2283 /// A struct variant.
2285 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2286 Struct(&'hir [StructField<'hir>], /* recovered */ bool),
2287 /// A tuple variant.
2289 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2290 Tuple(&'hir [StructField<'hir>], HirId),
2293 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2297 impl VariantData<'hir> {
2298 /// Return the fields of this variant.
2299 pub fn fields(&self) -> &'hir [StructField<'hir>] {
2301 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2306 /// Return the `HirId` of this variant's constructor, if it has one.
2307 pub fn ctor_hir_id(&self) -> Option<HirId> {
2309 VariantData::Struct(_, _) => None,
2310 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2315 // The bodies for items are stored "out of line", in a separate
2316 // hashmap in the `Crate`. Here we just record the node-id of the item
2317 // so it can fetched later.
2318 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2325 /// The name might be a dummy name in case of anonymous items
2326 #[derive(RustcEncodable, RustcDecodable, Debug)]
2327 pub struct Item<'hir> {
2330 pub attrs: &'hir [Attribute],
2331 pub kind: ItemKind<'hir>,
2332 pub vis: Visibility<'hir>,
2336 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2337 #[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
2344 pub fn prefix_str(&self) -> &'static str {
2346 Self::Unsafe => "unsafe ",
2352 impl fmt::Display for Unsafety {
2353 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2354 f.write_str(match *self {
2355 Self::Unsafe => "unsafe",
2356 Self::Normal => "normal",
2361 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2362 #[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
2363 pub enum Constness {
2368 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2369 pub struct FnHeader {
2370 pub unsafety: Unsafety,
2371 pub constness: Constness,
2372 pub asyncness: IsAsync,
2377 pub fn is_const(&self) -> bool {
2378 match &self.constness {
2379 Constness::Const => true,
2385 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2386 pub enum ItemKind<'hir> {
2387 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2389 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2390 ExternCrate(Option<Name>),
2392 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2396 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2397 Use(&'hir Path<'hir>, UseKind),
2399 /// A `static` item.
2400 Static(&'hir Ty<'hir>, Mutability, BodyId),
2402 Const(&'hir Ty<'hir>, BodyId),
2403 /// A function declaration.
2404 Fn(FnSig<'hir>, Generics<'hir>, BodyId),
2407 /// An external module, e.g. `extern { .. }`.
2408 ForeignMod(ForeignMod<'hir>),
2409 /// Module-level inline assembly (from `global_asm!`).
2410 GlobalAsm(&'hir GlobalAsm),
2411 /// A type alias, e.g., `type Foo = Bar<u8>`.
2412 TyAlias(&'hir Ty<'hir>, Generics<'hir>),
2413 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2414 OpaqueTy(OpaqueTy<'hir>),
2415 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2416 Enum(EnumDef<'hir>, Generics<'hir>),
2417 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2418 Struct(VariantData<'hir>, Generics<'hir>),
2419 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2420 Union(VariantData<'hir>, Generics<'hir>),
2421 /// A trait definition.
2422 Trait(IsAuto, Unsafety, Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
2424 TraitAlias(Generics<'hir>, GenericBounds<'hir>),
2426 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2429 polarity: ImplPolarity,
2430 defaultness: Defaultness,
2431 // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata
2432 // decoding as `Span`s cannot be decoded when a `Session` is not available.
2433 defaultness_span: Option<Span>,
2434 constness: Constness,
2435 generics: Generics<'hir>,
2437 /// The trait being implemented, if any.
2438 of_trait: Option<TraitRef<'hir>>,
2440 self_ty: &'hir Ty<'hir>,
2441 items: &'hir [ImplItemRef<'hir>],
2446 pub fn descr(&self) -> &str {
2448 ItemKind::ExternCrate(..) => "extern crate",
2449 ItemKind::Use(..) => "`use` import",
2450 ItemKind::Static(..) => "static item",
2451 ItemKind::Const(..) => "constant item",
2452 ItemKind::Fn(..) => "function",
2453 ItemKind::Mod(..) => "module",
2454 ItemKind::ForeignMod(..) => "extern block",
2455 ItemKind::GlobalAsm(..) => "global asm item",
2456 ItemKind::TyAlias(..) => "type alias",
2457 ItemKind::OpaqueTy(..) => "opaque type",
2458 ItemKind::Enum(..) => "enum",
2459 ItemKind::Struct(..) => "struct",
2460 ItemKind::Union(..) => "union",
2461 ItemKind::Trait(..) => "trait",
2462 ItemKind::TraitAlias(..) => "trait alias",
2463 ItemKind::Impl { .. } => "implementation",
2467 pub fn generics(&self) -> Option<&Generics<'_>> {
2469 ItemKind::Fn(_, ref generics, _)
2470 | ItemKind::TyAlias(_, ref generics)
2471 | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
2472 | ItemKind::Enum(_, ref generics)
2473 | ItemKind::Struct(_, ref generics)
2474 | ItemKind::Union(_, ref generics)
2475 | ItemKind::Trait(_, _, ref generics, _, _)
2476 | ItemKind::Impl { ref generics, .. } => generics,
2482 /// A reference from an trait to one of its associated items. This
2483 /// contains the item's id, naturally, but also the item's name and
2484 /// some other high-level details (like whether it is an associated
2485 /// type or method, and whether it is public). This allows other
2486 /// passes to find the impl they want without loading the ID (which
2487 /// means fewer edges in the incremental compilation graph).
2488 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2489 pub struct TraitItemRef {
2490 pub id: TraitItemId,
2491 #[stable_hasher(project(name))]
2493 pub kind: AssocItemKind,
2495 pub defaultness: Defaultness,
2498 /// A reference from an impl to one of its associated items. This
2499 /// contains the item's ID, naturally, but also the item's name and
2500 /// some other high-level details (like whether it is an associated
2501 /// type or method, and whether it is public). This allows other
2502 /// passes to find the impl they want without loading the ID (which
2503 /// means fewer edges in the incremental compilation graph).
2504 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2505 pub struct ImplItemRef<'hir> {
2507 #[stable_hasher(project(name))]
2509 pub kind: AssocItemKind,
2511 pub vis: Visibility<'hir>,
2512 pub defaultness: Defaultness,
2515 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2516 pub enum AssocItemKind {
2518 Method { has_self: bool },
2523 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2524 pub struct ForeignItem<'hir> {
2525 #[stable_hasher(project(name))]
2527 pub attrs: &'hir [Attribute],
2528 pub kind: ForeignItemKind<'hir>,
2531 pub vis: Visibility<'hir>,
2534 /// An item within an `extern` block.
2535 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2536 pub enum ForeignItemKind<'hir> {
2537 /// A foreign function.
2538 Fn(&'hir FnDecl<'hir>, &'hir [Ident], Generics<'hir>),
2539 /// A foreign static item (`static ext: u8`).
2540 Static(&'hir Ty<'hir>, Mutability),
2545 impl ForeignItemKind<'hir> {
2546 pub fn descriptive_variant(&self) -> &str {
2548 ForeignItemKind::Fn(..) => "foreign function",
2549 ForeignItemKind::Static(..) => "foreign static item",
2550 ForeignItemKind::Type => "foreign type",
2555 /// A variable captured by a closure.
2556 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable, HashStable_Generic)]
2558 // First span where it is accessed (there can be multiple).
2562 pub type CaptureModeMap = NodeMap<CaptureBy>;
2564 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2565 // has length > 0 if the trait is found through an chain of imports, starting with the
2566 // import/use statement in the scope where the trait is used.
2567 #[derive(Clone, Debug)]
2568 pub struct TraitCandidate<ID = HirId> {
2570 pub import_ids: SmallVec<[ID; 1]>,
2573 impl<ID> TraitCandidate<ID> {
2574 pub fn map_import_ids<F, T>(self, f: F) -> TraitCandidate<T>
2578 let TraitCandidate { def_id, import_ids } = self;
2579 let import_ids = import_ids.into_iter().map(f).collect();
2580 TraitCandidate { def_id, import_ids }
2584 // Trait method resolution
2585 pub type TraitMap<ID = HirId> = NodeMap<Vec<TraitCandidate<ID>>>;
2587 // Map from the NodeId of a glob import to a list of items which are actually
2589 pub type GlobMap = NodeMap<FxHashSet<Name>>;
2591 #[derive(Copy, Clone, Debug, HashStable_Generic)]
2592 pub enum Node<'hir> {
2593 Param(&'hir Param<'hir>),
2594 Item(&'hir Item<'hir>),
2595 ForeignItem(&'hir ForeignItem<'hir>),
2596 TraitItem(&'hir TraitItem<'hir>),
2597 ImplItem(&'hir ImplItem<'hir>),
2598 Variant(&'hir Variant<'hir>),
2599 Field(&'hir StructField<'hir>),
2600 AnonConst(&'hir AnonConst),
2601 Expr(&'hir Expr<'hir>),
2602 Stmt(&'hir Stmt<'hir>),
2603 PathSegment(&'hir PathSegment<'hir>),
2605 TraitRef(&'hir TraitRef<'hir>),
2606 Binding(&'hir Pat<'hir>),
2607 Pat(&'hir Pat<'hir>),
2608 Arm(&'hir Arm<'hir>),
2609 Block(&'hir Block<'hir>),
2610 Local(&'hir Local<'hir>),
2611 MacroDef(&'hir MacroDef<'hir>),
2613 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
2614 /// with synthesized constructors.
2615 Ctor(&'hir VariantData<'hir>),
2617 Lifetime(&'hir Lifetime),
2618 GenericParam(&'hir GenericParam<'hir>),
2619 Visibility(&'hir Visibility<'hir>),
2621 Crate(&'hir CrateItem<'hir>),
2625 pub fn ident(&self) -> Option<Ident> {
2627 Node::TraitItem(TraitItem { ident, .. })
2628 | Node::ImplItem(ImplItem { ident, .. })
2629 | Node::ForeignItem(ForeignItem { ident, .. })
2630 | Node::Item(Item { ident, .. }) => Some(*ident),
2635 pub fn fn_decl(&self) -> Option<&FnDecl<'_>> {
2637 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
2638 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
2639 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
2640 Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
2647 pub fn generics(&self) -> Option<&Generics<'_>> {
2649 Node::TraitItem(TraitItem { generics, .. })
2650 | Node::ImplItem(ImplItem { generics, .. })
2651 | Node::Item(Item { kind: ItemKind::Fn(_, generics, _), .. }) => Some(generics),