1 use crate::def::{DefKind, Namespace, Res};
2 use crate::def_id::DefId;
3 crate use crate::hir_id::HirId;
4 use crate::itemlikevisit;
7 crate use BlockCheckMode::*;
9 crate use UnsafeSource::*;
11 use rustc_ast::ast::{self, AsmDialect, CrateSugar, Ident, Name};
12 use rustc_ast::ast::{AttrVec, Attribute, FloatTy, IntTy, Label, LitKind, StrStyle, UintTy};
13 pub use rustc_ast::ast::{BorrowKind, ImplPolarity, IsAuto};
14 pub use rustc_ast::ast::{CaptureBy, Movability, Mutability};
15 use rustc_ast::node_id::NodeMap;
16 use rustc_ast::util::parser::ExprPrecedence;
17 use rustc_data_structures::fx::FxHashSet;
18 use rustc_data_structures::sync::{par_for_each_in, Send, Sync};
19 use rustc_errors::FatalError;
20 use rustc_macros::HashStable_Generic;
21 use rustc_span::source_map::{SourceMap, Spanned};
22 use rustc_span::symbol::{kw, sym, Symbol};
23 use rustc_span::{MultiSpan, Span, DUMMY_SP};
24 use rustc_target::spec::abi::Abi;
26 use smallvec::SmallVec;
27 use std::collections::{BTreeMap, BTreeSet};
30 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, HashStable_Generic)]
35 /// Either "`'a`", referring to a named lifetime definition,
36 /// or "``" (i.e., `kw::Invalid`), for elision placeholders.
38 /// HIR lowering inserts these placeholders in type paths that
39 /// refer to type definitions needing lifetime parameters,
40 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
41 pub name: LifetimeName,
44 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
45 #[derive(HashStable_Generic)]
47 /// Some user-given name like `T` or `'x`.
50 /// Synthetic name generated when user elided a lifetime in an impl header.
52 /// E.g., the lifetimes in cases like these:
55 /// impl Foo<'_> for u32
57 /// in that case, we rewrite to
59 /// impl<'f> Foo for &'f u32
60 /// impl<'f> Foo<'f> for u32
62 /// where `'f` is something like `Fresh(0)`. The indices are
63 /// unique per impl, but not necessarily continuous.
66 /// Indicates an illegal name was given and an error has been
67 /// reported (so we should squelch other derived errors). Occurs
68 /// when, e.g., `'_` is used in the wrong place.
73 pub fn ident(&self) -> Ident {
75 ParamName::Plain(ident) => ident,
76 ParamName::Fresh(_) | ParamName::Error => {
77 Ident::with_dummy_span(kw::UnderscoreLifetime)
82 pub fn normalize_to_macros_2_0(&self) -> ParamName {
84 ParamName::Plain(ident) => ParamName::Plain(ident.normalize_to_macros_2_0()),
85 param_name => param_name,
90 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
91 #[derive(HashStable_Generic)]
92 pub enum LifetimeName {
93 /// User-given names or fresh (synthetic) names.
96 /// User wrote nothing (e.g., the lifetime in `&u32`).
99 /// Implicit lifetime in a context like `dyn Foo`. This is
100 /// distinguished from implicit lifetimes elsewhere because the
101 /// lifetime that they default to must appear elsewhere within the
102 /// enclosing type. This means that, in an `impl Trait` context, we
103 /// don't have to create a parameter for them. That is, `impl
104 /// Trait<Item = &u32>` expands to an opaque type like `type
105 /// Foo<'a> = impl Trait<Item = &'a u32>`, but `impl Trait<item =
106 /// dyn Bar>` expands to `type Foo = impl Trait<Item = dyn Bar +
107 /// 'static>`. The latter uses `ImplicitObjectLifetimeDefault` so
108 /// that surrounding code knows not to create a lifetime
110 ImplicitObjectLifetimeDefault,
112 /// Indicates an error during lowering (usually `'_` in wrong place)
113 /// that was already reported.
116 /// User wrote specifies `'_`.
119 /// User wrote `'static`.
124 pub fn ident(&self) -> Ident {
126 LifetimeName::ImplicitObjectLifetimeDefault
127 | LifetimeName::Implicit
128 | LifetimeName::Error => Ident::invalid(),
129 LifetimeName::Underscore => Ident::with_dummy_span(kw::UnderscoreLifetime),
130 LifetimeName::Static => Ident::with_dummy_span(kw::StaticLifetime),
131 LifetimeName::Param(param_name) => param_name.ident(),
135 pub fn is_elided(&self) -> bool {
137 LifetimeName::ImplicitObjectLifetimeDefault
138 | LifetimeName::Implicit
139 | LifetimeName::Underscore => true,
141 // It might seem surprising that `Fresh(_)` counts as
142 // *not* elided -- but this is because, as far as the code
143 // in the compiler is concerned -- `Fresh(_)` variants act
144 // equivalently to "some fresh name". They correspond to
145 // early-bound regions on an impl, in other words.
146 LifetimeName::Error | LifetimeName::Param(_) | LifetimeName::Static => false,
150 fn is_static(&self) -> bool {
151 self == &LifetimeName::Static
154 pub fn normalize_to_macros_2_0(&self) -> LifetimeName {
156 LifetimeName::Param(param_name) => {
157 LifetimeName::Param(param_name.normalize_to_macros_2_0())
159 lifetime_name => lifetime_name,
164 impl fmt::Display for Lifetime {
165 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166 self.name.ident().fmt(f)
170 impl fmt::Debug for Lifetime {
171 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
176 print::to_string(print::NO_ANN, |s| s.print_lifetime(self))
182 pub fn is_elided(&self) -> bool {
183 self.name.is_elided()
186 pub fn is_static(&self) -> bool {
187 self.name.is_static()
191 /// A `Path` is essentially Rust's notion of a name; for instance,
192 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
193 /// along with a bunch of supporting information.
194 #[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
195 pub struct Path<'hir> {
197 /// The resolution for the path.
199 /// The segments in the path: the things separated by `::`.
200 pub segments: &'hir [PathSegment<'hir>],
204 pub fn is_global(&self) -> bool {
205 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
209 impl fmt::Debug for Path<'_> {
210 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
211 write!(f, "path({})", self)
215 impl fmt::Display for Path<'_> {
216 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
217 write!(f, "{}", print::to_string(print::NO_ANN, |s| s.print_path(self, false)))
221 /// A segment of a path: an identifier, an optional lifetime, and a set of
223 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
224 pub struct PathSegment<'hir> {
225 /// The identifier portion of this path segment.
226 #[stable_hasher(project(name))]
228 // `id` and `res` are optional. We currently only use these in save-analysis,
229 // any path segments without these will not have save-analysis info and
230 // therefore will not have 'jump to def' in IDEs, but otherwise will not be
231 // affected. (In general, we don't bother to get the defs for synthesized
232 // segments, only for segments which have come from the AST).
233 pub hir_id: Option<HirId>,
234 pub res: Option<Res>,
236 /// Type/lifetime parameters attached to this path. They come in
237 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
238 /// this is more than just simple syntactic sugar; the use of
239 /// parens affects the region binding rules, so we preserve the
241 pub args: Option<&'hir GenericArgs<'hir>>,
243 /// Whether to infer remaining type parameters, if any.
244 /// This only applies to expression and pattern paths, and
245 /// out of those only the segments with no type parameters
246 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
247 pub infer_args: bool,
250 impl<'hir> PathSegment<'hir> {
251 /// Converts an identifier to the corresponding segment.
252 pub fn from_ident(ident: Ident) -> PathSegment<'hir> {
253 PathSegment { ident, hir_id: None, res: None, infer_args: true, args: None }
256 pub fn generic_args(&self) -> &GenericArgs<'hir> {
257 if let Some(ref args) = self.args {
260 const DUMMY: &GenericArgs<'_> = &GenericArgs::none();
266 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
267 pub struct ConstArg {
268 pub value: AnonConst,
272 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
273 pub enum GenericArg<'hir> {
279 impl GenericArg<'_> {
280 pub fn span(&self) -> Span {
282 GenericArg::Lifetime(l) => l.span,
283 GenericArg::Type(t) => t.span,
284 GenericArg::Const(c) => c.span,
288 pub fn id(&self) -> HirId {
290 GenericArg::Lifetime(l) => l.hir_id,
291 GenericArg::Type(t) => t.hir_id,
292 GenericArg::Const(c) => c.value.hir_id,
296 pub fn is_const(&self) -> bool {
298 GenericArg::Const(_) => true,
303 pub fn descr(&self) -> &'static str {
305 GenericArg::Lifetime(_) => "lifetime",
306 GenericArg::Type(_) => "type",
307 GenericArg::Const(_) => "constant",
312 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
313 pub struct GenericArgs<'hir> {
314 /// The generic arguments for this path segment.
315 pub args: &'hir [GenericArg<'hir>],
316 /// Bindings (equality constraints) on associated types, if present.
317 /// E.g., `Foo<A = Bar>`.
318 pub bindings: &'hir [TypeBinding<'hir>],
319 /// Were arguments written in parenthesized form `Fn(T) -> U`?
320 /// This is required mostly for pretty-printing and diagnostics,
321 /// but also for changing lifetime elision rules to be "function-like".
322 pub parenthesized: bool,
325 impl GenericArgs<'_> {
326 pub const fn none() -> Self {
327 Self { args: &[], bindings: &[], parenthesized: false }
330 pub fn is_empty(&self) -> bool {
331 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
334 pub fn inputs(&self) -> &[Ty<'_>] {
335 if self.parenthesized {
336 for arg in self.args {
338 GenericArg::Lifetime(_) => {}
339 GenericArg::Type(ref ty) => {
340 if let TyKind::Tup(ref tys) = ty.kind {
345 GenericArg::Const(_) => {}
349 panic!("GenericArgs::inputs: not a `Fn(T) -> U`");
352 pub fn own_counts(&self) -> GenericParamCount {
353 // We could cache this as a property of `GenericParamCount`, but
354 // the aim is to refactor this away entirely eventually and the
355 // presence of this method will be a constant reminder.
356 let mut own_counts: GenericParamCount = Default::default();
358 for arg in self.args {
360 GenericArg::Lifetime(_) => own_counts.lifetimes += 1,
361 GenericArg::Type(_) => own_counts.types += 1,
362 GenericArg::Const(_) => own_counts.consts += 1,
370 /// A modifier on a bound, currently this is only used for `?Sized`, where the
371 /// modifier is `Maybe`. Negative bounds should also be handled here.
372 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
373 #[derive(HashStable_Generic)]
374 pub enum TraitBoundModifier {
380 /// The AST represents all type param bounds as types.
381 /// `typeck::collect::compute_bounds` matches these against
382 /// the "special" built-in traits (see `middle::lang_items`) and
383 /// detects `Copy`, `Send` and `Sync`.
384 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
385 pub enum GenericBound<'hir> {
386 Trait(PolyTraitRef<'hir>, TraitBoundModifier),
390 impl GenericBound<'_> {
391 pub fn trait_def_id(&self) -> Option<DefId> {
393 GenericBound::Trait(data, _) => Some(data.trait_ref.trait_def_id()),
398 pub fn span(&self) -> Span {
400 &GenericBound::Trait(ref t, ..) => t.span,
401 &GenericBound::Outlives(ref l) => l.span,
406 pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
408 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
409 pub enum LifetimeParamKind {
410 // Indicates that the lifetime definition was explicitly declared (e.g., in
411 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
414 // Indicates that the lifetime definition was synthetically added
415 // as a result of an in-band lifetime usage (e.g., in
416 // `fn foo(x: &'a u8) -> &'a u8 { x }`).
419 // Indication that the lifetime was elided (e.g., in both cases in
420 // `fn foo(x: &u8) -> &'_ u8 { x }`).
423 // Indication that the lifetime name was somehow in error.
427 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
428 pub enum GenericParamKind<'hir> {
429 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
431 kind: LifetimeParamKind,
434 default: Option<&'hir Ty<'hir>>,
435 synthetic: Option<SyntheticTyParamKind>,
442 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
443 pub struct GenericParam<'hir> {
446 pub attrs: &'hir [Attribute],
447 pub bounds: GenericBounds<'hir>,
449 pub pure_wrt_drop: bool,
450 pub kind: GenericParamKind<'hir>,
453 impl GenericParam<'hir> {
454 pub fn bounds_span(&self) -> Option<Span> {
455 self.bounds.iter().fold(None, |span, bound| {
456 let span = span.map(|s| s.to(bound.span())).unwrap_or_else(|| bound.span());
464 pub struct GenericParamCount {
465 pub lifetimes: usize,
470 /// Represents lifetimes and type parameters attached to a declaration
471 /// of a function, enum, trait, etc.
472 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
473 pub struct Generics<'hir> {
474 pub params: &'hir [GenericParam<'hir>],
475 pub where_clause: WhereClause<'hir>,
479 impl Generics<'hir> {
480 pub const fn empty() -> Generics<'hir> {
483 where_clause: WhereClause { predicates: &[], span: DUMMY_SP },
488 pub fn own_counts(&self) -> GenericParamCount {
489 // We could cache this as a property of `GenericParamCount`, but
490 // the aim is to refactor this away entirely eventually and the
491 // presence of this method will be a constant reminder.
492 let mut own_counts: GenericParamCount = Default::default();
494 for param in self.params {
496 GenericParamKind::Lifetime { .. } => own_counts.lifetimes += 1,
497 GenericParamKind::Type { .. } => own_counts.types += 1,
498 GenericParamKind::Const { .. } => own_counts.consts += 1,
505 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'_>> {
506 for param in self.params {
507 if name == param.name.ident().name {
514 pub fn spans(&self) -> MultiSpan {
515 if self.params.is_empty() {
518 self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
523 /// Synthetic type parameters are converted to another form during lowering; this allows
524 /// us to track the original form they had, and is useful for error messages.
525 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
526 #[derive(HashStable_Generic)]
527 pub enum SyntheticTyParamKind {
531 /// A where-clause in a definition.
532 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
533 pub struct WhereClause<'hir> {
534 pub predicates: &'hir [WherePredicate<'hir>],
535 // Only valid if predicates aren't empty.
539 impl WhereClause<'_> {
540 pub fn span(&self) -> Option<Span> {
541 if self.predicates.is_empty() { None } else { Some(self.span) }
544 /// The `WhereClause` under normal circumstances points at either the predicates or the empty
545 /// space where the `where` clause should be. Only of use for diagnostic suggestions.
546 pub fn span_for_predicates_or_empty_place(&self) -> Span {
551 /// A single predicate in a where-clause.
552 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
553 pub enum WherePredicate<'hir> {
554 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
555 BoundPredicate(WhereBoundPredicate<'hir>),
556 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
557 RegionPredicate(WhereRegionPredicate<'hir>),
558 /// An equality predicate (unsupported).
559 EqPredicate(WhereEqPredicate<'hir>),
562 impl WherePredicate<'_> {
563 pub fn span(&self) -> Span {
565 &WherePredicate::BoundPredicate(ref p) => p.span,
566 &WherePredicate::RegionPredicate(ref p) => p.span,
567 &WherePredicate::EqPredicate(ref p) => p.span,
572 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
573 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
574 pub struct WhereBoundPredicate<'hir> {
576 /// Any generics from a `for` binding.
577 pub bound_generic_params: &'hir [GenericParam<'hir>],
578 /// The type being bounded.
579 pub bounded_ty: &'hir Ty<'hir>,
580 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
581 pub bounds: GenericBounds<'hir>,
584 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
585 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
586 pub struct WhereRegionPredicate<'hir> {
588 pub lifetime: Lifetime,
589 pub bounds: GenericBounds<'hir>,
592 /// An equality predicate (e.g., `T = int`); currently unsupported.
593 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
594 pub struct WhereEqPredicate<'hir> {
597 pub lhs_ty: &'hir Ty<'hir>,
598 pub rhs_ty: &'hir Ty<'hir>,
601 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
602 pub struct ModuleItems {
603 // Use BTreeSets here so items are in the same order as in the
604 // list of all items in Crate
605 pub items: BTreeSet<HirId>,
606 pub trait_items: BTreeSet<TraitItemId>,
607 pub impl_items: BTreeSet<ImplItemId>,
610 /// A type representing only the top-level module.
611 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
612 pub struct CrateItem<'hir> {
613 pub module: Mod<'hir>,
614 pub attrs: &'hir [Attribute],
618 /// The top-level data structure that stores the entire contents of
619 /// the crate currently being compiled.
621 /// For more details, see the [rustc dev guide].
623 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
624 #[derive(RustcEncodable, RustcDecodable, Debug)]
625 pub struct Crate<'hir> {
626 pub item: CrateItem<'hir>,
627 pub exported_macros: &'hir [MacroDef<'hir>],
628 // Attributes from non-exported macros, kept only for collecting the library feature list.
629 pub non_exported_macro_attrs: &'hir [Attribute],
631 // N.B., we use a `BTreeMap` here so that `visit_all_items` iterates
632 // over the ids in increasing order. In principle it should not
633 // matter what order we visit things in, but in *practice* it
634 // does, because it can affect the order in which errors are
635 // detected, which in turn can make compile-fail tests yield
636 // slightly different results.
637 pub items: BTreeMap<HirId, Item<'hir>>,
639 pub trait_items: BTreeMap<TraitItemId, TraitItem<'hir>>,
640 pub impl_items: BTreeMap<ImplItemId, ImplItem<'hir>>,
641 pub bodies: BTreeMap<BodyId, Body<'hir>>,
642 pub trait_impls: BTreeMap<DefId, Vec<HirId>>,
644 /// A list of the body ids written out in the order in which they
645 /// appear in the crate. If you're going to process all the bodies
646 /// in the crate, you should iterate over this list rather than the keys
648 pub body_ids: Vec<BodyId>,
650 /// A list of modules written out in the order in which they
651 /// appear in the crate. This includes the main crate module.
652 pub modules: BTreeMap<HirId, ModuleItems>,
653 /// A list of proc macro HirIds, written out in the order in which
654 /// they are declared in the static array generated by proc_macro_harness.
655 pub proc_macros: Vec<HirId>,
659 pub fn item(&self, id: HirId) -> &Item<'hir> {
663 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem<'hir> {
664 &self.trait_items[&id]
667 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem<'hir> {
668 &self.impl_items[&id]
671 pub fn body(&self, id: BodyId) -> &Body<'hir> {
677 /// Visits all items in the crate in some deterministic (but
678 /// unspecified) order. If you just need to process every item,
679 /// but don't care about nesting, this method is the best choice.
681 /// If you do care about nesting -- usually because your algorithm
682 /// follows lexical scoping rules -- then you want a different
683 /// approach. You should override `visit_nested_item` in your
684 /// visitor and then call `intravisit::walk_crate` instead.
685 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
687 V: itemlikevisit::ItemLikeVisitor<'hir>,
689 for item in self.items.values() {
690 visitor.visit_item(item);
693 for trait_item in self.trait_items.values() {
694 visitor.visit_trait_item(trait_item);
697 for impl_item in self.impl_items.values() {
698 visitor.visit_impl_item(impl_item);
702 /// A parallel version of `visit_all_item_likes`.
703 pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
705 V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send,
709 par_for_each_in(&self.items, |(_, item)| {
710 visitor.visit_item(item);
714 par_for_each_in(&self.trait_items, |(_, trait_item)| {
715 visitor.visit_trait_item(trait_item);
719 par_for_each_in(&self.impl_items, |(_, impl_item)| {
720 visitor.visit_impl_item(impl_item);
727 /// A macro definition, in this crate or imported from another.
729 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
730 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
731 pub struct MacroDef<'hir> {
733 pub vis: Visibility<'hir>,
734 pub attrs: &'hir [Attribute],
737 pub ast: ast::MacroDef,
740 /// A block of statements `{ .. }`, which may have a label (in this case the
741 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
742 /// the `rules` being anything but `DefaultBlock`.
743 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
744 pub struct Block<'hir> {
745 /// Statements in a block.
746 pub stmts: &'hir [Stmt<'hir>],
747 /// An expression at the end of the block
748 /// without a semicolon, if any.
749 pub expr: Option<&'hir Expr<'hir>>,
750 #[stable_hasher(ignore)]
752 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
753 pub rules: BlockCheckMode,
755 /// If true, then there may exist `break 'a` values that aim to
756 /// break out of this block early.
757 /// Used by `'label: {}` blocks and by `try {}` blocks.
758 pub targeted_by_break: bool,
761 #[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
762 pub struct Pat<'hir> {
763 #[stable_hasher(ignore)]
765 pub kind: PatKind<'hir>,
769 impl fmt::Debug for Pat<'_> {
770 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
775 print::to_string(print::NO_ANN, |s| s.print_pat(self))
781 // FIXME(#19596) this is a workaround, but there should be a better way
782 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'_>) -> bool) -> bool {
789 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
790 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
791 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
792 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
793 Slice(before, slice, after) => {
794 before.iter().chain(slice.iter()).chain(after.iter()).all(|p| p.walk_short_(it))
799 /// Walk the pattern in left-to-right order,
800 /// short circuiting (with `.all(..)`) if `false` is returned.
802 /// Note that when visiting e.g. `Tuple(ps)`,
803 /// if visiting `ps[0]` returns `false`,
804 /// then `ps[1]` will not be visited.
805 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'_>) -> bool) -> bool {
806 self.walk_short_(&mut it)
809 // FIXME(#19596) this is a workaround, but there should be a better way
810 fn walk_(&self, it: &mut impl FnMut(&Pat<'_>) -> bool) {
817 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
818 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
819 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
820 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
821 Slice(before, slice, after) => {
822 before.iter().chain(slice.iter()).chain(after.iter()).for_each(|p| p.walk_(it))
827 /// Walk the pattern in left-to-right order.
829 /// If `it(pat)` returns `false`, the children are not visited.
830 pub fn walk(&self, mut it: impl FnMut(&Pat<'_>) -> bool) {
834 /// Walk the pattern in left-to-right order.
836 /// If you always want to recurse, prefer this method over `walk`.
837 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
845 /// A single field in a struct pattern.
847 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
848 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
849 /// except `is_shorthand` is true.
850 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
851 pub struct FieldPat<'hir> {
852 #[stable_hasher(ignore)]
854 /// The identifier for the field.
855 #[stable_hasher(project(name))]
857 /// The pattern the field is destructured to.
858 pub pat: &'hir Pat<'hir>,
859 pub is_shorthand: bool,
863 /// Explicit binding annotations given in the HIR for a binding. Note
864 /// that this is not the final binding *mode* that we infer after type
866 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
867 pub enum BindingAnnotation {
868 /// No binding annotation given: this means that the final binding mode
869 /// will depend on whether we have skipped through a `&` reference
870 /// when matching. For example, the `x` in `Some(x)` will have binding
871 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
872 /// ultimately be inferred to be by-reference.
874 /// Note that implicit reference skipping is not implemented yet (#42640).
877 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
880 /// Annotated as `ref`, like `ref x`
883 /// Annotated as `ref mut x`.
887 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
893 impl fmt::Display for RangeEnd {
894 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
895 f.write_str(match self {
896 RangeEnd::Included => "..=",
897 RangeEnd::Excluded => "..",
902 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
903 pub enum PatKind<'hir> {
904 /// Represents a wildcard pattern (i.e., `_`).
907 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
908 /// The `HirId` is the canonical ID for the variable being bound,
909 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
910 /// which is the pattern ID of the first `x`.
911 Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
913 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
914 /// The `bool` is `true` in the presence of a `..`.
915 Struct(QPath<'hir>, &'hir [FieldPat<'hir>], bool),
917 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
918 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
919 /// `0 <= position <= subpats.len()`
920 TupleStruct(QPath<'hir>, &'hir [&'hir Pat<'hir>], Option<usize>),
922 /// An or-pattern `A | B | C`.
923 /// Invariant: `pats.len() >= 2`.
924 Or(&'hir [&'hir Pat<'hir>]),
926 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
929 /// A tuple pattern (e.g., `(a, b)`).
930 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
931 /// `0 <= position <= subpats.len()`
932 Tuple(&'hir [&'hir Pat<'hir>], Option<usize>),
935 Box(&'hir Pat<'hir>),
937 /// A reference pattern (e.g., `&mut (a, b)`).
938 Ref(&'hir Pat<'hir>, Mutability),
941 Lit(&'hir Expr<'hir>),
943 /// A range pattern (e.g., `1..=2` or `1..2`).
944 Range(Option<&'hir Expr<'hir>>, Option<&'hir Expr<'hir>>, RangeEnd),
946 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
948 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
949 /// If `slice` exists, then `after` can be non-empty.
951 /// The representation for e.g., `[a, b, .., c, d]` is:
953 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
955 Slice(&'hir [&'hir Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [&'hir Pat<'hir>]),
958 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
960 /// The `+` operator (addition).
962 /// The `-` operator (subtraction).
964 /// The `*` operator (multiplication).
966 /// The `/` operator (division).
968 /// The `%` operator (modulus).
970 /// The `&&` operator (logical and).
972 /// The `||` operator (logical or).
974 /// The `^` operator (bitwise xor).
976 /// The `&` operator (bitwise and).
978 /// The `|` operator (bitwise or).
980 /// The `<<` operator (shift left).
982 /// The `>>` operator (shift right).
984 /// The `==` operator (equality).
986 /// The `<` operator (less than).
988 /// The `<=` operator (less than or equal to).
990 /// The `!=` operator (not equal to).
992 /// The `>=` operator (greater than or equal to).
994 /// The `>` operator (greater than).
999 pub fn as_str(self) -> &'static str {
1001 BinOpKind::Add => "+",
1002 BinOpKind::Sub => "-",
1003 BinOpKind::Mul => "*",
1004 BinOpKind::Div => "/",
1005 BinOpKind::Rem => "%",
1006 BinOpKind::And => "&&",
1007 BinOpKind::Or => "||",
1008 BinOpKind::BitXor => "^",
1009 BinOpKind::BitAnd => "&",
1010 BinOpKind::BitOr => "|",
1011 BinOpKind::Shl => "<<",
1012 BinOpKind::Shr => ">>",
1013 BinOpKind::Eq => "==",
1014 BinOpKind::Lt => "<",
1015 BinOpKind::Le => "<=",
1016 BinOpKind::Ne => "!=",
1017 BinOpKind::Ge => ">=",
1018 BinOpKind::Gt => ">",
1022 pub fn is_lazy(self) -> bool {
1024 BinOpKind::And | BinOpKind::Or => true,
1029 pub fn is_shift(self) -> bool {
1031 BinOpKind::Shl | BinOpKind::Shr => true,
1036 pub fn is_comparison(self) -> bool {
1043 | BinOpKind::Ge => true,
1055 | BinOpKind::Shr => false,
1059 /// Returns `true` if the binary operator takes its arguments by value.
1060 pub fn is_by_value(self) -> bool {
1061 !self.is_comparison()
1065 impl Into<ast::BinOpKind> for BinOpKind {
1066 fn into(self) -> ast::BinOpKind {
1068 BinOpKind::Add => ast::BinOpKind::Add,
1069 BinOpKind::Sub => ast::BinOpKind::Sub,
1070 BinOpKind::Mul => ast::BinOpKind::Mul,
1071 BinOpKind::Div => ast::BinOpKind::Div,
1072 BinOpKind::Rem => ast::BinOpKind::Rem,
1073 BinOpKind::And => ast::BinOpKind::And,
1074 BinOpKind::Or => ast::BinOpKind::Or,
1075 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1076 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1077 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1078 BinOpKind::Shl => ast::BinOpKind::Shl,
1079 BinOpKind::Shr => ast::BinOpKind::Shr,
1080 BinOpKind::Eq => ast::BinOpKind::Eq,
1081 BinOpKind::Lt => ast::BinOpKind::Lt,
1082 BinOpKind::Le => ast::BinOpKind::Le,
1083 BinOpKind::Ne => ast::BinOpKind::Ne,
1084 BinOpKind::Ge => ast::BinOpKind::Ge,
1085 BinOpKind::Gt => ast::BinOpKind::Gt,
1090 pub type BinOp = Spanned<BinOpKind>;
1092 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1094 /// The `*` operator (deferencing).
1096 /// The `!` operator (logical negation).
1098 /// The `-` operator (negation).
1103 pub fn as_str(self) -> &'static str {
1105 Self::UnDeref => "*",
1111 /// Returns `true` if the unary operator takes its argument by value.
1112 pub fn is_by_value(self) -> bool {
1114 Self::UnNeg | Self::UnNot => true,
1121 #[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
1122 pub struct Stmt<'hir> {
1124 pub kind: StmtKind<'hir>,
1128 impl fmt::Debug for Stmt<'_> {
1129 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1134 print::to_string(print::NO_ANN, |s| s.print_stmt(self))
1139 /// The contents of a statement.
1140 #[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
1141 pub enum StmtKind<'hir> {
1142 /// A local (`let`) binding.
1143 Local(&'hir Local<'hir>),
1145 /// An item binding.
1148 /// An expression without a trailing semi-colon (must have unit type).
1149 Expr(&'hir Expr<'hir>),
1151 /// An expression with a trailing semi-colon (may have any type).
1152 Semi(&'hir Expr<'hir>),
1155 impl StmtKind<'hir> {
1156 pub fn attrs(&self) -> &'hir [Attribute] {
1158 StmtKind::Local(ref l) => &l.attrs,
1159 StmtKind::Item(_) => &[],
1160 StmtKind::Expr(ref e) | StmtKind::Semi(ref e) => &e.attrs,
1165 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1166 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1167 pub struct Local<'hir> {
1168 pub pat: &'hir Pat<'hir>,
1169 /// Type annotation, if any (otherwise the type will be inferred).
1170 pub ty: Option<&'hir Ty<'hir>>,
1171 /// Initializer expression to set the value, if any.
1172 pub init: Option<&'hir Expr<'hir>>,
1176 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1177 /// desugaring. Otherwise will be `Normal`.
1178 pub source: LocalSource,
1181 /// Represents a single arm of a `match` expression, e.g.
1182 /// `<pat> (if <guard>) => <body>`.
1183 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1184 pub struct Arm<'hir> {
1185 #[stable_hasher(ignore)]
1188 pub attrs: &'hir [Attribute],
1189 /// If this pattern and the optional guard matches, then `body` is evaluated.
1190 pub pat: &'hir Pat<'hir>,
1191 /// Optional guard clause.
1192 pub guard: Option<Guard<'hir>>,
1193 /// The expression the arm evaluates to if this arm matches.
1194 pub body: &'hir Expr<'hir>,
1197 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1198 pub enum Guard<'hir> {
1199 If(&'hir Expr<'hir>),
1202 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1203 pub struct Field<'hir> {
1204 #[stable_hasher(ignore)]
1207 pub expr: &'hir Expr<'hir>,
1209 pub is_shorthand: bool,
1212 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1213 pub enum BlockCheckMode {
1215 UnsafeBlock(UnsafeSource),
1216 PushUnsafeBlock(UnsafeSource),
1217 PopUnsafeBlock(UnsafeSource),
1220 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1221 pub enum UnsafeSource {
1226 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1231 /// The body of a function, closure, or constant value. In the case of
1232 /// a function, the body contains not only the function body itself
1233 /// (which is an expression), but also the argument patterns, since
1234 /// those are something that the caller doesn't really care about.
1239 /// fn foo((x, y): (u32, u32)) -> u32 {
1244 /// Here, the `Body` associated with `foo()` would contain:
1246 /// - an `params` array containing the `(x, y)` pattern
1247 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1248 /// - `generator_kind` would be `None`
1250 /// All bodies have an **owner**, which can be accessed via the HIR
1251 /// map using `body_owner_def_id()`.
1252 #[derive(RustcEncodable, RustcDecodable, Debug)]
1253 pub struct Body<'hir> {
1254 pub params: &'hir [Param<'hir>],
1255 pub value: Expr<'hir>,
1256 pub generator_kind: Option<GeneratorKind>,
1260 pub fn id(&self) -> BodyId {
1261 BodyId { hir_id: self.value.hir_id }
1264 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1269 /// The type of source expression that caused this generator to be created.
1270 #[derive(Clone, PartialEq, Eq, HashStable_Generic, RustcEncodable, RustcDecodable, Debug, Copy)]
1271 pub enum GeneratorKind {
1272 /// An explicit `async` block or the body of an async function.
1273 Async(AsyncGeneratorKind),
1275 /// A generator literal created via a `yield` inside a closure.
1279 impl fmt::Display for GeneratorKind {
1280 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1282 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1283 GeneratorKind::Gen => f.write_str("generator"),
1288 /// In the case of a generator created as part of an async construct,
1289 /// which kind of async construct caused it to be created?
1291 /// This helps error messages but is also used to drive coercions in
1292 /// type-checking (see #60424).
1293 #[derive(Clone, PartialEq, Eq, HashStable_Generic, RustcEncodable, RustcDecodable, Debug, Copy)]
1294 pub enum AsyncGeneratorKind {
1295 /// An explicit `async` block written by the user.
1298 /// An explicit `async` block written by the user.
1301 /// The `async` block generated as the body of an async function.
1305 impl fmt::Display for AsyncGeneratorKind {
1306 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1307 f.write_str(match self {
1308 AsyncGeneratorKind::Block => "`async` block",
1309 AsyncGeneratorKind::Closure => "`async` closure body",
1310 AsyncGeneratorKind::Fn => "`async fn` body",
1315 #[derive(Copy, Clone, Debug)]
1316 pub enum BodyOwnerKind {
1317 /// Functions and methods.
1323 /// Constants and associated constants.
1326 /// Initializer of a `static` item.
1330 impl BodyOwnerKind {
1331 pub fn is_fn_or_closure(self) -> bool {
1333 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1334 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1340 pub type Lit = Spanned<LitKind>;
1342 /// A constant (expression) that's not an item or associated item,
1343 /// but needs its own `DefId` for type-checking, const-eval, etc.
1344 /// These are usually found nested inside types (e.g., array lengths)
1345 /// or expressions (e.g., repeat counts), and also used to define
1346 /// explicit discriminant values for enum variants.
1347 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1348 pub struct AnonConst {
1354 #[derive(RustcEncodable, RustcDecodable)]
1355 pub struct Expr<'hir> {
1357 pub kind: ExprKind<'hir>,
1362 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1363 #[cfg(target_arch = "x86_64")]
1364 rustc_data_structures::static_assert_size!(Expr<'static>, 64);
1367 pub fn precedence(&self) -> ExprPrecedence {
1369 ExprKind::Box(_) => ExprPrecedence::Box,
1370 ExprKind::Array(_) => ExprPrecedence::Array,
1371 ExprKind::Call(..) => ExprPrecedence::Call,
1372 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1373 ExprKind::Tup(_) => ExprPrecedence::Tup,
1374 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1375 ExprKind::Unary(..) => ExprPrecedence::Unary,
1376 ExprKind::Lit(_) => ExprPrecedence::Lit,
1377 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1378 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1379 ExprKind::Loop(..) => ExprPrecedence::Loop,
1380 ExprKind::Match(..) => ExprPrecedence::Match,
1381 ExprKind::Closure(..) => ExprPrecedence::Closure,
1382 ExprKind::Block(..) => ExprPrecedence::Block,
1383 ExprKind::Assign(..) => ExprPrecedence::Assign,
1384 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1385 ExprKind::Field(..) => ExprPrecedence::Field,
1386 ExprKind::Index(..) => ExprPrecedence::Index,
1387 ExprKind::Path(..) => ExprPrecedence::Path,
1388 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1389 ExprKind::Break(..) => ExprPrecedence::Break,
1390 ExprKind::Continue(..) => ExprPrecedence::Continue,
1391 ExprKind::Ret(..) => ExprPrecedence::Ret,
1392 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1393 ExprKind::Struct(..) => ExprPrecedence::Struct,
1394 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1395 ExprKind::Yield(..) => ExprPrecedence::Yield,
1396 ExprKind::Err => ExprPrecedence::Err,
1400 // Whether this looks like a place expr, without checking for deref
1402 // This will return `true` in some potentially surprising cases such as
1403 // `CONSTANT.field`.
1404 pub fn is_syntactic_place_expr(&self) -> bool {
1405 self.is_place_expr(|_| true)
1408 // Whether this is a place expression.
1409 // `allow_projections_from` should return `true` if indexing a field or
1410 // index expression based on the given expression should be considered a
1411 // place expression.
1412 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1414 ExprKind::Path(QPath::Resolved(_, ref path)) => match path.res {
1415 Res::Local(..) | Res::Def(DefKind::Static, _) | Res::Err => true,
1419 // Type ascription inherits its place expression kind from its
1421 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1422 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1424 ExprKind::Unary(UnOp::UnDeref, _) => true,
1426 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1427 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1430 // Partially qualified paths in expressions can only legally
1431 // refer to associated items which are always rvalues.
1432 ExprKind::Path(QPath::TypeRelative(..))
1433 | ExprKind::Call(..)
1434 | ExprKind::MethodCall(..)
1435 | ExprKind::Struct(..)
1437 | ExprKind::Match(..)
1438 | ExprKind::Closure(..)
1439 | ExprKind::Block(..)
1440 | ExprKind::Repeat(..)
1441 | ExprKind::Array(..)
1442 | ExprKind::Break(..)
1443 | ExprKind::Continue(..)
1445 | ExprKind::Loop(..)
1446 | ExprKind::Assign(..)
1447 | ExprKind::InlineAsm(..)
1448 | ExprKind::AssignOp(..)
1450 | ExprKind::Unary(..)
1452 | ExprKind::AddrOf(..)
1453 | ExprKind::Binary(..)
1454 | ExprKind::Yield(..)
1455 | ExprKind::Cast(..)
1456 | ExprKind::DropTemps(..)
1457 | ExprKind::Err => false,
1461 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1462 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1463 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1464 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1465 /// beyond remembering to call this function before doing analysis on it.
1466 pub fn peel_drop_temps(&self) -> &Self {
1467 let mut expr = self;
1468 while let ExprKind::DropTemps(inner) = &expr.kind {
1475 impl fmt::Debug for Expr<'_> {
1476 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1481 print::to_string(print::NO_ANN, |s| s.print_expr(self))
1486 /// Checks if the specified expression is a built-in range literal.
1487 /// (See: `LoweringContext::lower_expr()`).
1489 /// FIXME(#60607): This function is a hack. If and when we have `QPath::Lang(...)`,
1490 /// we can use that instead as simpler, more reliable mechanism, as opposed to using `SourceMap`.
1491 pub fn is_range_literal(sm: &SourceMap, expr: &Expr<'_>) -> bool {
1492 // Returns whether the given path represents a (desugared) range,
1493 // either in std or core, i.e. has either a `::std::ops::Range` or
1494 // `::core::ops::Range` prefix.
1495 fn is_range_path(path: &Path<'_>) -> bool {
1496 let segs: Vec<_> = path.segments.iter().map(|seg| seg.ident.to_string()).collect();
1497 let segs: Vec<_> = segs.iter().map(|seg| &**seg).collect();
1499 // "{{root}}" is the equivalent of `::` prefix in `Path`.
1500 if let ["{{root}}", std_core, "ops", range] = segs.as_slice() {
1501 (*std_core == "std" || *std_core == "core") && range.starts_with("Range")
1507 // Check whether a span corresponding to a range expression is a
1508 // range literal, rather than an explicit struct or `new()` call.
1509 fn is_lit(sm: &SourceMap, span: &Span) -> bool {
1510 let end_point = sm.end_point(*span);
1512 if let Ok(end_string) = sm.span_to_snippet(end_point) {
1513 !(end_string.ends_with('}') || end_string.ends_with(')'))
1520 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1521 ExprKind::Struct(ref qpath, _, _) => {
1522 if let QPath::Resolved(None, ref path) = **qpath {
1523 return is_range_path(&path) && is_lit(sm, &expr.span);
1527 // `..` desugars to its struct path.
1528 ExprKind::Path(QPath::Resolved(None, ref path)) => {
1529 return is_range_path(&path) && is_lit(sm, &expr.span);
1532 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1533 ExprKind::Call(ref func, _) => {
1534 if let ExprKind::Path(QPath::TypeRelative(ref ty, ref segment)) = func.kind {
1535 if let TyKind::Path(QPath::Resolved(None, ref path)) = ty.kind {
1536 let new_call = segment.ident.name == sym::new;
1537 return is_range_path(&path) && is_lit(sm, &expr.span) && new_call;
1548 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1549 pub enum ExprKind<'hir> {
1550 /// A `box x` expression.
1551 Box(&'hir Expr<'hir>),
1552 /// An array (e.g., `[a, b, c, d]`).
1553 Array(&'hir [Expr<'hir>]),
1554 /// A function call.
1556 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1557 /// and the second field is the list of arguments.
1558 /// This also represents calling the constructor of
1559 /// tuple-like ADTs such as tuple structs and enum variants.
1560 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1561 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1563 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1564 /// (within the angle brackets).
1565 /// The first element of the vector of `Expr`s is the expression that evaluates
1566 /// to the object on which the method is being called on (the receiver),
1567 /// and the remaining elements are the rest of the arguments.
1568 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1569 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1571 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1572 /// the `hir_id` of the `MethodCall` node itself.
1574 /// [`type_dependent_def_id`]: ../ty/struct.TypeckTables.html#method.type_dependent_def_id
1575 MethodCall(&'hir PathSegment<'hir>, Span, &'hir [Expr<'hir>]),
1576 /// A tuple (e.g., `(a, b, c, d)`).
1577 Tup(&'hir [Expr<'hir>]),
1578 /// A binary operation (e.g., `a + b`, `a * b`).
1579 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1580 /// A unary operation (e.g., `!x`, `*x`).
1581 Unary(UnOp, &'hir Expr<'hir>),
1582 /// A literal (e.g., `1`, `"foo"`).
1584 /// A cast (e.g., `foo as f64`).
1585 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1586 /// A type reference (e.g., `Foo`).
1587 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1588 /// Wraps the expression in a terminating scope.
1589 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1591 /// This construct only exists to tweak the drop order in HIR lowering.
1592 /// An example of that is the desugaring of `for` loops.
1593 DropTemps(&'hir Expr<'hir>),
1594 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1596 /// I.e., `'label: loop { <block> }`.
1597 Loop(&'hir Block<'hir>, Option<Label>, LoopSource),
1598 /// A `match` block, with a source that indicates whether or not it is
1599 /// the result of a desugaring, and if so, which kind.
1600 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1601 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1603 /// The `Span` is the argument block `|...|`.
1605 /// This may also be a generator literal or an `async block` as indicated by the
1606 /// `Option<Movability>`.
1607 Closure(CaptureBy, &'hir FnDecl<'hir>, BodyId, Span, Option<Movability>),
1608 /// A block (e.g., `'label: { ... }`).
1609 Block(&'hir Block<'hir>, Option<Label>),
1611 /// An assignment (e.g., `a = foo()`).
1612 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1613 /// An assignment with an operator.
1616 AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1617 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1618 Field(&'hir Expr<'hir>, Ident),
1619 /// An indexing operation (`foo[2]`).
1620 Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1622 /// Path to a definition, possibly containing lifetime or type parameters.
1625 /// A referencing operation (i.e., `&a` or `&mut a`).
1626 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1627 /// A `break`, with an optional label to break.
1628 Break(Destination, Option<&'hir Expr<'hir>>),
1629 /// A `continue`, with an optional label.
1630 Continue(Destination),
1631 /// A `return`, with an optional value to be returned.
1632 Ret(Option<&'hir Expr<'hir>>),
1634 /// Inline assembly (from `asm!`), with its outputs and inputs.
1635 InlineAsm(&'hir InlineAsm<'hir>),
1637 /// A struct or struct-like variant literal expression.
1639 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1640 /// where `base` is the `Option<Expr>`.
1641 Struct(&'hir QPath<'hir>, &'hir [Field<'hir>], Option<&'hir Expr<'hir>>),
1643 /// An array literal constructed from one repeated element.
1645 /// E.g., `[1; 5]`. The first expression is the element
1646 /// to be repeated; the second is the number of times to repeat it.
1647 Repeat(&'hir Expr<'hir>, AnonConst),
1649 /// A suspension point for generators (i.e., `yield <expr>`).
1650 Yield(&'hir Expr<'hir>, YieldSource),
1652 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1656 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1658 /// To resolve the path to a `DefId`, call [`qpath_res`].
1660 /// [`qpath_res`]: ../ty/struct.TypeckTables.html#method.qpath_res
1661 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1662 pub enum QPath<'hir> {
1663 /// Path to a definition, optionally "fully-qualified" with a `Self`
1664 /// type, if the path points to an associated item in a trait.
1666 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1667 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1668 /// even though they both have the same two-segment `Clone::clone` `Path`.
1669 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
1671 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1672 /// Will be resolved by type-checking to an associated item.
1674 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1675 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1676 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1677 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
1680 /// Hints at the original code for a let statement.
1681 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1682 pub enum LocalSource {
1683 /// A `match _ { .. }`.
1685 /// A desugared `for _ in _ { .. }` loop.
1687 /// When lowering async functions, we create locals within the `async move` so that
1688 /// all parameters are dropped after the future is polled.
1690 /// ```ignore (pseudo-Rust)
1691 /// async fn foo(<pattern> @ x: Type) {
1693 /// let <pattern> = x;
1698 /// A desugared `<expr>.await`.
1702 /// Hints at the original code for a `match _ { .. }`.
1703 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1704 #[derive(HashStable_Generic)]
1705 pub enum MatchSource {
1706 /// A `match _ { .. }`.
1708 /// An `if _ { .. }` (optionally with `else { .. }`).
1709 IfDesugar { contains_else_clause: bool },
1710 /// An `if let _ = _ { .. }` (optionally with `else { .. }`).
1711 IfLetDesugar { contains_else_clause: bool },
1712 /// A `while _ { .. }` (which was desugared to a `loop { match _ { .. } }`).
1714 /// A `while let _ = _ { .. }` (which was desugared to a
1715 /// `loop { match _ { .. } }`).
1717 /// A desugared `for _ in _ { .. }` loop.
1719 /// A desugared `?` operator.
1721 /// A desugared `<expr>.await`.
1726 pub fn name(self) -> &'static str {
1730 IfDesugar { .. } | IfLetDesugar { .. } => "if",
1731 WhileDesugar | WhileLetDesugar => "while",
1732 ForLoopDesugar => "for",
1734 AwaitDesugar => ".await",
1739 /// The loop type that yielded an `ExprKind::Loop`.
1740 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1741 pub enum LoopSource {
1742 /// A `loop { .. }` loop.
1744 /// A `while _ { .. }` loop.
1746 /// A `while let _ = _ { .. }` loop.
1748 /// A `for _ in _ { .. }` loop.
1753 pub fn name(self) -> &'static str {
1755 LoopSource::Loop => "loop",
1756 LoopSource::While | LoopSource::WhileLet => "while",
1757 LoopSource::ForLoop => "for",
1762 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1763 pub enum LoopIdError {
1765 UnlabeledCfInWhileCondition,
1769 impl fmt::Display for LoopIdError {
1770 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1771 f.write_str(match self {
1772 LoopIdError::OutsideLoopScope => "not inside loop scope",
1773 LoopIdError::UnlabeledCfInWhileCondition => {
1774 "unlabeled control flow (break or continue) in while condition"
1776 LoopIdError::UnresolvedLabel => "label not found",
1781 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1782 pub struct Destination {
1783 // This is `Some(_)` iff there is an explicit user-specified `label
1784 pub label: Option<Label>,
1786 // These errors are caught and then reported during the diagnostics pass in
1787 // librustc_passes/loops.rs
1788 pub target_id: Result<HirId, LoopIdError>,
1791 /// The yield kind that caused an `ExprKind::Yield`.
1792 #[derive(Copy, Clone, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable, HashStable_Generic)]
1793 pub enum YieldSource {
1794 /// An `<expr>.await`.
1796 /// A plain `yield`.
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,
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(RustcEncodable, RustcDecodable)]
1969 pub struct Ty<'hir> {
1971 pub kind: TyKind<'hir>,
1975 impl fmt::Debug for Ty<'_> {
1976 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1977 write!(f, "type({})", print::to_string(print::NO_ANN, |s| s.print_type(self)))
1981 /// Not represented directly in the AST; referred to by name through a `ty_path`.
1982 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1983 #[derive(HashStable_Generic)]
1993 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1994 pub struct BareFnTy<'hir> {
1995 pub unsafety: Unsafety,
1997 pub generic_params: &'hir [GenericParam<'hir>],
1998 pub decl: &'hir FnDecl<'hir>,
1999 pub param_names: &'hir [Ident],
2002 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2003 pub struct OpaqueTy<'hir> {
2004 pub generics: Generics<'hir>,
2005 pub bounds: GenericBounds<'hir>,
2006 pub impl_trait_fn: Option<DefId>,
2007 pub origin: OpaqueTyOrigin,
2010 /// From whence the opaque type came.
2011 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2012 pub enum OpaqueTyOrigin {
2013 /// `type Foo = impl Trait;`
2019 /// Impl trait in bindings, consts, statics, bounds.
2023 /// The various kinds of types recognized by the compiler.
2024 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2025 pub enum TyKind<'hir> {
2026 /// A variable length slice (i.e., `[T]`).
2027 Slice(&'hir Ty<'hir>),
2028 /// A fixed length array (i.e., `[T; n]`).
2029 Array(&'hir Ty<'hir>, AnonConst),
2030 /// A raw pointer (i.e., `*const T` or `*mut T`).
2032 /// A reference (i.e., `&'a T` or `&'a mut T`).
2033 Rptr(Lifetime, MutTy<'hir>),
2034 /// A bare function (e.g., `fn(usize) -> bool`).
2035 BareFn(&'hir BareFnTy<'hir>),
2036 /// The never type (`!`).
2038 /// A tuple (`(A, B, C, D, ...)`).
2039 Tup(&'hir [Ty<'hir>]),
2040 /// A path to a type definition (`module::module::...::Type`), or an
2041 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2043 /// Type parameters may be stored in each `PathSegment`.
2045 /// A type definition itself. This is currently only used for the `type Foo = impl Trait`
2046 /// item that `impl Trait` in return position desugars to.
2048 /// The generic argument list contains the lifetimes (and in the future possibly parameters)
2049 /// that are actually bound on the `impl Trait`.
2050 Def(ItemId, &'hir [GenericArg<'hir>]),
2051 /// A trait object type `Bound1 + Bound2 + Bound3`
2052 /// where `Bound` is a trait or a lifetime.
2053 TraitObject(&'hir [PolyTraitRef<'hir>], Lifetime),
2056 /// `TyKind::Infer` means the type should be inferred instead of it having been
2057 /// specified. This can appear anywhere in a type.
2059 /// Placeholder for a type that has failed to be defined.
2063 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic, PartialEq)]
2064 pub struct InlineAsmOutput {
2065 pub constraint: Symbol,
2067 pub is_indirect: bool,
2071 // NOTE(eddyb) This is used within MIR as well, so unlike the rest of the HIR,
2072 // it needs to be `Clone` and use plain `Vec<T>` instead of arena-allocated slice.
2073 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic, PartialEq)]
2074 pub struct InlineAsmInner {
2076 pub asm_str_style: StrStyle,
2077 pub outputs: Vec<InlineAsmOutput>,
2078 pub inputs: Vec<Symbol>,
2079 pub clobbers: Vec<Symbol>,
2081 pub alignstack: bool,
2082 pub dialect: AsmDialect,
2085 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2086 pub struct InlineAsm<'hir> {
2087 pub inner: InlineAsmInner,
2088 pub outputs_exprs: &'hir [Expr<'hir>],
2089 pub inputs_exprs: &'hir [Expr<'hir>],
2092 /// Represents a parameter in a function header.
2093 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2094 pub struct Param<'hir> {
2095 pub attrs: &'hir [Attribute],
2097 pub pat: &'hir Pat<'hir>,
2101 /// Represents the header (not the body) of a function declaration.
2102 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2103 pub struct FnDecl<'hir> {
2104 /// The types of the function's parameters.
2106 /// Additional argument data is stored in the function's [body](Body::parameters).
2107 pub inputs: &'hir [Ty<'hir>],
2108 pub output: FnRetTy<'hir>,
2109 pub c_variadic: bool,
2110 /// Does the function have an implicit self?
2111 pub implicit_self: ImplicitSelfKind,
2114 /// Represents what type of implicit self a function has, if any.
2115 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2116 pub enum ImplicitSelfKind {
2117 /// Represents a `fn x(self);`.
2119 /// Represents a `fn x(mut self);`.
2121 /// Represents a `fn x(&self);`.
2123 /// Represents a `fn x(&mut self);`.
2125 /// Represents when a function does not have a self argument or
2126 /// when a function has a `self: X` argument.
2130 impl ImplicitSelfKind {
2131 /// Does this represent an implicit self?
2132 pub fn has_implicit_self(&self) -> bool {
2134 ImplicitSelfKind::None => false,
2140 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
2141 #[derive(HashStable_Generic)]
2147 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2148 pub enum Defaultness {
2149 Default { has_value: bool },
2154 pub fn has_value(&self) -> bool {
2156 Defaultness::Default { has_value, .. } => has_value,
2157 Defaultness::Final => true,
2161 pub fn is_final(&self) -> bool {
2162 *self == Defaultness::Final
2165 pub fn is_default(&self) -> bool {
2167 Defaultness::Default { .. } => true,
2173 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2174 pub enum FnRetTy<'hir> {
2175 /// Return type is not specified.
2177 /// Functions default to `()` and
2178 /// closures default to inference. Span points to where return
2179 /// type would be inserted.
2180 DefaultReturn(Span),
2181 /// Everything else.
2182 Return(&'hir Ty<'hir>),
2185 impl fmt::Display for FnRetTy<'_> {
2186 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2188 Self::Return(ref ty) => print::to_string(print::NO_ANN, |s| s.print_type(ty)).fmt(f),
2189 Self::DefaultReturn(_) => "()".fmt(f),
2195 pub fn span(&self) -> Span {
2197 Self::DefaultReturn(span) => span,
2198 Self::Return(ref ty) => ty.span,
2203 #[derive(RustcEncodable, RustcDecodable, Debug)]
2204 pub struct Mod<'hir> {
2205 /// A span from the first token past `{` to the last token until `}`.
2206 /// For `mod foo;`, the inner span ranges from the first token
2207 /// to the last token in the external file.
2209 pub item_ids: &'hir [ItemId],
2212 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2213 pub struct ForeignMod<'hir> {
2215 pub items: &'hir [ForeignItem<'hir>],
2218 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2219 pub struct GlobalAsm {
2223 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2224 pub struct EnumDef<'hir> {
2225 pub variants: &'hir [Variant<'hir>],
2228 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2229 pub struct Variant<'hir> {
2230 /// Name of the variant.
2231 #[stable_hasher(project(name))]
2233 /// Attributes of the variant.
2234 pub attrs: &'hir [Attribute],
2235 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2237 /// Fields and constructor id of the variant.
2238 pub data: VariantData<'hir>,
2239 /// Explicit discriminant (e.g., `Foo = 1`).
2240 pub disr_expr: Option<AnonConst>,
2245 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2247 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2248 /// Also produced for each element of a list `use`, e.g.
2249 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2252 /// Glob import, e.g., `use foo::*`.
2255 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2256 /// an additional `use foo::{}` for performing checks such as
2257 /// unstable feature gating. May be removed in the future.
2261 /// References to traits in impls.
2263 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2264 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2265 /// trait being referred to but just a unique `HirId` that serves as a key
2266 /// within the resolution map.
2267 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2268 pub struct TraitRef<'hir> {
2269 pub path: &'hir Path<'hir>,
2270 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2271 #[stable_hasher(ignore)]
2272 pub hir_ref_id: HirId,
2276 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2277 pub fn trait_def_id(&self) -> DefId {
2278 match self.path.res {
2279 Res::Def(DefKind::Trait, did) => did,
2280 Res::Def(DefKind::TraitAlias, did) => did,
2284 _ => unreachable!(),
2289 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2290 pub struct PolyTraitRef<'hir> {
2291 /// The `'a` in `for<'a> Foo<&'a T>`.
2292 pub bound_generic_params: &'hir [GenericParam<'hir>],
2294 /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
2295 pub trait_ref: TraitRef<'hir>,
2300 pub type Visibility<'hir> = Spanned<VisibilityKind<'hir>>;
2302 #[derive(RustcEncodable, RustcDecodable, Debug)]
2303 pub enum VisibilityKind<'hir> {
2306 Restricted { path: &'hir Path<'hir>, hir_id: HirId },
2310 impl VisibilityKind<'_> {
2311 pub fn is_pub(&self) -> bool {
2313 VisibilityKind::Public => true,
2318 pub fn is_pub_restricted(&self) -> bool {
2320 VisibilityKind::Public | VisibilityKind::Inherited => false,
2321 VisibilityKind::Crate(..) | VisibilityKind::Restricted { .. } => true,
2325 pub fn descr(&self) -> &'static str {
2327 VisibilityKind::Public => "public",
2328 VisibilityKind::Inherited => "private",
2329 VisibilityKind::Crate(..) => "crate-visible",
2330 VisibilityKind::Restricted { .. } => "restricted",
2335 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2336 pub struct StructField<'hir> {
2338 #[stable_hasher(project(name))]
2340 pub vis: Visibility<'hir>,
2342 pub ty: &'hir Ty<'hir>,
2343 pub attrs: &'hir [Attribute],
2346 impl StructField<'_> {
2347 // Still necessary in couple of places
2348 pub fn is_positional(&self) -> bool {
2349 let first = self.ident.as_str().as_bytes()[0];
2350 first >= b'0' && first <= b'9'
2354 /// Fields and constructor IDs of enum variants and structs.
2355 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2356 pub enum VariantData<'hir> {
2357 /// A struct variant.
2359 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2360 Struct(&'hir [StructField<'hir>], /* recovered */ bool),
2361 /// A tuple variant.
2363 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2364 Tuple(&'hir [StructField<'hir>], HirId),
2367 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2371 impl VariantData<'hir> {
2372 /// Return the fields of this variant.
2373 pub fn fields(&self) -> &'hir [StructField<'hir>] {
2375 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2380 /// Return the `HirId` of this variant's constructor, if it has one.
2381 pub fn ctor_hir_id(&self) -> Option<HirId> {
2383 VariantData::Struct(_, _) => None,
2384 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2389 // The bodies for items are stored "out of line", in a separate
2390 // hashmap in the `Crate`. Here we just record the node-id of the item
2391 // so it can fetched later.
2392 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2399 /// The name might be a dummy name in case of anonymous items
2400 #[derive(RustcEncodable, RustcDecodable, Debug)]
2401 pub struct Item<'hir> {
2404 pub attrs: &'hir [Attribute],
2405 pub kind: ItemKind<'hir>,
2406 pub vis: Visibility<'hir>,
2410 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2411 #[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
2418 pub fn prefix_str(&self) -> &'static str {
2420 Self::Unsafe => "unsafe ",
2426 impl fmt::Display for Unsafety {
2427 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2428 f.write_str(match *self {
2429 Self::Unsafe => "unsafe",
2430 Self::Normal => "normal",
2435 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2436 #[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
2437 pub enum Constness {
2442 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2443 pub struct FnHeader {
2444 pub unsafety: Unsafety,
2445 pub constness: Constness,
2446 pub asyncness: IsAsync,
2451 pub fn is_const(&self) -> bool {
2452 match &self.constness {
2453 Constness::Const => true,
2459 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2460 pub enum ItemKind<'hir> {
2461 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2463 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2464 ExternCrate(Option<Name>),
2466 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2470 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2471 Use(&'hir Path<'hir>, UseKind),
2473 /// A `static` item.
2474 Static(&'hir Ty<'hir>, Mutability, BodyId),
2476 Const(&'hir Ty<'hir>, BodyId),
2477 /// A function declaration.
2478 Fn(FnSig<'hir>, Generics<'hir>, BodyId),
2481 /// An external module, e.g. `extern { .. }`.
2482 ForeignMod(ForeignMod<'hir>),
2483 /// Module-level inline assembly (from `global_asm!`).
2484 GlobalAsm(&'hir GlobalAsm),
2485 /// A type alias, e.g., `type Foo = Bar<u8>`.
2486 TyAlias(&'hir Ty<'hir>, Generics<'hir>),
2487 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2488 OpaqueTy(OpaqueTy<'hir>),
2489 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2490 Enum(EnumDef<'hir>, Generics<'hir>),
2491 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2492 Struct(VariantData<'hir>, Generics<'hir>),
2493 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2494 Union(VariantData<'hir>, Generics<'hir>),
2495 /// A trait definition.
2496 Trait(IsAuto, Unsafety, Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
2498 TraitAlias(Generics<'hir>, GenericBounds<'hir>),
2500 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2503 polarity: ImplPolarity,
2504 defaultness: Defaultness,
2505 constness: Constness,
2506 generics: Generics<'hir>,
2508 /// The trait being implemented, if any.
2509 of_trait: Option<TraitRef<'hir>>,
2511 self_ty: &'hir Ty<'hir>,
2512 items: &'hir [ImplItemRef<'hir>],
2517 pub fn descr(&self) -> &str {
2519 ItemKind::ExternCrate(..) => "extern crate",
2520 ItemKind::Use(..) => "`use` import",
2521 ItemKind::Static(..) => "static item",
2522 ItemKind::Const(..) => "constant item",
2523 ItemKind::Fn(..) => "function",
2524 ItemKind::Mod(..) => "module",
2525 ItemKind::ForeignMod(..) => "extern block",
2526 ItemKind::GlobalAsm(..) => "global asm item",
2527 ItemKind::TyAlias(..) => "type alias",
2528 ItemKind::OpaqueTy(..) => "opaque type",
2529 ItemKind::Enum(..) => "enum",
2530 ItemKind::Struct(..) => "struct",
2531 ItemKind::Union(..) => "union",
2532 ItemKind::Trait(..) => "trait",
2533 ItemKind::TraitAlias(..) => "trait alias",
2534 ItemKind::Impl { .. } => "implementation",
2538 pub fn generics(&self) -> Option<&Generics<'_>> {
2540 ItemKind::Fn(_, ref generics, _)
2541 | ItemKind::TyAlias(_, ref generics)
2542 | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
2543 | ItemKind::Enum(_, ref generics)
2544 | ItemKind::Struct(_, ref generics)
2545 | ItemKind::Union(_, ref generics)
2546 | ItemKind::Trait(_, _, ref generics, _, _)
2547 | ItemKind::Impl { ref generics, .. } => generics,
2553 /// A reference from an trait to one of its associated items. This
2554 /// contains the item's id, naturally, but also the item's name and
2555 /// some other high-level details (like whether it is an associated
2556 /// type or method, and whether it is public). This allows other
2557 /// passes to find the impl they want without loading the ID (which
2558 /// means fewer edges in the incremental compilation graph).
2559 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2560 pub struct TraitItemRef {
2561 pub id: TraitItemId,
2562 #[stable_hasher(project(name))]
2564 pub kind: AssocItemKind,
2566 pub defaultness: Defaultness,
2569 /// A reference from an impl to one of its associated items. This
2570 /// contains the item's ID, naturally, but also the item's name and
2571 /// some other high-level details (like whether it is an associated
2572 /// type or method, and whether it is public). This allows other
2573 /// passes to find the impl they want without loading the ID (which
2574 /// means fewer edges in the incremental compilation graph).
2575 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2576 pub struct ImplItemRef<'hir> {
2578 #[stable_hasher(project(name))]
2580 pub kind: AssocItemKind,
2582 pub vis: Visibility<'hir>,
2583 pub defaultness: Defaultness,
2586 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2587 pub enum AssocItemKind {
2589 Method { has_self: bool },
2594 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2595 pub struct ForeignItem<'hir> {
2596 #[stable_hasher(project(name))]
2598 pub attrs: &'hir [Attribute],
2599 pub kind: ForeignItemKind<'hir>,
2602 pub vis: Visibility<'hir>,
2605 /// An item within an `extern` block.
2606 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2607 pub enum ForeignItemKind<'hir> {
2608 /// A foreign function.
2609 Fn(&'hir FnDecl<'hir>, &'hir [Ident], Generics<'hir>),
2610 /// A foreign static item (`static ext: u8`).
2611 Static(&'hir Ty<'hir>, Mutability),
2616 impl ForeignItemKind<'hir> {
2617 pub fn descriptive_variant(&self) -> &str {
2619 ForeignItemKind::Fn(..) => "foreign function",
2620 ForeignItemKind::Static(..) => "foreign static item",
2621 ForeignItemKind::Type => "foreign type",
2626 /// A variable captured by a closure.
2627 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable, HashStable_Generic)]
2629 // First span where it is accessed (there can be multiple).
2633 pub type CaptureModeMap = NodeMap<CaptureBy>;
2635 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2636 // has length > 0 if the trait is found through an chain of imports, starting with the
2637 // import/use statement in the scope where the trait is used.
2638 #[derive(Clone, Debug)]
2639 pub struct TraitCandidate<ID = HirId> {
2641 pub import_ids: SmallVec<[ID; 1]>,
2644 impl<ID> TraitCandidate<ID> {
2645 pub fn map_import_ids<F, T>(self, f: F) -> TraitCandidate<T>
2649 let TraitCandidate { def_id, import_ids } = self;
2650 let import_ids = import_ids.into_iter().map(f).collect();
2651 TraitCandidate { def_id, import_ids }
2655 // Trait method resolution
2656 pub type TraitMap<ID = HirId> = NodeMap<Vec<TraitCandidate<ID>>>;
2658 // Map from the NodeId of a glob import to a list of items which are actually
2660 pub type GlobMap = NodeMap<FxHashSet<Name>>;
2662 #[derive(Copy, Clone, Debug, HashStable_Generic)]
2663 pub enum Node<'hir> {
2664 Param(&'hir Param<'hir>),
2665 Item(&'hir Item<'hir>),
2666 ForeignItem(&'hir ForeignItem<'hir>),
2667 TraitItem(&'hir TraitItem<'hir>),
2668 ImplItem(&'hir ImplItem<'hir>),
2669 Variant(&'hir Variant<'hir>),
2670 Field(&'hir StructField<'hir>),
2671 AnonConst(&'hir AnonConst),
2672 Expr(&'hir Expr<'hir>),
2673 Stmt(&'hir Stmt<'hir>),
2674 PathSegment(&'hir PathSegment<'hir>),
2676 TraitRef(&'hir TraitRef<'hir>),
2677 Binding(&'hir Pat<'hir>),
2678 Pat(&'hir Pat<'hir>),
2679 Arm(&'hir Arm<'hir>),
2680 Block(&'hir Block<'hir>),
2681 Local(&'hir Local<'hir>),
2682 MacroDef(&'hir MacroDef<'hir>),
2684 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
2685 /// with synthesized constructors.
2686 Ctor(&'hir VariantData<'hir>),
2688 Lifetime(&'hir Lifetime),
2689 GenericParam(&'hir GenericParam<'hir>),
2690 Visibility(&'hir Visibility<'hir>),
2692 Crate(&'hir CrateItem<'hir>),
2696 pub fn ident(&self) -> Option<Ident> {
2698 Node::TraitItem(TraitItem { ident, .. })
2699 | Node::ImplItem(ImplItem { ident, .. })
2700 | Node::ForeignItem(ForeignItem { ident, .. })
2701 | Node::Item(Item { ident, .. }) => Some(*ident),
2706 pub fn fn_decl(&self) -> Option<&FnDecl<'_>> {
2708 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
2709 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
2710 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
2711 Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
2718 pub fn generics(&self) -> Option<&Generics<'_>> {
2720 Node::TraitItem(TraitItem { generics, .. })
2721 | Node::ImplItem(ImplItem { generics, .. })
2722 | Node::Item(Item { kind: ItemKind::Fn(_, generics, _), .. }) => Some(generics),