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, LlvmAsmDialect};
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, Ident, 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,
1294 /// The kind of an item that requires const-checking.
1295 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1296 pub enum ConstContext {
1300 /// A `static` or `static mut`.
1303 /// A `const`, associated `const`, or other const context.
1305 /// Other contexts include:
1306 /// - Array length expressions
1307 /// - Enum discriminants
1308 /// - Const generics
1310 /// For the most part, other contexts are treated just like a regular `const`, so they are
1311 /// lumped into the same category.
1316 /// A description of this const context that can appear between backticks in an error message.
1318 /// E.g. `const` or `static mut`.
1319 pub fn keyword_name(self) -> &'static str {
1321 Self::Const => "const",
1322 Self::Static(Mutability::Not) => "static",
1323 Self::Static(Mutability::Mut) => "static mut",
1324 Self::ConstFn => "const fn",
1329 /// A colloquial, trivially pluralizable description of this const context for use in error
1331 impl fmt::Display for ConstContext {
1332 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1334 Self::Const => write!(f, "constant"),
1335 Self::Static(_) => write!(f, "static"),
1336 Self::ConstFn => write!(f, "constant function"),
1342 pub type Lit = Spanned<LitKind>;
1344 /// A constant (expression) that's not an item or associated item,
1345 /// but needs its own `DefId` for type-checking, const-eval, etc.
1346 /// These are usually found nested inside types (e.g., array lengths)
1347 /// or expressions (e.g., repeat counts), and also used to define
1348 /// explicit discriminant values for enum variants.
1349 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1350 pub struct AnonConst {
1356 #[derive(Debug, RustcEncodable, RustcDecodable)]
1357 pub struct Expr<'hir> {
1359 pub kind: ExprKind<'hir>,
1364 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1365 #[cfg(target_arch = "x86_64")]
1366 rustc_data_structures::static_assert_size!(Expr<'static>, 64);
1369 pub fn precedence(&self) -> ExprPrecedence {
1371 ExprKind::Box(_) => ExprPrecedence::Box,
1372 ExprKind::Array(_) => ExprPrecedence::Array,
1373 ExprKind::Call(..) => ExprPrecedence::Call,
1374 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1375 ExprKind::Tup(_) => ExprPrecedence::Tup,
1376 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1377 ExprKind::Unary(..) => ExprPrecedence::Unary,
1378 ExprKind::Lit(_) => ExprPrecedence::Lit,
1379 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1380 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1381 ExprKind::Loop(..) => ExprPrecedence::Loop,
1382 ExprKind::Match(..) => ExprPrecedence::Match,
1383 ExprKind::Closure(..) => ExprPrecedence::Closure,
1384 ExprKind::Block(..) => ExprPrecedence::Block,
1385 ExprKind::Assign(..) => ExprPrecedence::Assign,
1386 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1387 ExprKind::Field(..) => ExprPrecedence::Field,
1388 ExprKind::Index(..) => ExprPrecedence::Index,
1389 ExprKind::Path(..) => ExprPrecedence::Path,
1390 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1391 ExprKind::Break(..) => ExprPrecedence::Break,
1392 ExprKind::Continue(..) => ExprPrecedence::Continue,
1393 ExprKind::Ret(..) => ExprPrecedence::Ret,
1394 ExprKind::LlvmInlineAsm(..) => ExprPrecedence::InlineAsm,
1395 ExprKind::Struct(..) => ExprPrecedence::Struct,
1396 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1397 ExprKind::Yield(..) => ExprPrecedence::Yield,
1398 ExprKind::Err => ExprPrecedence::Err,
1402 // Whether this looks like a place expr, without checking for deref
1404 // This will return `true` in some potentially surprising cases such as
1405 // `CONSTANT.field`.
1406 pub fn is_syntactic_place_expr(&self) -> bool {
1407 self.is_place_expr(|_| true)
1410 // Whether this is a place expression.
1411 // `allow_projections_from` should return `true` if indexing a field or
1412 // index expression based on the given expression should be considered a
1413 // place expression.
1414 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1416 ExprKind::Path(QPath::Resolved(_, ref path)) => match path.res {
1417 Res::Local(..) | Res::Def(DefKind::Static, _) | Res::Err => true,
1421 // Type ascription inherits its place expression kind from its
1423 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1424 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1426 ExprKind::Unary(UnOp::UnDeref, _) => true,
1428 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1429 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1432 // Partially qualified paths in expressions can only legally
1433 // refer to associated items which are always rvalues.
1434 ExprKind::Path(QPath::TypeRelative(..))
1435 | ExprKind::Call(..)
1436 | ExprKind::MethodCall(..)
1437 | ExprKind::Struct(..)
1439 | ExprKind::Match(..)
1440 | ExprKind::Closure(..)
1441 | ExprKind::Block(..)
1442 | ExprKind::Repeat(..)
1443 | ExprKind::Array(..)
1444 | ExprKind::Break(..)
1445 | ExprKind::Continue(..)
1447 | ExprKind::Loop(..)
1448 | ExprKind::Assign(..)
1449 | ExprKind::LlvmInlineAsm(..)
1450 | ExprKind::AssignOp(..)
1452 | ExprKind::Unary(..)
1454 | ExprKind::AddrOf(..)
1455 | ExprKind::Binary(..)
1456 | ExprKind::Yield(..)
1457 | ExprKind::Cast(..)
1458 | ExprKind::DropTemps(..)
1459 | ExprKind::Err => false,
1463 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1464 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1465 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1466 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1467 /// beyond remembering to call this function before doing analysis on it.
1468 pub fn peel_drop_temps(&self) -> &Self {
1469 let mut expr = self;
1470 while let ExprKind::DropTemps(inner) = &expr.kind {
1477 /// Checks if the specified expression is a built-in range literal.
1478 /// (See: `LoweringContext::lower_expr()`).
1480 /// FIXME(#60607): This function is a hack. If and when we have `QPath::Lang(...)`,
1481 /// we can use that instead as simpler, more reliable mechanism, as opposed to using `SourceMap`.
1482 pub fn is_range_literal(sm: &SourceMap, expr: &Expr<'_>) -> bool {
1483 // Returns whether the given path represents a (desugared) range,
1484 // either in std or core, i.e. has either a `::std::ops::Range` or
1485 // `::core::ops::Range` prefix.
1486 fn is_range_path(path: &Path<'_>) -> bool {
1487 let segs: Vec<_> = path.segments.iter().map(|seg| seg.ident.to_string()).collect();
1488 let segs: Vec<_> = segs.iter().map(|seg| &**seg).collect();
1490 // "{{root}}" is the equivalent of `::` prefix in `Path`.
1491 if let ["{{root}}", std_core, "ops", range] = segs.as_slice() {
1492 (*std_core == "std" || *std_core == "core") && range.starts_with("Range")
1498 // Check whether a span corresponding to a range expression is a
1499 // range literal, rather than an explicit struct or `new()` call.
1500 fn is_lit(sm: &SourceMap, span: &Span) -> bool {
1501 let end_point = sm.end_point(*span);
1503 if let Ok(end_string) = sm.span_to_snippet(end_point) {
1504 !(end_string.ends_with('}') || end_string.ends_with(')'))
1511 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1512 ExprKind::Struct(ref qpath, _, _) => {
1513 if let QPath::Resolved(None, ref path) = **qpath {
1514 return is_range_path(&path) && is_lit(sm, &expr.span);
1518 // `..` desugars to its struct path.
1519 ExprKind::Path(QPath::Resolved(None, ref path)) => {
1520 return is_range_path(&path) && is_lit(sm, &expr.span);
1523 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1524 ExprKind::Call(ref func, _) => {
1525 if let ExprKind::Path(QPath::TypeRelative(ref ty, ref segment)) = func.kind {
1526 if let TyKind::Path(QPath::Resolved(None, ref path)) = ty.kind {
1527 let new_call = segment.ident.name == sym::new;
1528 return is_range_path(&path) && is_lit(sm, &expr.span) && new_call;
1539 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1540 pub enum ExprKind<'hir> {
1541 /// A `box x` expression.
1542 Box(&'hir Expr<'hir>),
1543 /// An array (e.g., `[a, b, c, d]`).
1544 Array(&'hir [Expr<'hir>]),
1545 /// A function call.
1547 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1548 /// and the second field is the list of arguments.
1549 /// This also represents calling the constructor of
1550 /// tuple-like ADTs such as tuple structs and enum variants.
1551 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1552 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1554 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1555 /// (within the angle brackets).
1556 /// The first element of the vector of `Expr`s is the expression that evaluates
1557 /// to the object on which the method is being called on (the receiver),
1558 /// and the remaining elements are the rest of the arguments.
1559 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1560 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1562 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1563 /// the `hir_id` of the `MethodCall` node itself.
1565 /// [`type_dependent_def_id`]: ../ty/struct.TypeckTables.html#method.type_dependent_def_id
1566 MethodCall(&'hir PathSegment<'hir>, Span, &'hir [Expr<'hir>]),
1567 /// A tuple (e.g., `(a, b, c, d)`).
1568 Tup(&'hir [Expr<'hir>]),
1569 /// A binary operation (e.g., `a + b`, `a * b`).
1570 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1571 /// A unary operation (e.g., `!x`, `*x`).
1572 Unary(UnOp, &'hir Expr<'hir>),
1573 /// A literal (e.g., `1`, `"foo"`).
1575 /// A cast (e.g., `foo as f64`).
1576 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1577 /// A type reference (e.g., `Foo`).
1578 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1579 /// Wraps the expression in a terminating scope.
1580 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1582 /// This construct only exists to tweak the drop order in HIR lowering.
1583 /// An example of that is the desugaring of `for` loops.
1584 DropTemps(&'hir Expr<'hir>),
1585 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1587 /// I.e., `'label: loop { <block> }`.
1588 Loop(&'hir Block<'hir>, Option<Label>, LoopSource),
1589 /// A `match` block, with a source that indicates whether or not it is
1590 /// the result of a desugaring, and if so, which kind.
1591 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1592 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1594 /// The `Span` is the argument block `|...|`.
1596 /// This may also be a generator literal or an `async block` as indicated by the
1597 /// `Option<Movability>`.
1598 Closure(CaptureBy, &'hir FnDecl<'hir>, BodyId, Span, Option<Movability>),
1599 /// A block (e.g., `'label: { ... }`).
1600 Block(&'hir Block<'hir>, Option<Label>),
1602 /// An assignment (e.g., `a = foo()`).
1603 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1604 /// An assignment with an operator.
1607 AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1608 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1609 Field(&'hir Expr<'hir>, Ident),
1610 /// An indexing operation (`foo[2]`).
1611 Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1613 /// Path to a definition, possibly containing lifetime or type parameters.
1616 /// A referencing operation (i.e., `&a` or `&mut a`).
1617 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1618 /// A `break`, with an optional label to break.
1619 Break(Destination, Option<&'hir Expr<'hir>>),
1620 /// A `continue`, with an optional label.
1621 Continue(Destination),
1622 /// A `return`, with an optional value to be returned.
1623 Ret(Option<&'hir Expr<'hir>>),
1625 /// Inline assembly (from `llvm_asm!`), with its outputs and inputs.
1626 LlvmInlineAsm(&'hir LlvmInlineAsm<'hir>),
1628 /// A struct or struct-like variant literal expression.
1630 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1631 /// where `base` is the `Option<Expr>`.
1632 Struct(&'hir QPath<'hir>, &'hir [Field<'hir>], Option<&'hir Expr<'hir>>),
1634 /// An array literal constructed from one repeated element.
1636 /// E.g., `[1; 5]`. The first expression is the element
1637 /// to be repeated; the second is the number of times to repeat it.
1638 Repeat(&'hir Expr<'hir>, AnonConst),
1640 /// A suspension point for generators (i.e., `yield <expr>`).
1641 Yield(&'hir Expr<'hir>, YieldSource),
1643 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1647 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1649 /// To resolve the path to a `DefId`, call [`qpath_res`].
1651 /// [`qpath_res`]: ../rustc_middle/ty/struct.TypeckTables.html#method.qpath_res
1652 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1653 pub enum QPath<'hir> {
1654 /// Path to a definition, optionally "fully-qualified" with a `Self`
1655 /// type, if the path points to an associated item in a trait.
1657 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1658 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1659 /// even though they both have the same two-segment `Clone::clone` `Path`.
1660 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
1662 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1663 /// Will be resolved by type-checking to an associated item.
1665 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1666 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1667 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1668 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
1671 /// Hints at the original code for a let statement.
1672 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1673 pub enum LocalSource {
1674 /// A `match _ { .. }`.
1676 /// A desugared `for _ in _ { .. }` loop.
1678 /// When lowering async functions, we create locals within the `async move` so that
1679 /// all parameters are dropped after the future is polled.
1681 /// ```ignore (pseudo-Rust)
1682 /// async fn foo(<pattern> @ x: Type) {
1684 /// let <pattern> = x;
1689 /// A desugared `<expr>.await`.
1693 /// Hints at the original code for a `match _ { .. }`.
1694 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1695 #[derive(HashStable_Generic)]
1696 pub enum MatchSource {
1697 /// A `match _ { .. }`.
1699 /// An `if _ { .. }` (optionally with `else { .. }`).
1700 IfDesugar { contains_else_clause: bool },
1701 /// An `if let _ = _ { .. }` (optionally with `else { .. }`).
1702 IfLetDesugar { contains_else_clause: bool },
1703 /// A `while _ { .. }` (which was desugared to a `loop { match _ { .. } }`).
1705 /// A `while let _ = _ { .. }` (which was desugared to a
1706 /// `loop { match _ { .. } }`).
1708 /// A desugared `for _ in _ { .. }` loop.
1710 /// A desugared `?` operator.
1712 /// A desugared `<expr>.await`.
1717 pub fn name(self) -> &'static str {
1721 IfDesugar { .. } | IfLetDesugar { .. } => "if",
1722 WhileDesugar | WhileLetDesugar => "while",
1723 ForLoopDesugar => "for",
1725 AwaitDesugar => ".await",
1730 /// The loop type that yielded an `ExprKind::Loop`.
1731 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1732 pub enum LoopSource {
1733 /// A `loop { .. }` loop.
1735 /// A `while _ { .. }` loop.
1737 /// A `while let _ = _ { .. }` loop.
1739 /// A `for _ in _ { .. }` loop.
1744 pub fn name(self) -> &'static str {
1746 LoopSource::Loop => "loop",
1747 LoopSource::While | LoopSource::WhileLet => "while",
1748 LoopSource::ForLoop => "for",
1753 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1754 pub enum LoopIdError {
1756 UnlabeledCfInWhileCondition,
1760 impl fmt::Display for LoopIdError {
1761 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1762 f.write_str(match self {
1763 LoopIdError::OutsideLoopScope => "not inside loop scope",
1764 LoopIdError::UnlabeledCfInWhileCondition => {
1765 "unlabeled control flow (break or continue) in while condition"
1767 LoopIdError::UnresolvedLabel => "label not found",
1772 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1773 pub struct Destination {
1774 // This is `Some(_)` iff there is an explicit user-specified `label
1775 pub label: Option<Label>,
1777 // These errors are caught and then reported during the diagnostics pass in
1778 // librustc_passes/loops.rs
1779 pub target_id: Result<HirId, LoopIdError>,
1782 /// The yield kind that caused an `ExprKind::Yield`.
1783 #[derive(Copy, Clone, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable, HashStable_Generic)]
1784 pub enum YieldSource {
1785 /// An `<expr>.await`.
1786 Await { expr: Option<HirId> },
1787 /// A plain `yield`.
1792 pub fn is_await(&self) -> bool {
1794 YieldSource::Await { .. } => true,
1795 YieldSource::Yield => false,
1800 impl fmt::Display for YieldSource {
1801 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1802 f.write_str(match self {
1803 YieldSource::Await { .. } => "`await`",
1804 YieldSource::Yield => "`yield`",
1809 impl From<GeneratorKind> for YieldSource {
1810 fn from(kind: GeneratorKind) -> Self {
1812 // Guess based on the kind of the current generator.
1813 GeneratorKind::Gen => Self::Yield,
1814 GeneratorKind::Async(_) => Self::Await { expr: None },
1819 // N.B., if you change this, you'll probably want to change the corresponding
1820 // type structure in middle/ty.rs as well.
1821 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1822 pub struct MutTy<'hir> {
1823 pub ty: &'hir Ty<'hir>,
1824 pub mutbl: Mutability,
1827 /// Represents a function's signature in a trait declaration,
1828 /// trait implementation, or a free function.
1829 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1830 pub struct FnSig<'hir> {
1831 pub header: FnHeader,
1832 pub decl: &'hir FnDecl<'hir>,
1835 // The bodies for items are stored "out of line", in a separate
1836 // hashmap in the `Crate`. Here we just record the node-id of the item
1837 // so it can fetched later.
1838 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1839 pub struct TraitItemId {
1843 /// Represents an item declaration within a trait declaration,
1844 /// possibly including a default implementation. A trait item is
1845 /// either required (meaning it doesn't have an implementation, just a
1846 /// signature) or provided (meaning it has a default implementation).
1847 #[derive(RustcEncodable, RustcDecodable, Debug)]
1848 pub struct TraitItem<'hir> {
1851 pub attrs: &'hir [Attribute],
1852 pub generics: Generics<'hir>,
1853 pub kind: TraitItemKind<'hir>,
1857 /// Represents a trait method's body (or just argument names).
1858 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1859 pub enum TraitFn<'hir> {
1860 /// No default body in the trait, just a signature.
1861 Required(&'hir [Ident]),
1863 /// Both signature and body are provided in the trait.
1867 /// Represents a trait method or associated constant or type
1868 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1869 pub enum TraitItemKind<'hir> {
1870 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
1871 Const(&'hir Ty<'hir>, Option<BodyId>),
1872 /// An associated function with an optional body.
1873 Fn(FnSig<'hir>, TraitFn<'hir>),
1874 /// An associated type with (possibly empty) bounds and optional concrete
1876 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
1879 // The bodies for items are stored "out of line", in a separate
1880 // hashmap in the `Crate`. Here we just record the node-id of the item
1881 // so it can fetched later.
1882 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1883 pub struct ImplItemId {
1887 /// Represents anything within an `impl` block.
1888 #[derive(RustcEncodable, RustcDecodable, Debug)]
1889 pub struct ImplItem<'hir> {
1892 pub vis: Visibility<'hir>,
1893 pub defaultness: Defaultness,
1894 pub attrs: &'hir [Attribute],
1895 pub generics: Generics<'hir>,
1896 pub kind: ImplItemKind<'hir>,
1900 /// Represents various kinds of content within an `impl`.
1901 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1902 pub enum ImplItemKind<'hir> {
1903 /// An associated constant of the given type, set to the constant result
1904 /// of the expression.
1905 Const(&'hir Ty<'hir>, BodyId),
1906 /// An associated function implementation with the given signature and body.
1907 Fn(FnSig<'hir>, BodyId),
1908 /// An associated type.
1909 TyAlias(&'hir Ty<'hir>),
1910 /// An associated `type = impl Trait`.
1911 OpaqueTy(GenericBounds<'hir>),
1914 impl ImplItemKind<'_> {
1915 pub fn namespace(&self) -> Namespace {
1917 ImplItemKind::OpaqueTy(..) | ImplItemKind::TyAlias(..) => Namespace::TypeNS,
1918 ImplItemKind::Const(..) | ImplItemKind::Fn(..) => Namespace::ValueNS,
1923 // The name of the associated type for `Fn` return types.
1924 pub const FN_OUTPUT_NAME: Symbol = sym::Output;
1926 /// Bind a type to an associated type (i.e., `A = Foo`).
1928 /// Bindings like `A: Debug` are represented as a special type `A =
1929 /// $::Debug` that is understood by the astconv code.
1931 /// FIXME(alexreg): why have a separate type for the binding case,
1932 /// wouldn't it be better to make the `ty` field an enum like the
1936 /// enum TypeBindingKind {
1941 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1942 pub struct TypeBinding<'hir> {
1944 #[stable_hasher(project(name))]
1946 pub kind: TypeBindingKind<'hir>,
1950 // Represents the two kinds of type bindings.
1951 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1952 pub enum TypeBindingKind<'hir> {
1953 /// E.g., `Foo<Bar: Send>`.
1954 Constraint { bounds: &'hir [GenericBound<'hir>] },
1955 /// E.g., `Foo<Bar = ()>`.
1956 Equality { ty: &'hir Ty<'hir> },
1959 impl TypeBinding<'_> {
1960 pub fn ty(&self) -> &Ty<'_> {
1962 TypeBindingKind::Equality { ref ty } => ty,
1963 _ => panic!("expected equality type binding for parenthesized generic args"),
1968 #[derive(Debug, RustcEncodable, RustcDecodable)]
1969 pub struct Ty<'hir> {
1971 pub kind: TyKind<'hir>,
1975 /// Not represented directly in the AST; referred to by name through a `ty_path`.
1976 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1977 #[derive(HashStable_Generic)]
1987 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1988 pub struct BareFnTy<'hir> {
1989 pub unsafety: Unsafety,
1991 pub generic_params: &'hir [GenericParam<'hir>],
1992 pub decl: &'hir FnDecl<'hir>,
1993 pub param_names: &'hir [Ident],
1996 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1997 pub struct OpaqueTy<'hir> {
1998 pub generics: Generics<'hir>,
1999 pub bounds: GenericBounds<'hir>,
2000 pub impl_trait_fn: Option<DefId>,
2001 pub origin: OpaqueTyOrigin,
2004 /// From whence the opaque type came.
2005 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2006 pub enum OpaqueTyOrigin {
2007 /// `type Foo = impl Trait;`
2013 /// Impl trait in bindings, consts, statics, bounds.
2017 /// The various kinds of types recognized by the compiler.
2018 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2019 pub enum TyKind<'hir> {
2020 /// A variable length slice (i.e., `[T]`).
2021 Slice(&'hir Ty<'hir>),
2022 /// A fixed length array (i.e., `[T; n]`).
2023 Array(&'hir Ty<'hir>, AnonConst),
2024 /// A raw pointer (i.e., `*const T` or `*mut T`).
2026 /// A reference (i.e., `&'a T` or `&'a mut T`).
2027 Rptr(Lifetime, MutTy<'hir>),
2028 /// A bare function (e.g., `fn(usize) -> bool`).
2029 BareFn(&'hir BareFnTy<'hir>),
2030 /// The never type (`!`).
2032 /// A tuple (`(A, B, C, D, ...)`).
2033 Tup(&'hir [Ty<'hir>]),
2034 /// A path to a type definition (`module::module::...::Type`), or an
2035 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2037 /// Type parameters may be stored in each `PathSegment`.
2039 /// A type definition itself. This is currently only used for the `type Foo = impl Trait`
2040 /// item that `impl Trait` in return position desugars to.
2042 /// The generic argument list contains the lifetimes (and in the future possibly parameters)
2043 /// that are actually bound on the `impl Trait`.
2044 Def(ItemId, &'hir [GenericArg<'hir>]),
2045 /// A trait object type `Bound1 + Bound2 + Bound3`
2046 /// where `Bound` is a trait or a lifetime.
2047 TraitObject(&'hir [PolyTraitRef<'hir>], Lifetime),
2050 /// `TyKind::Infer` means the type should be inferred instead of it having been
2051 /// specified. This can appear anywhere in a type.
2053 /// Placeholder for a type that has failed to be defined.
2057 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic, PartialEq)]
2058 pub struct LlvmInlineAsmOutput {
2059 pub constraint: Symbol,
2061 pub is_indirect: bool,
2065 // NOTE(eddyb) This is used within MIR as well, so unlike the rest of the HIR,
2066 // it needs to be `Clone` and use plain `Vec<T>` instead of arena-allocated slice.
2067 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic, PartialEq)]
2068 pub struct LlvmInlineAsmInner {
2070 pub asm_str_style: StrStyle,
2071 pub outputs: Vec<LlvmInlineAsmOutput>,
2072 pub inputs: Vec<Symbol>,
2073 pub clobbers: Vec<Symbol>,
2075 pub alignstack: bool,
2076 pub dialect: LlvmAsmDialect,
2079 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2080 pub struct LlvmInlineAsm<'hir> {
2081 pub inner: LlvmInlineAsmInner,
2082 pub outputs_exprs: &'hir [Expr<'hir>],
2083 pub inputs_exprs: &'hir [Expr<'hir>],
2086 /// Represents a parameter in a function header.
2087 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2088 pub struct Param<'hir> {
2089 pub attrs: &'hir [Attribute],
2091 pub pat: &'hir Pat<'hir>,
2095 /// Represents the header (not the body) of a function declaration.
2096 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2097 pub struct FnDecl<'hir> {
2098 /// The types of the function's parameters.
2100 /// Additional argument data is stored in the function's [body](Body::params).
2101 pub inputs: &'hir [Ty<'hir>],
2102 pub output: FnRetTy<'hir>,
2103 pub c_variadic: bool,
2104 /// Does the function have an implicit self?
2105 pub implicit_self: ImplicitSelfKind,
2108 /// Represents what type of implicit self a function has, if any.
2109 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2110 pub enum ImplicitSelfKind {
2111 /// Represents a `fn x(self);`.
2113 /// Represents a `fn x(mut self);`.
2115 /// Represents a `fn x(&self);`.
2117 /// Represents a `fn x(&mut self);`.
2119 /// Represents when a function does not have a self argument or
2120 /// when a function has a `self: X` argument.
2124 impl ImplicitSelfKind {
2125 /// Does this represent an implicit self?
2126 pub fn has_implicit_self(&self) -> bool {
2128 ImplicitSelfKind::None => false,
2134 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
2135 #[derive(HashStable_Generic)]
2141 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2142 pub enum Defaultness {
2143 Default { has_value: bool },
2148 pub fn has_value(&self) -> bool {
2150 Defaultness::Default { has_value } => has_value,
2151 Defaultness::Final => true,
2155 pub fn is_final(&self) -> bool {
2156 *self == Defaultness::Final
2159 pub fn is_default(&self) -> bool {
2161 Defaultness::Default { .. } => true,
2167 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2168 pub enum FnRetTy<'hir> {
2169 /// Return type is not specified.
2171 /// Functions default to `()` and
2172 /// closures default to inference. Span points to where return
2173 /// type would be inserted.
2174 DefaultReturn(Span),
2175 /// Everything else.
2176 Return(&'hir Ty<'hir>),
2180 pub fn span(&self) -> Span {
2182 Self::DefaultReturn(span) => span,
2183 Self::Return(ref ty) => ty.span,
2188 #[derive(RustcEncodable, RustcDecodable, Debug)]
2189 pub struct Mod<'hir> {
2190 /// A span from the first token past `{` to the last token until `}`.
2191 /// For `mod foo;`, the inner span ranges from the first token
2192 /// to the last token in the external file.
2194 pub item_ids: &'hir [ItemId],
2197 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2198 pub struct ForeignMod<'hir> {
2200 pub items: &'hir [ForeignItem<'hir>],
2203 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2204 pub struct GlobalAsm {
2208 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2209 pub struct EnumDef<'hir> {
2210 pub variants: &'hir [Variant<'hir>],
2213 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2214 pub struct Variant<'hir> {
2215 /// Name of the variant.
2216 #[stable_hasher(project(name))]
2218 /// Attributes of the variant.
2219 pub attrs: &'hir [Attribute],
2220 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2222 /// Fields and constructor id of the variant.
2223 pub data: VariantData<'hir>,
2224 /// Explicit discriminant (e.g., `Foo = 1`).
2225 pub disr_expr: Option<AnonConst>,
2230 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2232 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2233 /// Also produced for each element of a list `use`, e.g.
2234 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2237 /// Glob import, e.g., `use foo::*`.
2240 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2241 /// an additional `use foo::{}` for performing checks such as
2242 /// unstable feature gating. May be removed in the future.
2246 /// References to traits in impls.
2248 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2249 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2250 /// trait being referred to but just a unique `HirId` that serves as a key
2251 /// within the resolution map.
2252 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2253 pub struct TraitRef<'hir> {
2254 pub path: &'hir Path<'hir>,
2255 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2256 #[stable_hasher(ignore)]
2257 pub hir_ref_id: HirId,
2261 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2262 pub fn trait_def_id(&self) -> Option<DefId> {
2263 match self.path.res {
2264 Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
2266 _ => unreachable!(),
2271 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2272 pub struct PolyTraitRef<'hir> {
2273 /// The `'a` in `for<'a> Foo<&'a T>`.
2274 pub bound_generic_params: &'hir [GenericParam<'hir>],
2276 /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
2277 pub trait_ref: TraitRef<'hir>,
2282 pub type Visibility<'hir> = Spanned<VisibilityKind<'hir>>;
2284 #[derive(RustcEncodable, RustcDecodable, Debug)]
2285 pub enum VisibilityKind<'hir> {
2288 Restricted { path: &'hir Path<'hir>, hir_id: HirId },
2292 impl VisibilityKind<'_> {
2293 pub fn is_pub(&self) -> bool {
2295 VisibilityKind::Public => true,
2300 pub fn is_pub_restricted(&self) -> bool {
2302 VisibilityKind::Public | VisibilityKind::Inherited => false,
2303 VisibilityKind::Crate(..) | VisibilityKind::Restricted { .. } => true,
2307 pub fn descr(&self) -> &'static str {
2309 VisibilityKind::Public => "public",
2310 VisibilityKind::Inherited => "private",
2311 VisibilityKind::Crate(..) => "crate-visible",
2312 VisibilityKind::Restricted { .. } => "restricted",
2317 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2318 pub struct StructField<'hir> {
2320 #[stable_hasher(project(name))]
2322 pub vis: Visibility<'hir>,
2324 pub ty: &'hir Ty<'hir>,
2325 pub attrs: &'hir [Attribute],
2328 impl StructField<'_> {
2329 // Still necessary in couple of places
2330 pub fn is_positional(&self) -> bool {
2331 let first = self.ident.as_str().as_bytes()[0];
2332 first >= b'0' && first <= b'9'
2336 /// Fields and constructor IDs of enum variants and structs.
2337 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2338 pub enum VariantData<'hir> {
2339 /// A struct variant.
2341 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2342 Struct(&'hir [StructField<'hir>], /* recovered */ bool),
2343 /// A tuple variant.
2345 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2346 Tuple(&'hir [StructField<'hir>], HirId),
2349 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2353 impl VariantData<'hir> {
2354 /// Return the fields of this variant.
2355 pub fn fields(&self) -> &'hir [StructField<'hir>] {
2357 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2362 /// Return the `HirId` of this variant's constructor, if it has one.
2363 pub fn ctor_hir_id(&self) -> Option<HirId> {
2365 VariantData::Struct(_, _) => None,
2366 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2371 // The bodies for items are stored "out of line", in a separate
2372 // hashmap in the `Crate`. Here we just record the node-id of the item
2373 // so it can fetched later.
2374 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2381 /// The name might be a dummy name in case of anonymous items
2382 #[derive(RustcEncodable, RustcDecodable, Debug)]
2383 pub struct Item<'hir> {
2386 pub attrs: &'hir [Attribute],
2387 pub kind: ItemKind<'hir>,
2388 pub vis: Visibility<'hir>,
2392 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2393 #[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
2400 pub fn prefix_str(&self) -> &'static str {
2402 Self::Unsafe => "unsafe ",
2408 impl fmt::Display for Unsafety {
2409 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2410 f.write_str(match *self {
2411 Self::Unsafe => "unsafe",
2412 Self::Normal => "normal",
2417 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2418 #[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
2419 pub enum Constness {
2424 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2425 pub struct FnHeader {
2426 pub unsafety: Unsafety,
2427 pub constness: Constness,
2428 pub asyncness: IsAsync,
2433 pub fn is_const(&self) -> bool {
2434 match &self.constness {
2435 Constness::Const => true,
2441 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2442 pub enum ItemKind<'hir> {
2443 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2445 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2446 ExternCrate(Option<Symbol>),
2448 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2452 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2453 Use(&'hir Path<'hir>, UseKind),
2455 /// A `static` item.
2456 Static(&'hir Ty<'hir>, Mutability, BodyId),
2458 Const(&'hir Ty<'hir>, BodyId),
2459 /// A function declaration.
2460 Fn(FnSig<'hir>, Generics<'hir>, BodyId),
2463 /// An external module, e.g. `extern { .. }`.
2464 ForeignMod(ForeignMod<'hir>),
2465 /// Module-level inline assembly (from `global_asm!`).
2466 GlobalAsm(&'hir GlobalAsm),
2467 /// A type alias, e.g., `type Foo = Bar<u8>`.
2468 TyAlias(&'hir Ty<'hir>, Generics<'hir>),
2469 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2470 OpaqueTy(OpaqueTy<'hir>),
2471 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2472 Enum(EnumDef<'hir>, Generics<'hir>),
2473 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2474 Struct(VariantData<'hir>, Generics<'hir>),
2475 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2476 Union(VariantData<'hir>, Generics<'hir>),
2477 /// A trait definition.
2478 Trait(IsAuto, Unsafety, Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
2480 TraitAlias(Generics<'hir>, GenericBounds<'hir>),
2482 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2485 polarity: ImplPolarity,
2486 defaultness: Defaultness,
2487 // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata
2488 // decoding as `Span`s cannot be decoded when a `Session` is not available.
2489 defaultness_span: Option<Span>,
2490 constness: Constness,
2491 generics: Generics<'hir>,
2493 /// The trait being implemented, if any.
2494 of_trait: Option<TraitRef<'hir>>,
2496 self_ty: &'hir Ty<'hir>,
2497 items: &'hir [ImplItemRef<'hir>],
2502 pub fn generics(&self) -> Option<&Generics<'_>> {
2504 ItemKind::Fn(_, ref generics, _)
2505 | ItemKind::TyAlias(_, ref generics)
2506 | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
2507 | ItemKind::Enum(_, ref generics)
2508 | ItemKind::Struct(_, ref generics)
2509 | ItemKind::Union(_, ref generics)
2510 | ItemKind::Trait(_, _, ref generics, _, _)
2511 | ItemKind::Impl { ref generics, .. } => generics,
2517 /// A reference from an trait to one of its associated items. This
2518 /// contains the item's id, naturally, but also the item's name and
2519 /// some other high-level details (like whether it is an associated
2520 /// type or method, and whether it is public). This allows other
2521 /// passes to find the impl they want without loading the ID (which
2522 /// means fewer edges in the incremental compilation graph).
2523 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2524 pub struct TraitItemRef {
2525 pub id: TraitItemId,
2526 #[stable_hasher(project(name))]
2528 pub kind: AssocItemKind,
2530 pub defaultness: Defaultness,
2533 /// A reference from an impl to one of its associated items. This
2534 /// contains the item's ID, naturally, but also the item's name and
2535 /// some other high-level details (like whether it is an associated
2536 /// type or method, and whether it is public). This allows other
2537 /// passes to find the impl they want without loading the ID (which
2538 /// means fewer edges in the incremental compilation graph).
2539 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2540 pub struct ImplItemRef<'hir> {
2542 #[stable_hasher(project(name))]
2544 pub kind: AssocItemKind,
2546 pub vis: Visibility<'hir>,
2547 pub defaultness: Defaultness,
2550 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2551 pub enum AssocItemKind {
2553 Fn { has_self: bool },
2558 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2559 pub struct ForeignItem<'hir> {
2560 #[stable_hasher(project(name))]
2562 pub attrs: &'hir [Attribute],
2563 pub kind: ForeignItemKind<'hir>,
2566 pub vis: Visibility<'hir>,
2569 /// An item within an `extern` block.
2570 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2571 pub enum ForeignItemKind<'hir> {
2572 /// A foreign function.
2573 Fn(&'hir FnDecl<'hir>, &'hir [Ident], Generics<'hir>),
2574 /// A foreign static item (`static ext: u8`).
2575 Static(&'hir Ty<'hir>, Mutability),
2580 /// A variable captured by a closure.
2581 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable, HashStable_Generic)]
2583 // First span where it is accessed (there can be multiple).
2587 pub type CaptureModeMap = NodeMap<CaptureBy>;
2589 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2590 // has length > 0 if the trait is found through an chain of imports, starting with the
2591 // import/use statement in the scope where the trait is used.
2592 #[derive(Clone, Debug)]
2593 pub struct TraitCandidate<ID = HirId> {
2595 pub import_ids: SmallVec<[ID; 1]>,
2598 impl<ID> TraitCandidate<ID> {
2599 pub fn map_import_ids<F, T>(self, f: F) -> TraitCandidate<T>
2603 let TraitCandidate { def_id, import_ids } = self;
2604 let import_ids = import_ids.into_iter().map(f).collect();
2605 TraitCandidate { def_id, import_ids }
2609 // Trait method resolution
2610 pub type TraitMap<ID = HirId> = NodeMap<Vec<TraitCandidate<ID>>>;
2612 // Map from the NodeId of a glob import to a list of items which are actually
2614 pub type GlobMap = NodeMap<FxHashSet<Symbol>>;
2616 #[derive(Copy, Clone, Debug, HashStable_Generic)]
2617 pub enum Node<'hir> {
2618 Param(&'hir Param<'hir>),
2619 Item(&'hir Item<'hir>),
2620 ForeignItem(&'hir ForeignItem<'hir>),
2621 TraitItem(&'hir TraitItem<'hir>),
2622 ImplItem(&'hir ImplItem<'hir>),
2623 Variant(&'hir Variant<'hir>),
2624 Field(&'hir StructField<'hir>),
2625 AnonConst(&'hir AnonConst),
2626 Expr(&'hir Expr<'hir>),
2627 Stmt(&'hir Stmt<'hir>),
2628 PathSegment(&'hir PathSegment<'hir>),
2630 TraitRef(&'hir TraitRef<'hir>),
2631 Binding(&'hir Pat<'hir>),
2632 Pat(&'hir Pat<'hir>),
2633 Arm(&'hir Arm<'hir>),
2634 Block(&'hir Block<'hir>),
2635 Local(&'hir Local<'hir>),
2636 MacroDef(&'hir MacroDef<'hir>),
2638 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
2639 /// with synthesized constructors.
2640 Ctor(&'hir VariantData<'hir>),
2642 Lifetime(&'hir Lifetime),
2643 GenericParam(&'hir GenericParam<'hir>),
2644 Visibility(&'hir Visibility<'hir>),
2646 Crate(&'hir CrateItem<'hir>),
2650 pub fn ident(&self) -> Option<Ident> {
2652 Node::TraitItem(TraitItem { ident, .. })
2653 | Node::ImplItem(ImplItem { ident, .. })
2654 | Node::ForeignItem(ForeignItem { ident, .. })
2655 | Node::Item(Item { ident, .. }) => Some(*ident),
2660 pub fn fn_decl(&self) -> Option<&FnDecl<'_>> {
2662 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
2663 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
2664 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
2665 Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
2672 pub fn generics(&self) -> Option<&Generics<'_>> {
2674 Node::TraitItem(TraitItem { generics, .. })
2675 | Node::ImplItem(ImplItem { generics, .. })
2678 ItemKind::Trait(_, _, generics, ..)
2679 | ItemKind::Impl { generics, .. }
2680 | ItemKind::Fn(_, generics, _),
2682 }) => Some(generics),
2687 pub fn hir_id(&self) -> Option<HirId> {
2689 Node::Item(Item { hir_id, .. })
2690 | Node::ForeignItem(ForeignItem { hir_id, .. })
2691 | Node::TraitItem(TraitItem { hir_id, .. })
2692 | Node::ImplItem(ImplItem { hir_id, .. })
2693 | Node::Field(StructField { hir_id, .. })
2694 | Node::AnonConst(AnonConst { hir_id, .. })
2695 | Node::Expr(Expr { hir_id, .. })
2696 | Node::Stmt(Stmt { hir_id, .. })
2697 | Node::Ty(Ty { hir_id, .. })
2698 | Node::Binding(Pat { hir_id, .. })
2699 | Node::Pat(Pat { hir_id, .. })
2700 | Node::Arm(Arm { hir_id, .. })
2701 | Node::Block(Block { hir_id, .. })
2702 | Node::Local(Local { hir_id, .. })
2703 | Node::MacroDef(MacroDef { hir_id, .. })
2704 | Node::Lifetime(Lifetime { hir_id, .. })
2705 | Node::Param(Param { hir_id, .. })
2706 | Node::GenericParam(GenericParam { hir_id, .. }) => Some(*hir_id),
2707 Node::TraitRef(TraitRef { hir_ref_id, .. }) => Some(*hir_ref_id),
2708 Node::PathSegment(PathSegment { hir_id, .. }) => *hir_id,
2709 Node::Variant(Variant { id, .. }) => Some(*id),
2710 Node::Ctor(variant) => variant.ctor_hir_id(),
2711 Node::Crate(_) | Node::Visibility(_) => None,