1 use crate::def::{CtorKind, DefKind, Res};
2 use crate::def_id::{DefId, CRATE_DEF_ID};
3 crate use crate::hir_id::{HirId, ItemLocalId};
4 use crate::{itemlikevisit, LangItem};
6 use rustc_ast::util::parser::ExprPrecedence;
7 use rustc_ast::{self as ast, CrateSugar, LlvmAsmDialect};
8 use rustc_ast::{Attribute, FloatTy, IntTy, Label, LitKind, StrStyle, TraitObjectSyntax, UintTy};
9 pub use rustc_ast::{BorrowKind, ImplPolarity, IsAuto};
10 pub use rustc_ast::{CaptureBy, Movability, Mutability};
11 use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
12 use rustc_data_structures::fx::FxHashMap;
13 use rustc_data_structures::sync::{par_for_each_in, Send, Sync};
14 use rustc_index::vec::IndexVec;
15 use rustc_macros::HashStable_Generic;
16 use rustc_span::source_map::Spanned;
17 use rustc_span::symbol::{kw, sym, Ident, Symbol};
18 use rustc_span::{def_id::LocalDefId, BytePos};
19 use rustc_span::{MultiSpan, Span, DUMMY_SP};
20 use rustc_target::asm::InlineAsmRegOrRegClass;
21 use rustc_target::spec::abi::Abi;
23 use smallvec::SmallVec;
24 use std::collections::{BTreeMap, BTreeSet};
27 #[derive(Copy, Clone, Encodable, HashStable_Generic)]
32 /// Either "`'a`", referring to a named lifetime definition,
33 /// or "``" (i.e., `kw::Empty`), for elision placeholders.
35 /// HIR lowering inserts these placeholders in type paths that
36 /// refer to type definitions needing lifetime parameters,
37 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
38 pub name: LifetimeName,
41 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
42 #[derive(HashStable_Generic)]
44 /// Some user-given name like `T` or `'x`.
47 /// Synthetic name generated when user elided a lifetime in an impl header.
49 /// E.g., the lifetimes in cases like these:
52 /// impl Foo<'_> for u32
54 /// in that case, we rewrite to
56 /// impl<'f> Foo for &'f u32
57 /// impl<'f> Foo<'f> for u32
59 /// where `'f` is something like `Fresh(0)`. The indices are
60 /// unique per impl, but not necessarily continuous.
63 /// Indicates an illegal name was given and an error has been
64 /// reported (so we should squelch other derived errors). Occurs
65 /// when, e.g., `'_` is used in the wrong place.
70 pub fn ident(&self) -> Ident {
72 ParamName::Plain(ident) => ident,
73 ParamName::Fresh(_) | ParamName::Error => {
74 Ident::with_dummy_span(kw::UnderscoreLifetime)
79 pub fn normalize_to_macros_2_0(&self) -> ParamName {
81 ParamName::Plain(ident) => ParamName::Plain(ident.normalize_to_macros_2_0()),
82 param_name => param_name,
87 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
88 #[derive(HashStable_Generic)]
89 pub enum LifetimeName {
90 /// User-given names or fresh (synthetic) names.
93 /// User wrote nothing (e.g., the lifetime in `&u32`).
96 /// Implicit lifetime in a context like `dyn Foo`. This is
97 /// distinguished from implicit lifetimes elsewhere because the
98 /// lifetime that they default to must appear elsewhere within the
99 /// enclosing type. This means that, in an `impl Trait` context, we
100 /// don't have to create a parameter for them. That is, `impl
101 /// Trait<Item = &u32>` expands to an opaque type like `type
102 /// Foo<'a> = impl Trait<Item = &'a u32>`, but `impl Trait<item =
103 /// dyn Bar>` expands to `type Foo = impl Trait<Item = dyn Bar +
104 /// 'static>`. The latter uses `ImplicitObjectLifetimeDefault` so
105 /// that surrounding code knows not to create a lifetime
107 ImplicitObjectLifetimeDefault,
109 /// Indicates an error during lowering (usually `'_` in wrong place)
110 /// that was already reported.
113 /// User wrote specifies `'_`.
116 /// User wrote `'static`.
121 pub fn ident(&self) -> Ident {
123 LifetimeName::ImplicitObjectLifetimeDefault
124 | LifetimeName::Implicit
125 | LifetimeName::Error => Ident::invalid(),
126 LifetimeName::Underscore => Ident::with_dummy_span(kw::UnderscoreLifetime),
127 LifetimeName::Static => Ident::with_dummy_span(kw::StaticLifetime),
128 LifetimeName::Param(param_name) => param_name.ident(),
132 pub fn is_elided(&self) -> bool {
134 LifetimeName::ImplicitObjectLifetimeDefault
135 | LifetimeName::Implicit
136 | LifetimeName::Underscore => true,
138 // It might seem surprising that `Fresh(_)` counts as
139 // *not* elided -- but this is because, as far as the code
140 // in the compiler is concerned -- `Fresh(_)` variants act
141 // equivalently to "some fresh name". They correspond to
142 // early-bound regions on an impl, in other words.
143 LifetimeName::Error | LifetimeName::Param(_) | LifetimeName::Static => false,
147 fn is_static(&self) -> bool {
148 self == &LifetimeName::Static
151 pub fn normalize_to_macros_2_0(&self) -> LifetimeName {
153 LifetimeName::Param(param_name) => {
154 LifetimeName::Param(param_name.normalize_to_macros_2_0())
156 lifetime_name => lifetime_name,
161 impl fmt::Display for Lifetime {
162 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163 self.name.ident().fmt(f)
167 impl fmt::Debug for Lifetime {
168 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
169 write!(f, "lifetime({}: {})", self.hir_id, self.name.ident())
174 pub fn is_elided(&self) -> bool {
175 self.name.is_elided()
178 pub fn is_static(&self) -> bool {
179 self.name.is_static()
183 /// A `Path` is essentially Rust's notion of a name; for instance,
184 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
185 /// along with a bunch of supporting information.
186 #[derive(Debug, HashStable_Generic)]
187 pub struct Path<'hir> {
189 /// The resolution for the path.
191 /// The segments in the path: the things separated by `::`.
192 pub segments: &'hir [PathSegment<'hir>],
196 pub fn is_global(&self) -> bool {
197 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
201 /// A segment of a path: an identifier, an optional lifetime, and a set of
203 #[derive(Debug, HashStable_Generic)]
204 pub struct PathSegment<'hir> {
205 /// The identifier portion of this path segment.
206 #[stable_hasher(project(name))]
208 // `id` and `res` are optional. We currently only use these in save-analysis,
209 // any path segments without these will not have save-analysis info and
210 // therefore will not have 'jump to def' in IDEs, but otherwise will not be
211 // affected. (In general, we don't bother to get the defs for synthesized
212 // segments, only for segments which have come from the AST).
213 pub hir_id: Option<HirId>,
214 pub res: Option<Res>,
216 /// Type/lifetime parameters attached to this path. They come in
217 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
218 /// this is more than just simple syntactic sugar; the use of
219 /// parens affects the region binding rules, so we preserve the
221 pub args: Option<&'hir GenericArgs<'hir>>,
223 /// Whether to infer remaining type parameters, if any.
224 /// This only applies to expression and pattern paths, and
225 /// out of those only the segments with no type parameters
226 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
227 pub infer_args: bool,
230 impl<'hir> PathSegment<'hir> {
231 /// Converts an identifier to the corresponding segment.
232 pub fn from_ident(ident: Ident) -> PathSegment<'hir> {
233 PathSegment { ident, hir_id: None, res: None, infer_args: true, args: None }
236 pub fn invalid() -> Self {
237 Self::from_ident(Ident::invalid())
240 pub fn args(&self) -> &GenericArgs<'hir> {
241 if let Some(ref args) = self.args {
244 const DUMMY: &GenericArgs<'_> = &GenericArgs::none();
250 #[derive(Encodable, Debug, HashStable_Generic)]
251 pub struct ConstArg {
252 pub value: AnonConst,
256 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
264 pub fn is_type(self) -> bool {
265 matches!(self, InferKind::Type)
269 #[derive(Encodable, Debug, HashStable_Generic)]
270 pub struct InferArg {
277 pub fn to_ty(&self) -> Ty<'_> {
278 Ty { kind: TyKind::Infer, span: self.span, hir_id: self.hir_id }
282 #[derive(Debug, HashStable_Generic)]
283 pub enum GenericArg<'hir> {
290 impl GenericArg<'_> {
291 pub fn span(&self) -> Span {
293 GenericArg::Lifetime(l) => l.span,
294 GenericArg::Type(t) => t.span,
295 GenericArg::Const(c) => c.span,
296 GenericArg::Infer(i) => i.span,
300 pub fn id(&self) -> HirId {
302 GenericArg::Lifetime(l) => l.hir_id,
303 GenericArg::Type(t) => t.hir_id,
304 GenericArg::Const(c) => c.value.hir_id,
305 GenericArg::Infer(i) => i.hir_id,
309 pub fn is_const(&self) -> bool {
310 matches!(self, GenericArg::Const(_))
313 pub fn is_synthetic(&self) -> bool {
314 matches!(self, GenericArg::Lifetime(lifetime) if lifetime.name.ident() == Ident::invalid())
317 pub fn descr(&self) -> &'static str {
319 GenericArg::Lifetime(_) => "lifetime",
320 GenericArg::Type(_) => "type",
321 GenericArg::Const(_) => "constant",
322 GenericArg::Infer(_) => "inferred",
326 pub fn to_ord(&self, feats: &rustc_feature::Features) -> ast::ParamKindOrd {
328 GenericArg::Lifetime(_) => ast::ParamKindOrd::Lifetime,
329 GenericArg::Type(_) => ast::ParamKindOrd::Type,
330 GenericArg::Const(_) => {
331 ast::ParamKindOrd::Const { unordered: feats.unordered_const_ty_params() }
333 GenericArg::Infer(_) => ast::ParamKindOrd::Infer,
338 #[derive(Debug, HashStable_Generic)]
339 pub struct GenericArgs<'hir> {
340 /// The generic arguments for this path segment.
341 pub args: &'hir [GenericArg<'hir>],
342 /// Bindings (equality constraints) on associated types, if present.
343 /// E.g., `Foo<A = Bar>`.
344 pub bindings: &'hir [TypeBinding<'hir>],
345 /// Were arguments written in parenthesized form `Fn(T) -> U`?
346 /// This is required mostly for pretty-printing and diagnostics,
347 /// but also for changing lifetime elision rules to be "function-like".
348 pub parenthesized: bool,
349 /// The span encompassing arguments and the surrounding brackets `<>` or `()`
350 /// Foo<A, B, AssocTy = D> Fn(T, U, V) -> W
351 /// ^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^
352 /// Note that this may be:
353 /// - empty, if there are no generic brackets (but there may be hidden lifetimes)
354 /// - dummy, if this was generated while desugaring
358 impl GenericArgs<'_> {
359 pub const fn none() -> Self {
360 Self { args: &[], bindings: &[], parenthesized: false, span_ext: DUMMY_SP }
363 pub fn inputs(&self) -> &[Ty<'_>] {
364 if self.parenthesized {
365 for arg in self.args {
367 GenericArg::Lifetime(_) => {}
368 GenericArg::Type(ref ty) => {
369 if let TyKind::Tup(ref tys) = ty.kind {
374 GenericArg::Const(_) => {}
375 GenericArg::Infer(_) => {}
379 panic!("GenericArgs::inputs: not a `Fn(T) -> U`");
383 pub fn has_type_params(&self) -> bool {
384 self.args.iter().any(|arg| matches!(arg, GenericArg::Type(_)))
388 pub fn num_type_params(&self) -> usize {
389 self.args.iter().filter(|arg| matches!(arg, GenericArg::Type(_))).count()
393 pub fn num_lifetime_params(&self) -> usize {
394 self.args.iter().filter(|arg| matches!(arg, GenericArg::Lifetime(_))).count()
398 pub fn has_lifetime_params(&self) -> bool {
399 self.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)))
403 pub fn num_generic_params(&self) -> usize {
404 self.args.iter().filter(|arg| !matches!(arg, GenericArg::Lifetime(_))).count()
407 /// The span encompassing the text inside the surrounding brackets.
408 /// It will also include bindings if they aren't in the form `-> Ret`
409 /// Returns `None` if the span is empty (e.g. no brackets) or dummy
410 pub fn span(&self) -> Option<Span> {
411 let span_ext = self.span_ext()?;
412 Some(span_ext.with_lo(span_ext.lo() + BytePos(1)).with_hi(span_ext.hi() - BytePos(1)))
415 /// Returns span encompassing arguments and their surrounding `<>` or `()`
416 pub fn span_ext(&self) -> Option<Span> {
417 Some(self.span_ext).filter(|span| !span.is_empty())
420 pub fn is_empty(&self) -> bool {
425 /// A modifier on a bound, currently this is only used for `?Sized`, where the
426 /// modifier is `Maybe`. Negative bounds should also be handled here.
427 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
428 #[derive(HashStable_Generic)]
429 pub enum TraitBoundModifier {
435 /// The AST represents all type param bounds as types.
436 /// `typeck::collect::compute_bounds` matches these against
437 /// the "special" built-in traits (see `middle::lang_items`) and
438 /// detects `Copy`, `Send` and `Sync`.
439 #[derive(Clone, Debug, HashStable_Generic)]
440 pub enum GenericBound<'hir> {
441 Trait(PolyTraitRef<'hir>, TraitBoundModifier),
442 // FIXME(davidtwco): Introduce `PolyTraitRef::LangItem`
443 LangItemTrait(LangItem, Span, HirId, &'hir GenericArgs<'hir>),
448 impl GenericBound<'_> {
449 pub fn trait_ref(&self) -> Option<&TraitRef<'_>> {
451 GenericBound::Trait(data, _) => Some(&data.trait_ref),
456 pub fn span(&self) -> Span {
458 GenericBound::Trait(t, ..) => t.span,
459 GenericBound::LangItemTrait(_, span, ..) => *span,
460 GenericBound::Outlives(l) => l.span,
461 GenericBound::Unsized(span) => *span,
466 pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
468 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
469 pub enum LifetimeParamKind {
470 // Indicates that the lifetime definition was explicitly declared (e.g., in
471 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
474 // Indicates that the lifetime definition was synthetically added
475 // as a result of an in-band lifetime usage (e.g., in
476 // `fn foo(x: &'a u8) -> &'a u8 { x }`).
479 // Indication that the lifetime was elided (e.g., in both cases in
480 // `fn foo(x: &u8) -> &'_ u8 { x }`).
483 // Indication that the lifetime name was somehow in error.
487 #[derive(Debug, HashStable_Generic)]
488 pub enum GenericParamKind<'hir> {
489 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
491 kind: LifetimeParamKind,
494 default: Option<&'hir Ty<'hir>>,
495 synthetic: Option<SyntheticTyParamKind>,
499 /// Optional default value for the const generic param
500 default: Option<AnonConst>,
504 #[derive(Debug, HashStable_Generic)]
505 pub struct GenericParam<'hir> {
508 pub bounds: GenericBounds<'hir>,
510 pub pure_wrt_drop: bool,
511 pub kind: GenericParamKind<'hir>,
514 impl GenericParam<'hir> {
515 pub fn bounds_span(&self) -> Option<Span> {
516 self.bounds.iter().fold(None, |span, bound| {
517 let span = span.map(|s| s.to(bound.span())).unwrap_or_else(|| bound.span());
525 pub struct GenericParamCount {
526 pub lifetimes: usize,
532 /// Represents lifetimes and type parameters attached to a declaration
533 /// of a function, enum, trait, etc.
534 #[derive(Debug, HashStable_Generic)]
535 pub struct Generics<'hir> {
536 pub params: &'hir [GenericParam<'hir>],
537 pub where_clause: WhereClause<'hir>,
541 impl Generics<'hir> {
542 pub const fn empty() -> Generics<'hir> {
545 where_clause: WhereClause { predicates: &[], span: DUMMY_SP },
550 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'_>> {
551 for param in self.params {
552 if name == param.name.ident().name {
559 pub fn spans(&self) -> MultiSpan {
560 if self.params.is_empty() {
563 self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
568 /// Synthetic type parameters are converted to another form during lowering; this allows
569 /// us to track the original form they had, and is useful for error messages.
570 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
571 #[derive(HashStable_Generic)]
572 pub enum SyntheticTyParamKind {
574 // Created by the `#[rustc_synthetic]` attribute.
578 /// A where-clause in a definition.
579 #[derive(Debug, HashStable_Generic)]
580 pub struct WhereClause<'hir> {
581 pub predicates: &'hir [WherePredicate<'hir>],
582 // Only valid if predicates aren't empty.
586 impl WhereClause<'_> {
587 pub fn span(&self) -> Option<Span> {
588 if self.predicates.is_empty() { None } else { Some(self.span) }
591 /// The `WhereClause` under normal circumstances points at either the predicates or the empty
592 /// space where the `where` clause should be. Only of use for diagnostic suggestions.
593 pub fn span_for_predicates_or_empty_place(&self) -> Span {
597 /// `Span` where further predicates would be suggested, accounting for trailing commas, like
598 /// in `fn foo<T>(t: T) where T: Foo,` so we don't suggest two trailing commas.
599 pub fn tail_span_for_suggestion(&self) -> Span {
600 let end = self.span_for_predicates_or_empty_place().shrink_to_hi();
601 self.predicates.last().map_or(end, |p| p.span()).shrink_to_hi().to(end)
605 /// A single predicate in a where-clause.
606 #[derive(Debug, HashStable_Generic)]
607 pub enum WherePredicate<'hir> {
608 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
609 BoundPredicate(WhereBoundPredicate<'hir>),
610 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
611 RegionPredicate(WhereRegionPredicate<'hir>),
612 /// An equality predicate (unsupported).
613 EqPredicate(WhereEqPredicate<'hir>),
616 impl WherePredicate<'_> {
617 pub fn span(&self) -> Span {
619 WherePredicate::BoundPredicate(p) => p.span,
620 WherePredicate::RegionPredicate(p) => p.span,
621 WherePredicate::EqPredicate(p) => p.span,
626 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
627 #[derive(Debug, HashStable_Generic)]
628 pub struct WhereBoundPredicate<'hir> {
630 /// Any generics from a `for` binding.
631 pub bound_generic_params: &'hir [GenericParam<'hir>],
632 /// The type being bounded.
633 pub bounded_ty: &'hir Ty<'hir>,
634 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
635 pub bounds: GenericBounds<'hir>,
638 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
639 #[derive(Debug, HashStable_Generic)]
640 pub struct WhereRegionPredicate<'hir> {
642 pub lifetime: Lifetime,
643 pub bounds: GenericBounds<'hir>,
646 /// An equality predicate (e.g., `T = int`); currently unsupported.
647 #[derive(Debug, HashStable_Generic)]
648 pub struct WhereEqPredicate<'hir> {
651 pub lhs_ty: &'hir Ty<'hir>,
652 pub rhs_ty: &'hir Ty<'hir>,
655 #[derive(Default, Encodable, Debug, HashStable_Generic)]
656 pub struct ModuleItems {
657 // Use BTreeSets here so items are in the same order as in the
658 // list of all items in Crate
659 pub items: BTreeSet<ItemId>,
660 pub trait_items: BTreeSet<TraitItemId>,
661 pub impl_items: BTreeSet<ImplItemId>,
662 pub foreign_items: BTreeSet<ForeignItemId>,
665 /// The top-level data structure that stores the entire contents of
666 /// the crate currently being compiled.
668 /// For more details, see the [rustc dev guide].
670 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
672 pub struct Crate<'hir> {
673 // Attributes from non-exported macros, kept only for collecting the library feature list.
674 pub non_exported_macro_attrs: &'hir [Attribute],
676 pub owners: IndexVec<LocalDefId, Option<OwnerNode<'hir>>>,
677 pub bodies: BTreeMap<BodyId, Body<'hir>>,
678 pub trait_impls: BTreeMap<DefId, Vec<LocalDefId>>,
680 /// A list of the body ids written out in the order in which they
681 /// appear in the crate. If you're going to process all the bodies
682 /// in the crate, you should iterate over this list rather than the keys
684 pub body_ids: Vec<BodyId>,
686 /// A list of modules written out in the order in which they
687 /// appear in the crate. This includes the main crate module.
688 pub modules: BTreeMap<LocalDefId, ModuleItems>,
689 /// A list of proc macro HirIds, written out in the order in which
690 /// they are declared in the static array generated by proc_macro_harness.
691 pub proc_macros: Vec<HirId>,
693 /// Map indicating what traits are in scope for places where this
694 /// is relevant; generated by resolve.
695 pub trait_map: FxHashMap<LocalDefId, FxHashMap<ItemLocalId, Box<[TraitCandidate]>>>,
697 /// Collected attributes from HIR nodes.
698 pub attrs: BTreeMap<HirId, &'hir [Attribute]>,
702 pub fn module(&self) -> &'hir Mod<'hir> {
703 if let Some(OwnerNode::Crate(m)) = self.owners[CRATE_DEF_ID] { m } else { panic!() }
706 pub fn item(&self, id: ItemId) -> &'hir Item<'hir> {
707 self.owners[id.def_id].as_ref().unwrap().expect_item()
710 pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> {
711 self.owners[id.def_id].as_ref().unwrap().expect_trait_item()
714 pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> {
715 self.owners[id.def_id].as_ref().unwrap().expect_impl_item()
718 pub fn foreign_item(&self, id: ForeignItemId) -> &'hir ForeignItem<'hir> {
719 self.owners[id.def_id].as_ref().unwrap().expect_foreign_item()
722 pub fn body(&self, id: BodyId) -> &Body<'hir> {
728 /// Visits all items in the crate in some deterministic (but
729 /// unspecified) order. If you just need to process every item,
730 /// but don't care about nesting, this method is the best choice.
732 /// If you do care about nesting -- usually because your algorithm
733 /// follows lexical scoping rules -- then you want a different
734 /// approach. You should override `visit_nested_item` in your
735 /// visitor and then call `intravisit::walk_crate` instead.
736 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
738 V: itemlikevisit::ItemLikeVisitor<'hir>,
740 for owner in self.owners.iter().filter_map(Option::as_ref) {
742 OwnerNode::Item(item) => visitor.visit_item(item),
743 OwnerNode::ForeignItem(item) => visitor.visit_foreign_item(item),
744 OwnerNode::ImplItem(item) => visitor.visit_impl_item(item),
745 OwnerNode::TraitItem(item) => visitor.visit_trait_item(item),
746 OwnerNode::MacroDef(_) | OwnerNode::Crate(_) => {}
751 /// A parallel version of `visit_all_item_likes`.
752 pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
754 V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send,
756 par_for_each_in(&self.owners.raw, |owner| match owner {
757 Some(OwnerNode::Item(item)) => visitor.visit_item(item),
758 Some(OwnerNode::ForeignItem(item)) => visitor.visit_foreign_item(item),
759 Some(OwnerNode::ImplItem(item)) => visitor.visit_impl_item(item),
760 Some(OwnerNode::TraitItem(item)) => visitor.visit_trait_item(item),
761 Some(OwnerNode::MacroDef(_)) | Some(OwnerNode::Crate(_)) | None => {}
765 pub fn items<'hir>(&'hir self) -> impl Iterator<Item = &'hir Item<'hir>> + 'hir {
766 self.owners.iter().filter_map(|owner| match owner {
767 Some(OwnerNode::Item(item)) => Some(*item),
772 pub fn exported_macros<'hir>(&'hir self) -> impl Iterator<Item = &'hir MacroDef<'hir>> + 'hir {
773 self.owners.iter().filter_map(|owner| match owner {
774 Some(OwnerNode::MacroDef(macro_def)) => Some(*macro_def),
780 /// A macro definition, in this crate or imported from another.
782 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
784 pub struct MacroDef<'hir> {
786 pub vis: Visibility<'hir>,
787 pub def_id: LocalDefId,
789 pub ast: ast::MacroDef,
794 pub fn hir_id(&self) -> HirId {
795 HirId::make_owner(self.def_id)
799 /// A block of statements `{ .. }`, which may have a label (in this case the
800 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
801 /// the `rules` being anything but `DefaultBlock`.
802 #[derive(Debug, HashStable_Generic)]
803 pub struct Block<'hir> {
804 /// Statements in a block.
805 pub stmts: &'hir [Stmt<'hir>],
806 /// An expression at the end of the block
807 /// without a semicolon, if any.
808 pub expr: Option<&'hir Expr<'hir>>,
809 #[stable_hasher(ignore)]
811 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
812 pub rules: BlockCheckMode,
814 /// If true, then there may exist `break 'a` values that aim to
815 /// break out of this block early.
816 /// Used by `'label: {}` blocks and by `try {}` blocks.
817 pub targeted_by_break: bool,
820 #[derive(Debug, HashStable_Generic)]
821 pub struct Pat<'hir> {
822 #[stable_hasher(ignore)]
824 pub kind: PatKind<'hir>,
826 // Whether to use default binding modes.
827 // At present, this is false only for destructuring assignment.
828 pub default_binding_modes: bool,
831 impl<'hir> Pat<'hir> {
832 // FIXME(#19596) this is a workaround, but there should be a better way
833 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) -> bool {
840 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
841 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
842 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
843 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
844 Slice(before, slice, after) => {
845 before.iter().chain(slice).chain(after.iter()).all(|p| p.walk_short_(it))
850 /// Walk the pattern in left-to-right order,
851 /// short circuiting (with `.all(..)`) if `false` is returned.
853 /// Note that when visiting e.g. `Tuple(ps)`,
854 /// if visiting `ps[0]` returns `false`,
855 /// then `ps[1]` will not be visited.
856 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) -> bool {
857 self.walk_short_(&mut it)
860 // FIXME(#19596) this is a workaround, but there should be a better way
861 fn walk_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) {
868 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
869 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
870 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
871 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
872 Slice(before, slice, after) => {
873 before.iter().chain(slice).chain(after.iter()).for_each(|p| p.walk_(it))
878 /// Walk the pattern in left-to-right order.
880 /// If `it(pat)` returns `false`, the children are not visited.
881 pub fn walk(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) {
885 /// Walk the pattern in left-to-right order.
887 /// If you always want to recurse, prefer this method over `walk`.
888 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
896 /// A single field in a struct pattern.
898 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
899 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
900 /// except `is_shorthand` is true.
901 #[derive(Debug, HashStable_Generic)]
902 pub struct PatField<'hir> {
903 #[stable_hasher(ignore)]
905 /// The identifier for the field.
906 #[stable_hasher(project(name))]
908 /// The pattern the field is destructured to.
909 pub pat: &'hir Pat<'hir>,
910 pub is_shorthand: bool,
914 /// Explicit binding annotations given in the HIR for a binding. Note
915 /// that this is not the final binding *mode* that we infer after type
917 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
918 pub enum BindingAnnotation {
919 /// No binding annotation given: this means that the final binding mode
920 /// will depend on whether we have skipped through a `&` reference
921 /// when matching. For example, the `x` in `Some(x)` will have binding
922 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
923 /// ultimately be inferred to be by-reference.
925 /// Note that implicit reference skipping is not implemented yet (#42640).
928 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
931 /// Annotated as `ref`, like `ref x`
934 /// Annotated as `ref mut x`.
938 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
944 impl fmt::Display for RangeEnd {
945 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
946 f.write_str(match self {
947 RangeEnd::Included => "..=",
948 RangeEnd::Excluded => "..",
953 #[derive(Debug, HashStable_Generic)]
954 pub enum PatKind<'hir> {
955 /// Represents a wildcard pattern (i.e., `_`).
958 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
959 /// The `HirId` is the canonical ID for the variable being bound,
960 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
961 /// which is the pattern ID of the first `x`.
962 Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
964 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
965 /// The `bool` is `true` in the presence of a `..`.
966 Struct(QPath<'hir>, &'hir [PatField<'hir>], bool),
968 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
969 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
970 /// `0 <= position <= subpats.len()`
971 TupleStruct(QPath<'hir>, &'hir [Pat<'hir>], Option<usize>),
973 /// An or-pattern `A | B | C`.
974 /// Invariant: `pats.len() >= 2`.
975 Or(&'hir [Pat<'hir>]),
977 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
980 /// A tuple pattern (e.g., `(a, b)`).
981 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
982 /// `0 <= position <= subpats.len()`
983 Tuple(&'hir [Pat<'hir>], Option<usize>),
986 Box(&'hir Pat<'hir>),
988 /// A reference pattern (e.g., `&mut (a, b)`).
989 Ref(&'hir Pat<'hir>, Mutability),
992 Lit(&'hir Expr<'hir>),
994 /// A range pattern (e.g., `1..=2` or `1..2`).
995 Range(Option<&'hir Expr<'hir>>, Option<&'hir Expr<'hir>>, RangeEnd),
997 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
999 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
1000 /// If `slice` exists, then `after` can be non-empty.
1002 /// The representation for e.g., `[a, b, .., c, d]` is:
1004 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
1006 Slice(&'hir [Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [Pat<'hir>]),
1009 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1010 pub enum BinOpKind {
1011 /// The `+` operator (addition).
1013 /// The `-` operator (subtraction).
1015 /// The `*` operator (multiplication).
1017 /// The `/` operator (division).
1019 /// The `%` operator (modulus).
1021 /// The `&&` operator (logical and).
1023 /// The `||` operator (logical or).
1025 /// The `^` operator (bitwise xor).
1027 /// The `&` operator (bitwise and).
1029 /// The `|` operator (bitwise or).
1031 /// The `<<` operator (shift left).
1033 /// The `>>` operator (shift right).
1035 /// The `==` operator (equality).
1037 /// The `<` operator (less than).
1039 /// The `<=` operator (less than or equal to).
1041 /// The `!=` operator (not equal to).
1043 /// The `>=` operator (greater than or equal to).
1045 /// The `>` operator (greater than).
1050 pub fn as_str(self) -> &'static str {
1052 BinOpKind::Add => "+",
1053 BinOpKind::Sub => "-",
1054 BinOpKind::Mul => "*",
1055 BinOpKind::Div => "/",
1056 BinOpKind::Rem => "%",
1057 BinOpKind::And => "&&",
1058 BinOpKind::Or => "||",
1059 BinOpKind::BitXor => "^",
1060 BinOpKind::BitAnd => "&",
1061 BinOpKind::BitOr => "|",
1062 BinOpKind::Shl => "<<",
1063 BinOpKind::Shr => ">>",
1064 BinOpKind::Eq => "==",
1065 BinOpKind::Lt => "<",
1066 BinOpKind::Le => "<=",
1067 BinOpKind::Ne => "!=",
1068 BinOpKind::Ge => ">=",
1069 BinOpKind::Gt => ">",
1073 pub fn is_lazy(self) -> bool {
1074 matches!(self, BinOpKind::And | BinOpKind::Or)
1077 pub fn is_shift(self) -> bool {
1078 matches!(self, BinOpKind::Shl | BinOpKind::Shr)
1081 pub fn is_comparison(self) -> bool {
1088 | BinOpKind::Ge => true,
1100 | BinOpKind::Shr => false,
1104 /// Returns `true` if the binary operator takes its arguments by value.
1105 pub fn is_by_value(self) -> bool {
1106 !self.is_comparison()
1110 impl Into<ast::BinOpKind> for BinOpKind {
1111 fn into(self) -> ast::BinOpKind {
1113 BinOpKind::Add => ast::BinOpKind::Add,
1114 BinOpKind::Sub => ast::BinOpKind::Sub,
1115 BinOpKind::Mul => ast::BinOpKind::Mul,
1116 BinOpKind::Div => ast::BinOpKind::Div,
1117 BinOpKind::Rem => ast::BinOpKind::Rem,
1118 BinOpKind::And => ast::BinOpKind::And,
1119 BinOpKind::Or => ast::BinOpKind::Or,
1120 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1121 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1122 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1123 BinOpKind::Shl => ast::BinOpKind::Shl,
1124 BinOpKind::Shr => ast::BinOpKind::Shr,
1125 BinOpKind::Eq => ast::BinOpKind::Eq,
1126 BinOpKind::Lt => ast::BinOpKind::Lt,
1127 BinOpKind::Le => ast::BinOpKind::Le,
1128 BinOpKind::Ne => ast::BinOpKind::Ne,
1129 BinOpKind::Ge => ast::BinOpKind::Ge,
1130 BinOpKind::Gt => ast::BinOpKind::Gt,
1135 pub type BinOp = Spanned<BinOpKind>;
1137 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1139 /// The `*` operator (deferencing).
1141 /// The `!` operator (logical negation).
1143 /// The `-` operator (negation).
1148 pub fn as_str(self) -> &'static str {
1156 /// Returns `true` if the unary operator takes its argument by value.
1157 pub fn is_by_value(self) -> bool {
1158 matches!(self, Self::Neg | Self::Not)
1163 #[derive(Debug, HashStable_Generic)]
1164 pub struct Stmt<'hir> {
1166 pub kind: StmtKind<'hir>,
1170 /// The contents of a statement.
1171 #[derive(Debug, HashStable_Generic)]
1172 pub enum StmtKind<'hir> {
1173 /// A local (`let`) binding.
1174 Local(&'hir Local<'hir>),
1176 /// An item binding.
1179 /// An expression without a trailing semi-colon (must have unit type).
1180 Expr(&'hir Expr<'hir>),
1182 /// An expression with a trailing semi-colon (may have any type).
1183 Semi(&'hir Expr<'hir>),
1186 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1187 #[derive(Debug, HashStable_Generic)]
1188 pub struct Local<'hir> {
1189 pub pat: &'hir Pat<'hir>,
1190 /// Type annotation, if any (otherwise the type will be inferred).
1191 pub ty: Option<&'hir Ty<'hir>>,
1192 /// Initializer expression to set the value, if any.
1193 pub init: Option<&'hir Expr<'hir>>,
1196 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1197 /// desugaring. Otherwise will be `Normal`.
1198 pub source: LocalSource,
1201 /// Represents a single arm of a `match` expression, e.g.
1202 /// `<pat> (if <guard>) => <body>`.
1203 #[derive(Debug, HashStable_Generic)]
1204 pub struct Arm<'hir> {
1205 #[stable_hasher(ignore)]
1208 /// If this pattern and the optional guard matches, then `body` is evaluated.
1209 pub pat: &'hir Pat<'hir>,
1210 /// Optional guard clause.
1211 pub guard: Option<Guard<'hir>>,
1212 /// The expression the arm evaluates to if this arm matches.
1213 pub body: &'hir Expr<'hir>,
1216 #[derive(Debug, HashStable_Generic)]
1217 pub enum Guard<'hir> {
1218 If(&'hir Expr<'hir>),
1219 IfLet(&'hir Pat<'hir>, &'hir Expr<'hir>),
1222 #[derive(Debug, HashStable_Generic)]
1223 pub struct ExprField<'hir> {
1224 #[stable_hasher(ignore)]
1227 pub expr: &'hir Expr<'hir>,
1229 pub is_shorthand: bool,
1232 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1233 pub enum BlockCheckMode {
1235 UnsafeBlock(UnsafeSource),
1238 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1239 pub enum UnsafeSource {
1244 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Hash, Debug)]
1249 /// The body of a function, closure, or constant value. In the case of
1250 /// a function, the body contains not only the function body itself
1251 /// (which is an expression), but also the argument patterns, since
1252 /// those are something that the caller doesn't really care about.
1257 /// fn foo((x, y): (u32, u32)) -> u32 {
1262 /// Here, the `Body` associated with `foo()` would contain:
1264 /// - an `params` array containing the `(x, y)` pattern
1265 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1266 /// - `generator_kind` would be `None`
1268 /// All bodies have an **owner**, which can be accessed via the HIR
1269 /// map using `body_owner_def_id()`.
1271 pub struct Body<'hir> {
1272 pub params: &'hir [Param<'hir>],
1273 pub value: Expr<'hir>,
1274 pub generator_kind: Option<GeneratorKind>,
1278 pub fn id(&self) -> BodyId {
1279 BodyId { hir_id: self.value.hir_id }
1282 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1287 /// The type of source expression that caused this generator to be created.
1300 pub enum GeneratorKind {
1301 /// An explicit `async` block or the body of an async function.
1302 Async(AsyncGeneratorKind),
1304 /// A generator literal created via a `yield` inside a closure.
1308 impl fmt::Display for GeneratorKind {
1309 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1311 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1312 GeneratorKind::Gen => f.write_str("generator"),
1317 impl GeneratorKind {
1318 pub fn descr(&self) -> &'static str {
1320 GeneratorKind::Async(ask) => ask.descr(),
1321 GeneratorKind::Gen => "generator",
1326 /// In the case of a generator created as part of an async construct,
1327 /// which kind of async construct caused it to be created?
1329 /// This helps error messages but is also used to drive coercions in
1330 /// type-checking (see #60424).
1343 pub enum AsyncGeneratorKind {
1344 /// An explicit `async` block written by the user.
1347 /// An explicit `async` block written by the user.
1350 /// The `async` block generated as the body of an async function.
1354 impl fmt::Display for AsyncGeneratorKind {
1355 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1356 f.write_str(match self {
1357 AsyncGeneratorKind::Block => "`async` block",
1358 AsyncGeneratorKind::Closure => "`async` closure body",
1359 AsyncGeneratorKind::Fn => "`async fn` body",
1364 impl AsyncGeneratorKind {
1365 pub fn descr(&self) -> &'static str {
1367 AsyncGeneratorKind::Block => "`async` block",
1368 AsyncGeneratorKind::Closure => "`async` closure body",
1369 AsyncGeneratorKind::Fn => "`async fn` body",
1374 #[derive(Copy, Clone, Debug)]
1375 pub enum BodyOwnerKind {
1376 /// Functions and methods.
1382 /// Constants and associated constants.
1385 /// Initializer of a `static` item.
1389 impl BodyOwnerKind {
1390 pub fn is_fn_or_closure(self) -> bool {
1392 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1393 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1398 /// The kind of an item that requires const-checking.
1399 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1400 pub enum ConstContext {
1404 /// A `static` or `static mut`.
1407 /// A `const`, associated `const`, or other const context.
1409 /// Other contexts include:
1410 /// - Array length expressions
1411 /// - Enum discriminants
1412 /// - Const generics
1414 /// For the most part, other contexts are treated just like a regular `const`, so they are
1415 /// lumped into the same category.
1420 /// A description of this const context that can appear between backticks in an error message.
1422 /// E.g. `const` or `static mut`.
1423 pub fn keyword_name(self) -> &'static str {
1425 Self::Const => "const",
1426 Self::Static(Mutability::Not) => "static",
1427 Self::Static(Mutability::Mut) => "static mut",
1428 Self::ConstFn => "const fn",
1433 /// A colloquial, trivially pluralizable description of this const context for use in error
1435 impl fmt::Display for ConstContext {
1436 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1438 Self::Const => write!(f, "constant"),
1439 Self::Static(_) => write!(f, "static"),
1440 Self::ConstFn => write!(f, "constant function"),
1446 pub type Lit = Spanned<LitKind>;
1448 /// A constant (expression) that's not an item or associated item,
1449 /// but needs its own `DefId` for type-checking, const-eval, etc.
1450 /// These are usually found nested inside types (e.g., array lengths)
1451 /// or expressions (e.g., repeat counts), and also used to define
1452 /// explicit discriminant values for enum variants.
1454 /// You can check if this anon const is a default in a const param
1455 /// `const N: usize = { ... }` with `tcx.hir().opt_const_param_default_param_hir_id(..)`
1456 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1457 pub struct AnonConst {
1464 pub struct Expr<'hir> {
1466 pub kind: ExprKind<'hir>,
1471 pub fn precedence(&self) -> ExprPrecedence {
1473 ExprKind::Box(_) => ExprPrecedence::Box,
1474 ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1475 ExprKind::Array(_) => ExprPrecedence::Array,
1476 ExprKind::Call(..) => ExprPrecedence::Call,
1477 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1478 ExprKind::Tup(_) => ExprPrecedence::Tup,
1479 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1480 ExprKind::Unary(..) => ExprPrecedence::Unary,
1481 ExprKind::Lit(_) => ExprPrecedence::Lit,
1482 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1483 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1484 ExprKind::If(..) => ExprPrecedence::If,
1485 ExprKind::Let(..) => ExprPrecedence::Let,
1486 ExprKind::Loop(..) => ExprPrecedence::Loop,
1487 ExprKind::Match(..) => ExprPrecedence::Match,
1488 ExprKind::Closure(..) => ExprPrecedence::Closure,
1489 ExprKind::Block(..) => ExprPrecedence::Block,
1490 ExprKind::Assign(..) => ExprPrecedence::Assign,
1491 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1492 ExprKind::Field(..) => ExprPrecedence::Field,
1493 ExprKind::Index(..) => ExprPrecedence::Index,
1494 ExprKind::Path(..) => ExprPrecedence::Path,
1495 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1496 ExprKind::Break(..) => ExprPrecedence::Break,
1497 ExprKind::Continue(..) => ExprPrecedence::Continue,
1498 ExprKind::Ret(..) => ExprPrecedence::Ret,
1499 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1500 ExprKind::LlvmInlineAsm(..) => ExprPrecedence::InlineAsm,
1501 ExprKind::Struct(..) => ExprPrecedence::Struct,
1502 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1503 ExprKind::Yield(..) => ExprPrecedence::Yield,
1504 ExprKind::Err => ExprPrecedence::Err,
1508 // Whether this looks like a place expr, without checking for deref
1510 // This will return `true` in some potentially surprising cases such as
1511 // `CONSTANT.field`.
1512 pub fn is_syntactic_place_expr(&self) -> bool {
1513 self.is_place_expr(|_| true)
1516 /// Whether this is a place expression.
1518 /// `allow_projections_from` should return `true` if indexing a field or index expression based
1519 /// on the given expression should be considered a place expression.
1520 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1522 ExprKind::Path(QPath::Resolved(_, ref path)) => {
1523 matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static, _) | Res::Err)
1526 // Type ascription inherits its place expression kind from its
1528 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1529 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1531 ExprKind::Unary(UnOp::Deref, _) => true,
1533 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1534 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1537 // Lang item paths cannot currently be local variables or statics.
1538 ExprKind::Path(QPath::LangItem(..)) => false,
1540 // Partially qualified paths in expressions can only legally
1541 // refer to associated items which are always rvalues.
1542 ExprKind::Path(QPath::TypeRelative(..))
1543 | ExprKind::Call(..)
1544 | ExprKind::MethodCall(..)
1545 | ExprKind::Struct(..)
1548 | ExprKind::Match(..)
1549 | ExprKind::Closure(..)
1550 | ExprKind::Block(..)
1551 | ExprKind::Repeat(..)
1552 | ExprKind::Array(..)
1553 | ExprKind::Break(..)
1554 | ExprKind::Continue(..)
1557 | ExprKind::Loop(..)
1558 | ExprKind::Assign(..)
1559 | ExprKind::InlineAsm(..)
1560 | ExprKind::LlvmInlineAsm(..)
1561 | ExprKind::AssignOp(..)
1563 | ExprKind::ConstBlock(..)
1564 | ExprKind::Unary(..)
1566 | ExprKind::AddrOf(..)
1567 | ExprKind::Binary(..)
1568 | ExprKind::Yield(..)
1569 | ExprKind::Cast(..)
1570 | ExprKind::DropTemps(..)
1571 | ExprKind::Err => false,
1575 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1576 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1577 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1578 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1579 /// beyond remembering to call this function before doing analysis on it.
1580 pub fn peel_drop_temps(&self) -> &Self {
1581 let mut expr = self;
1582 while let ExprKind::DropTemps(inner) = &expr.kind {
1588 pub fn peel_blocks(&self) -> &Self {
1589 let mut expr = self;
1590 while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind {
1596 pub fn can_have_side_effects(&self) -> bool {
1597 match self.peel_drop_temps().kind {
1598 ExprKind::Path(_) | ExprKind::Lit(_) => false,
1599 ExprKind::Type(base, _)
1600 | ExprKind::Unary(_, base)
1601 | ExprKind::Field(base, _)
1602 | ExprKind::Index(base, _)
1603 | ExprKind::AddrOf(.., base)
1604 | ExprKind::Cast(base, _) => {
1605 // This isn't exactly true for `Index` and all `Unnary`, but we are using this
1606 // method exclusively for diagnostics and there's a *cultural* pressure against
1607 // them being used only for its side-effects.
1608 base.can_have_side_effects()
1610 ExprKind::Struct(_, fields, init) => fields
1612 .map(|field| field.expr)
1613 .chain(init.into_iter())
1614 .all(|e| e.can_have_side_effects()),
1616 ExprKind::Array(args)
1617 | ExprKind::Tup(args)
1621 ExprKind::Path(QPath::Resolved(
1623 Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. },
1628 ) => args.iter().all(|arg| arg.can_have_side_effects()),
1630 | ExprKind::Match(..)
1631 | ExprKind::MethodCall(..)
1632 | ExprKind::Call(..)
1633 | ExprKind::Closure(..)
1634 | ExprKind::Block(..)
1635 | ExprKind::Repeat(..)
1636 | ExprKind::Break(..)
1637 | ExprKind::Continue(..)
1640 | ExprKind::Loop(..)
1641 | ExprKind::Assign(..)
1642 | ExprKind::InlineAsm(..)
1643 | ExprKind::LlvmInlineAsm(..)
1644 | ExprKind::AssignOp(..)
1645 | ExprKind::ConstBlock(..)
1647 | ExprKind::Binary(..)
1648 | ExprKind::Yield(..)
1649 | ExprKind::DropTemps(..)
1650 | ExprKind::Err => true,
1655 /// Checks if the specified expression is a built-in range literal.
1656 /// (See: `LoweringContext::lower_expr()`).
1657 pub fn is_range_literal(expr: &Expr<'_>) -> bool {
1659 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1660 ExprKind::Struct(ref qpath, _, _) => matches!(
1665 | LangItem::RangeFrom
1666 | LangItem::RangeFull
1667 | LangItem::RangeToInclusive,
1672 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1673 ExprKind::Call(ref func, _) => {
1674 matches!(func.kind, ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, _)))
1681 #[derive(Debug, HashStable_Generic)]
1682 pub enum ExprKind<'hir> {
1683 /// A `box x` expression.
1684 Box(&'hir Expr<'hir>),
1685 /// Allow anonymous constants from an inline `const` block
1686 ConstBlock(AnonConst),
1687 /// An array (e.g., `[a, b, c, d]`).
1688 Array(&'hir [Expr<'hir>]),
1689 /// A function call.
1691 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1692 /// and the second field is the list of arguments.
1693 /// This also represents calling the constructor of
1694 /// tuple-like ADTs such as tuple structs and enum variants.
1695 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1696 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1698 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1699 /// (within the angle brackets).
1700 /// The first element of the vector of `Expr`s is the expression that evaluates
1701 /// to the object on which the method is being called on (the receiver),
1702 /// and the remaining elements are the rest of the arguments.
1703 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1704 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1705 /// The final `Span` represents the span of the function and arguments
1706 /// (e.g. `foo::<Bar, Baz>(a, b, c, d)` in `x.foo::<Bar, Baz>(a, b, c, d)`
1708 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1709 /// the `hir_id` of the `MethodCall` node itself.
1711 /// [`type_dependent_def_id`]: ../ty/struct.TypeckResults.html#method.type_dependent_def_id
1712 MethodCall(&'hir PathSegment<'hir>, Span, &'hir [Expr<'hir>], Span),
1713 /// A tuple (e.g., `(a, b, c, d)`).
1714 Tup(&'hir [Expr<'hir>]),
1715 /// A binary operation (e.g., `a + b`, `a * b`).
1716 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1717 /// A unary operation (e.g., `!x`, `*x`).
1718 Unary(UnOp, &'hir Expr<'hir>),
1719 /// A literal (e.g., `1`, `"foo"`).
1721 /// A cast (e.g., `foo as f64`).
1722 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1723 /// A type reference (e.g., `Foo`).
1724 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1725 /// Wraps the expression in a terminating scope.
1726 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1728 /// This construct only exists to tweak the drop order in HIR lowering.
1729 /// An example of that is the desugaring of `for` loops.
1730 DropTemps(&'hir Expr<'hir>),
1731 /// A `let $pat = $expr` expression.
1733 /// These are not `Local` and only occur as expressions.
1734 /// The `let Some(x) = foo()` in `if let Some(x) = foo()` is an example of `Let(..)`.
1735 Let(&'hir Pat<'hir>, &'hir Expr<'hir>, Span),
1736 /// An `if` block, with an optional else block.
1738 /// I.e., `if <expr> { <expr> } else { <expr> }`.
1739 If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
1740 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1742 /// I.e., `'label: loop { <block> }`.
1744 /// The `Span` is the loop header (`for x in y`/`while let pat = expr`).
1745 Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span),
1746 /// A `match` block, with a source that indicates whether or not it is
1747 /// the result of a desugaring, and if so, which kind.
1748 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1749 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1751 /// The `Span` is the argument block `|...|`.
1753 /// This may also be a generator literal or an `async block` as indicated by the
1754 /// `Option<Movability>`.
1755 Closure(CaptureBy, &'hir FnDecl<'hir>, BodyId, Span, Option<Movability>),
1756 /// A block (e.g., `'label: { ... }`).
1757 Block(&'hir Block<'hir>, Option<Label>),
1759 /// An assignment (e.g., `a = foo()`).
1760 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1761 /// An assignment with an operator.
1764 AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1765 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1766 Field(&'hir Expr<'hir>, Ident),
1767 /// An indexing operation (`foo[2]`).
1768 Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1770 /// Path to a definition, possibly containing lifetime or type parameters.
1773 /// A referencing operation (i.e., `&a` or `&mut a`).
1774 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1775 /// A `break`, with an optional label to break.
1776 Break(Destination, Option<&'hir Expr<'hir>>),
1777 /// A `continue`, with an optional label.
1778 Continue(Destination),
1779 /// A `return`, with an optional value to be returned.
1780 Ret(Option<&'hir Expr<'hir>>),
1782 /// Inline assembly (from `asm!`), with its outputs and inputs.
1783 InlineAsm(&'hir InlineAsm<'hir>),
1784 /// Inline assembly (from `llvm_asm!`), with its outputs and inputs.
1785 LlvmInlineAsm(&'hir LlvmInlineAsm<'hir>),
1787 /// A struct or struct-like variant literal expression.
1789 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1790 /// where `base` is the `Option<Expr>`.
1791 Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], Option<&'hir Expr<'hir>>),
1793 /// An array literal constructed from one repeated element.
1795 /// E.g., `[1; 5]`. The first expression is the element
1796 /// to be repeated; the second is the number of times to repeat it.
1797 Repeat(&'hir Expr<'hir>, AnonConst),
1799 /// A suspension point for generators (i.e., `yield <expr>`).
1800 Yield(&'hir Expr<'hir>, YieldSource),
1802 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1806 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1808 /// To resolve the path to a `DefId`, call [`qpath_res`].
1810 /// [`qpath_res`]: ../rustc_middle/ty/struct.TypeckResults.html#method.qpath_res
1811 #[derive(Debug, HashStable_Generic)]
1812 pub enum QPath<'hir> {
1813 /// Path to a definition, optionally "fully-qualified" with a `Self`
1814 /// type, if the path points to an associated item in a trait.
1816 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1817 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1818 /// even though they both have the same two-segment `Clone::clone` `Path`.
1819 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
1821 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1822 /// Will be resolved by type-checking to an associated item.
1824 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1825 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1826 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1827 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
1829 /// Reference to a `#[lang = "foo"]` item.
1830 LangItem(LangItem, Span),
1833 impl<'hir> QPath<'hir> {
1834 /// Returns the span of this `QPath`.
1835 pub fn span(&self) -> Span {
1837 QPath::Resolved(_, path) => path.span,
1838 QPath::TypeRelative(qself, ps) => qself.span.to(ps.ident.span),
1839 QPath::LangItem(_, span) => span,
1843 /// Returns the span of the qself of this `QPath`. For example, `()` in
1844 /// `<() as Trait>::method`.
1845 pub fn qself_span(&self) -> Span {
1847 QPath::Resolved(_, path) => path.span,
1848 QPath::TypeRelative(qself, _) => qself.span,
1849 QPath::LangItem(_, span) => span,
1853 /// Returns the span of the last segment of this `QPath`. For example, `method` in
1854 /// `<() as Trait>::method`.
1855 pub fn last_segment_span(&self) -> Span {
1857 QPath::Resolved(_, path) => path.segments.last().unwrap().ident.span,
1858 QPath::TypeRelative(_, segment) => segment.ident.span,
1859 QPath::LangItem(_, span) => span,
1864 /// Hints at the original code for a let statement.
1865 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1866 pub enum LocalSource {
1867 /// A `match _ { .. }`.
1869 /// A desugared `for _ in _ { .. }` loop.
1871 /// When lowering async functions, we create locals within the `async move` so that
1872 /// all parameters are dropped after the future is polled.
1874 /// ```ignore (pseudo-Rust)
1875 /// async fn foo(<pattern> @ x: Type) {
1877 /// let <pattern> = x;
1882 /// A desugared `<expr>.await`.
1884 /// A desugared `expr = expr`, where the LHS is a tuple, struct or array.
1885 /// The span is that of the `=` sign.
1886 AssignDesugar(Span),
1889 /// Hints at the original code for a `match _ { .. }`.
1890 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
1891 #[derive(HashStable_Generic)]
1892 pub enum MatchSource {
1893 /// A `match _ { .. }`.
1895 /// A desugared `for _ in _ { .. }` loop.
1897 /// A desugared `?` operator.
1899 /// A desugared `<expr>.await`.
1905 pub const fn name(self) -> &'static str {
1909 ForLoopDesugar => "for",
1911 AwaitDesugar => ".await",
1916 /// The loop type that yielded an `ExprKind::Loop`.
1917 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1918 pub enum LoopSource {
1919 /// A `loop { .. }` loop.
1921 /// A `while _ { .. }` loop.
1923 /// A `for _ in _ { .. }` loop.
1928 pub fn name(self) -> &'static str {
1930 LoopSource::Loop => "loop",
1931 LoopSource::While => "while",
1932 LoopSource::ForLoop => "for",
1937 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1938 pub enum LoopIdError {
1940 UnlabeledCfInWhileCondition,
1944 impl fmt::Display for LoopIdError {
1945 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1946 f.write_str(match self {
1947 LoopIdError::OutsideLoopScope => "not inside loop scope",
1948 LoopIdError::UnlabeledCfInWhileCondition => {
1949 "unlabeled control flow (break or continue) in while condition"
1951 LoopIdError::UnresolvedLabel => "label not found",
1956 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1957 pub struct Destination {
1958 // This is `Some(_)` iff there is an explicit user-specified `label
1959 pub label: Option<Label>,
1961 // These errors are caught and then reported during the diagnostics pass in
1962 // librustc_passes/loops.rs
1963 pub target_id: Result<HirId, LoopIdError>,
1966 /// The yield kind that caused an `ExprKind::Yield`.
1967 #[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
1968 pub enum YieldSource {
1969 /// An `<expr>.await`.
1970 Await { expr: Option<HirId> },
1971 /// A plain `yield`.
1976 pub fn is_await(&self) -> bool {
1978 YieldSource::Await { .. } => true,
1979 YieldSource::Yield => false,
1984 impl fmt::Display for YieldSource {
1985 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1986 f.write_str(match self {
1987 YieldSource::Await { .. } => "`await`",
1988 YieldSource::Yield => "`yield`",
1993 impl From<GeneratorKind> for YieldSource {
1994 fn from(kind: GeneratorKind) -> Self {
1996 // Guess based on the kind of the current generator.
1997 GeneratorKind::Gen => Self::Yield,
1998 GeneratorKind::Async(_) => Self::Await { expr: None },
2003 // N.B., if you change this, you'll probably want to change the corresponding
2004 // type structure in middle/ty.rs as well.
2005 #[derive(Debug, HashStable_Generic)]
2006 pub struct MutTy<'hir> {
2007 pub ty: &'hir Ty<'hir>,
2008 pub mutbl: Mutability,
2011 /// Represents a function's signature in a trait declaration,
2012 /// trait implementation, or a free function.
2013 #[derive(Debug, HashStable_Generic)]
2014 pub struct FnSig<'hir> {
2015 pub header: FnHeader,
2016 pub decl: &'hir FnDecl<'hir>,
2020 // The bodies for items are stored "out of line", in a separate
2021 // hashmap in the `Crate`. Here we just record the hir-id of the item
2022 // so it can fetched later.
2023 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
2024 pub struct TraitItemId {
2025 pub def_id: LocalDefId,
2030 pub fn hir_id(&self) -> HirId {
2031 // Items are always HIR owners.
2032 HirId::make_owner(self.def_id)
2036 /// Represents an item declaration within a trait declaration,
2037 /// possibly including a default implementation. A trait item is
2038 /// either required (meaning it doesn't have an implementation, just a
2039 /// signature) or provided (meaning it has a default implementation).
2041 pub struct TraitItem<'hir> {
2043 pub def_id: LocalDefId,
2044 pub generics: Generics<'hir>,
2045 pub kind: TraitItemKind<'hir>,
2049 impl TraitItem<'_> {
2051 pub fn hir_id(&self) -> HirId {
2052 // Items are always HIR owners.
2053 HirId::make_owner(self.def_id)
2056 pub fn trait_item_id(&self) -> TraitItemId {
2057 TraitItemId { def_id: self.def_id }
2061 /// Represents a trait method's body (or just argument names).
2062 #[derive(Encodable, Debug, HashStable_Generic)]
2063 pub enum TraitFn<'hir> {
2064 /// No default body in the trait, just a signature.
2065 Required(&'hir [Ident]),
2067 /// Both signature and body are provided in the trait.
2071 /// Represents a trait method or associated constant or type
2072 #[derive(Debug, HashStable_Generic)]
2073 pub enum TraitItemKind<'hir> {
2074 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
2075 Const(&'hir Ty<'hir>, Option<BodyId>),
2076 /// An associated function with an optional body.
2077 Fn(FnSig<'hir>, TraitFn<'hir>),
2078 /// An associated type with (possibly empty) bounds and optional concrete
2080 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
2083 // The bodies for items are stored "out of line", in a separate
2084 // hashmap in the `Crate`. Here we just record the hir-id of the item
2085 // so it can fetched later.
2086 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
2087 pub struct ImplItemId {
2088 pub def_id: LocalDefId,
2093 pub fn hir_id(&self) -> HirId {
2094 // Items are always HIR owners.
2095 HirId::make_owner(self.def_id)
2099 /// Represents anything within an `impl` block.
2101 pub struct ImplItem<'hir> {
2103 pub def_id: LocalDefId,
2104 pub vis: Visibility<'hir>,
2105 pub defaultness: Defaultness,
2106 pub generics: Generics<'hir>,
2107 pub kind: ImplItemKind<'hir>,
2113 pub fn hir_id(&self) -> HirId {
2114 // Items are always HIR owners.
2115 HirId::make_owner(self.def_id)
2118 pub fn impl_item_id(&self) -> ImplItemId {
2119 ImplItemId { def_id: self.def_id }
2123 /// Represents various kinds of content within an `impl`.
2124 #[derive(Debug, HashStable_Generic)]
2125 pub enum ImplItemKind<'hir> {
2126 /// An associated constant of the given type, set to the constant result
2127 /// of the expression.
2128 Const(&'hir Ty<'hir>, BodyId),
2129 /// An associated function implementation with the given signature and body.
2130 Fn(FnSig<'hir>, BodyId),
2131 /// An associated type.
2132 TyAlias(&'hir Ty<'hir>),
2135 // The name of the associated type for `Fn` return types.
2136 pub const FN_OUTPUT_NAME: Symbol = sym::Output;
2138 /// Bind a type to an associated type (i.e., `A = Foo`).
2140 /// Bindings like `A: Debug` are represented as a special type `A =
2141 /// $::Debug` that is understood by the astconv code.
2143 /// FIXME(alexreg): why have a separate type for the binding case,
2144 /// wouldn't it be better to make the `ty` field an enum like the
2148 /// enum TypeBindingKind {
2153 #[derive(Debug, HashStable_Generic)]
2154 pub struct TypeBinding<'hir> {
2156 #[stable_hasher(project(name))]
2158 pub gen_args: &'hir GenericArgs<'hir>,
2159 pub kind: TypeBindingKind<'hir>,
2163 // Represents the two kinds of type bindings.
2164 #[derive(Debug, HashStable_Generic)]
2165 pub enum TypeBindingKind<'hir> {
2166 /// E.g., `Foo<Bar: Send>`.
2167 Constraint { bounds: &'hir [GenericBound<'hir>] },
2168 /// E.g., `Foo<Bar = ()>`.
2169 Equality { ty: &'hir Ty<'hir> },
2172 impl TypeBinding<'_> {
2173 pub fn ty(&self) -> &Ty<'_> {
2175 TypeBindingKind::Equality { ref ty } => ty,
2176 _ => panic!("expected equality type binding for parenthesized generic args"),
2182 pub struct Ty<'hir> {
2184 pub kind: TyKind<'hir>,
2188 /// Not represented directly in the AST; referred to by name through a `ty_path`.
2189 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
2190 #[derive(HashStable_Generic)]
2201 /// All of the primitive types
2202 pub const ALL: [Self; 17] = [
2203 // any changes here should also be reflected in `PrimTy::from_name`
2204 Self::Int(IntTy::I8),
2205 Self::Int(IntTy::I16),
2206 Self::Int(IntTy::I32),
2207 Self::Int(IntTy::I64),
2208 Self::Int(IntTy::I128),
2209 Self::Int(IntTy::Isize),
2210 Self::Uint(UintTy::U8),
2211 Self::Uint(UintTy::U16),
2212 Self::Uint(UintTy::U32),
2213 Self::Uint(UintTy::U64),
2214 Self::Uint(UintTy::U128),
2215 Self::Uint(UintTy::Usize),
2216 Self::Float(FloatTy::F32),
2217 Self::Float(FloatTy::F64),
2223 /// Like [`PrimTy::name`], but returns a &str instead of a symbol.
2226 pub fn name_str(self) -> &'static str {
2228 PrimTy::Int(i) => i.name_str(),
2229 PrimTy::Uint(u) => u.name_str(),
2230 PrimTy::Float(f) => f.name_str(),
2231 PrimTy::Str => "str",
2232 PrimTy::Bool => "bool",
2233 PrimTy::Char => "char",
2237 pub fn name(self) -> Symbol {
2239 PrimTy::Int(i) => i.name(),
2240 PrimTy::Uint(u) => u.name(),
2241 PrimTy::Float(f) => f.name(),
2242 PrimTy::Str => sym::str,
2243 PrimTy::Bool => sym::bool,
2244 PrimTy::Char => sym::char,
2248 /// Returns the matching `PrimTy` for a `Symbol` such as "str" or "i32".
2249 /// Returns `None` if no matching type is found.
2250 pub fn from_name(name: Symbol) -> Option<Self> {
2251 let ty = match name {
2252 // any changes here should also be reflected in `PrimTy::ALL`
2253 sym::i8 => Self::Int(IntTy::I8),
2254 sym::i16 => Self::Int(IntTy::I16),
2255 sym::i32 => Self::Int(IntTy::I32),
2256 sym::i64 => Self::Int(IntTy::I64),
2257 sym::i128 => Self::Int(IntTy::I128),
2258 sym::isize => Self::Int(IntTy::Isize),
2259 sym::u8 => Self::Uint(UintTy::U8),
2260 sym::u16 => Self::Uint(UintTy::U16),
2261 sym::u32 => Self::Uint(UintTy::U32),
2262 sym::u64 => Self::Uint(UintTy::U64),
2263 sym::u128 => Self::Uint(UintTy::U128),
2264 sym::usize => Self::Uint(UintTy::Usize),
2265 sym::f32 => Self::Float(FloatTy::F32),
2266 sym::f64 => Self::Float(FloatTy::F64),
2267 sym::bool => Self::Bool,
2268 sym::char => Self::Char,
2269 sym::str => Self::Str,
2276 #[derive(Debug, HashStable_Generic)]
2277 pub struct BareFnTy<'hir> {
2278 pub unsafety: Unsafety,
2280 pub generic_params: &'hir [GenericParam<'hir>],
2281 pub decl: &'hir FnDecl<'hir>,
2282 pub param_names: &'hir [Ident],
2285 #[derive(Debug, HashStable_Generic)]
2286 pub struct OpaqueTy<'hir> {
2287 pub generics: Generics<'hir>,
2288 pub bounds: GenericBounds<'hir>,
2289 pub impl_trait_fn: Option<DefId>,
2290 pub origin: OpaqueTyOrigin,
2293 /// From whence the opaque type came.
2294 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2295 pub enum OpaqueTyOrigin {
2300 /// type aliases: `type Foo = impl Trait;`
2304 /// The various kinds of types recognized by the compiler.
2305 #[derive(Debug, HashStable_Generic)]
2306 pub enum TyKind<'hir> {
2307 /// A variable length slice (i.e., `[T]`).
2308 Slice(&'hir Ty<'hir>),
2309 /// A fixed length array (i.e., `[T; n]`).
2310 Array(&'hir Ty<'hir>, AnonConst),
2311 /// A raw pointer (i.e., `*const T` or `*mut T`).
2313 /// A reference (i.e., `&'a T` or `&'a mut T`).
2314 Rptr(Lifetime, MutTy<'hir>),
2315 /// A bare function (e.g., `fn(usize) -> bool`).
2316 BareFn(&'hir BareFnTy<'hir>),
2317 /// The never type (`!`).
2319 /// A tuple (`(A, B, C, D, ...)`).
2320 Tup(&'hir [Ty<'hir>]),
2321 /// A path to a type definition (`module::module::...::Type`), or an
2322 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2324 /// Type parameters may be stored in each `PathSegment`.
2326 /// A opaque type definition itself. This is currently only used for the
2327 /// `opaque type Foo: Trait` item that `impl Trait` in desugars to.
2329 /// The generic argument list contains the lifetimes (and in the future
2330 /// possibly parameters) that are actually bound on the `impl Trait`.
2331 OpaqueDef(ItemId, &'hir [GenericArg<'hir>]),
2332 /// A trait object type `Bound1 + Bound2 + Bound3`
2333 /// where `Bound` is a trait or a lifetime.
2334 TraitObject(&'hir [PolyTraitRef<'hir>], Lifetime, TraitObjectSyntax),
2337 /// `TyKind::Infer` means the type should be inferred instead of it having been
2338 /// specified. This can appear anywhere in a type.
2340 /// Placeholder for a type that has failed to be defined.
2344 #[derive(Debug, HashStable_Generic)]
2345 pub enum InlineAsmOperand<'hir> {
2347 reg: InlineAsmRegOrRegClass,
2351 reg: InlineAsmRegOrRegClass,
2353 expr: Option<Expr<'hir>>,
2356 reg: InlineAsmRegOrRegClass,
2361 reg: InlineAsmRegOrRegClass,
2363 in_expr: Expr<'hir>,
2364 out_expr: Option<Expr<'hir>>,
2367 anon_const: AnonConst,
2374 impl<'hir> InlineAsmOperand<'hir> {
2375 pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
2377 Self::In { reg, .. }
2378 | Self::Out { reg, .. }
2379 | Self::InOut { reg, .. }
2380 | Self::SplitInOut { reg, .. } => Some(reg),
2381 Self::Const { .. } | Self::Sym { .. } => None,
2386 #[derive(Debug, HashStable_Generic)]
2387 pub struct InlineAsm<'hir> {
2388 pub template: &'hir [InlineAsmTemplatePiece],
2389 pub operands: &'hir [(InlineAsmOperand<'hir>, Span)],
2390 pub options: InlineAsmOptions,
2391 pub line_spans: &'hir [Span],
2394 #[derive(Copy, Clone, Encodable, Decodable, Debug, Hash, HashStable_Generic, PartialEq)]
2395 pub struct LlvmInlineAsmOutput {
2396 pub constraint: Symbol,
2398 pub is_indirect: bool,
2402 // NOTE(eddyb) This is used within MIR as well, so unlike the rest of the HIR,
2403 // it needs to be `Clone` and `Decodable` and use plain `Vec<T>` instead of
2404 // arena-allocated slice.
2405 #[derive(Clone, Encodable, Decodable, Debug, Hash, HashStable_Generic, PartialEq)]
2406 pub struct LlvmInlineAsmInner {
2408 pub asm_str_style: StrStyle,
2409 pub outputs: Vec<LlvmInlineAsmOutput>,
2410 pub inputs: Vec<Symbol>,
2411 pub clobbers: Vec<Symbol>,
2413 pub alignstack: bool,
2414 pub dialect: LlvmAsmDialect,
2417 #[derive(Debug, HashStable_Generic)]
2418 pub struct LlvmInlineAsm<'hir> {
2419 pub inner: LlvmInlineAsmInner,
2420 pub outputs_exprs: &'hir [Expr<'hir>],
2421 pub inputs_exprs: &'hir [Expr<'hir>],
2424 /// Represents a parameter in a function header.
2425 #[derive(Debug, HashStable_Generic)]
2426 pub struct Param<'hir> {
2428 pub pat: &'hir Pat<'hir>,
2433 /// Represents the header (not the body) of a function declaration.
2434 #[derive(Debug, HashStable_Generic)]
2435 pub struct FnDecl<'hir> {
2436 /// The types of the function's parameters.
2438 /// Additional argument data is stored in the function's [body](Body::params).
2439 pub inputs: &'hir [Ty<'hir>],
2440 pub output: FnRetTy<'hir>,
2441 pub c_variadic: bool,
2442 /// Does the function have an implicit self?
2443 pub implicit_self: ImplicitSelfKind,
2446 /// Represents what type of implicit self a function has, if any.
2447 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2448 pub enum ImplicitSelfKind {
2449 /// Represents a `fn x(self);`.
2451 /// Represents a `fn x(mut self);`.
2453 /// Represents a `fn x(&self);`.
2455 /// Represents a `fn x(&mut self);`.
2457 /// Represents when a function does not have a self argument or
2458 /// when a function has a `self: X` argument.
2462 impl ImplicitSelfKind {
2463 /// Does this represent an implicit self?
2464 pub fn has_implicit_self(&self) -> bool {
2465 !matches!(*self, ImplicitSelfKind::None)
2469 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable, Debug)]
2470 #[derive(HashStable_Generic)]
2476 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable, HashStable_Generic)]
2477 pub enum Defaultness {
2478 Default { has_value: bool },
2483 pub fn has_value(&self) -> bool {
2485 Defaultness::Default { has_value } => has_value,
2486 Defaultness::Final => true,
2490 pub fn is_final(&self) -> bool {
2491 *self == Defaultness::Final
2494 pub fn is_default(&self) -> bool {
2495 matches!(*self, Defaultness::Default { .. })
2499 #[derive(Debug, HashStable_Generic)]
2500 pub enum FnRetTy<'hir> {
2501 /// Return type is not specified.
2503 /// Functions default to `()` and
2504 /// closures default to inference. Span points to where return
2505 /// type would be inserted.
2506 DefaultReturn(Span),
2507 /// Everything else.
2508 Return(&'hir Ty<'hir>),
2513 pub fn span(&self) -> Span {
2515 Self::DefaultReturn(span) => span,
2516 Self::Return(ref ty) => ty.span,
2521 #[derive(Encodable, Debug)]
2522 pub struct Mod<'hir> {
2523 /// A span from the first token past `{` to the last token until `}`.
2524 /// For `mod foo;`, the inner span ranges from the first token
2525 /// to the last token in the external file.
2527 pub item_ids: &'hir [ItemId],
2530 #[derive(Debug, HashStable_Generic)]
2531 pub struct EnumDef<'hir> {
2532 pub variants: &'hir [Variant<'hir>],
2535 #[derive(Debug, HashStable_Generic)]
2536 pub struct Variant<'hir> {
2537 /// Name of the variant.
2538 #[stable_hasher(project(name))]
2540 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2542 /// Fields and constructor id of the variant.
2543 pub data: VariantData<'hir>,
2544 /// Explicit discriminant (e.g., `Foo = 1`).
2545 pub disr_expr: Option<AnonConst>,
2550 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2552 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2553 /// Also produced for each element of a list `use`, e.g.
2554 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2557 /// Glob import, e.g., `use foo::*`.
2560 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2561 /// an additional `use foo::{}` for performing checks such as
2562 /// unstable feature gating. May be removed in the future.
2566 /// References to traits in impls.
2568 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2569 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2570 /// trait being referred to but just a unique `HirId` that serves as a key
2571 /// within the resolution map.
2572 #[derive(Clone, Debug, HashStable_Generic)]
2573 pub struct TraitRef<'hir> {
2574 pub path: &'hir Path<'hir>,
2575 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2576 #[stable_hasher(ignore)]
2577 pub hir_ref_id: HirId,
2581 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2582 pub fn trait_def_id(&self) -> Option<DefId> {
2583 match self.path.res {
2584 Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
2586 _ => unreachable!(),
2591 #[derive(Clone, Debug, HashStable_Generic)]
2592 pub struct PolyTraitRef<'hir> {
2593 /// The `'a` in `for<'a> Foo<&'a T>`.
2594 pub bound_generic_params: &'hir [GenericParam<'hir>],
2596 /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
2597 pub trait_ref: TraitRef<'hir>,
2602 pub type Visibility<'hir> = Spanned<VisibilityKind<'hir>>;
2605 pub enum VisibilityKind<'hir> {
2608 Restricted { path: &'hir Path<'hir>, hir_id: HirId },
2612 impl VisibilityKind<'_> {
2613 pub fn is_pub(&self) -> bool {
2614 matches!(*self, VisibilityKind::Public)
2617 pub fn is_pub_restricted(&self) -> bool {
2619 VisibilityKind::Public | VisibilityKind::Inherited => false,
2620 VisibilityKind::Crate(..) | VisibilityKind::Restricted { .. } => true,
2625 #[derive(Debug, HashStable_Generic)]
2626 pub struct FieldDef<'hir> {
2628 #[stable_hasher(project(name))]
2630 pub vis: Visibility<'hir>,
2632 pub ty: &'hir Ty<'hir>,
2636 // Still necessary in couple of places
2637 pub fn is_positional(&self) -> bool {
2638 let first = self.ident.as_str().as_bytes()[0];
2639 (b'0'..=b'9').contains(&first)
2643 /// Fields and constructor IDs of enum variants and structs.
2644 #[derive(Debug, HashStable_Generic)]
2645 pub enum VariantData<'hir> {
2646 /// A struct variant.
2648 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2649 Struct(&'hir [FieldDef<'hir>], /* recovered */ bool),
2650 /// A tuple variant.
2652 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2653 Tuple(&'hir [FieldDef<'hir>], HirId),
2656 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2660 impl VariantData<'hir> {
2661 /// Return the fields of this variant.
2662 pub fn fields(&self) -> &'hir [FieldDef<'hir>] {
2664 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2669 /// Return the `HirId` of this variant's constructor, if it has one.
2670 pub fn ctor_hir_id(&self) -> Option<HirId> {
2672 VariantData::Struct(_, _) => None,
2673 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2678 // The bodies for items are stored "out of line", in a separate
2679 // hashmap in the `Crate`. Here we just record the hir-id of the item
2680 // so it can fetched later.
2681 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug, Hash)]
2683 pub def_id: LocalDefId,
2688 pub fn hir_id(&self) -> HirId {
2689 // Items are always HIR owners.
2690 HirId::make_owner(self.def_id)
2696 /// The name might be a dummy name in case of anonymous items
2698 pub struct Item<'hir> {
2700 pub def_id: LocalDefId,
2701 pub kind: ItemKind<'hir>,
2702 pub vis: Visibility<'hir>,
2708 pub fn hir_id(&self) -> HirId {
2709 // Items are always HIR owners.
2710 HirId::make_owner(self.def_id)
2713 pub fn item_id(&self) -> ItemId {
2714 ItemId { def_id: self.def_id }
2718 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2719 #[derive(Encodable, Decodable, HashStable_Generic)]
2726 pub fn prefix_str(&self) -> &'static str {
2728 Self::Unsafe => "unsafe ",
2734 impl fmt::Display for Unsafety {
2735 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2736 f.write_str(match *self {
2737 Self::Unsafe => "unsafe",
2738 Self::Normal => "normal",
2743 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2744 #[derive(Encodable, Decodable, HashStable_Generic)]
2745 pub enum Constness {
2750 impl fmt::Display for Constness {
2751 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2752 f.write_str(match *self {
2753 Self::Const => "const",
2754 Self::NotConst => "non-const",
2759 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2760 pub struct FnHeader {
2761 pub unsafety: Unsafety,
2762 pub constness: Constness,
2763 pub asyncness: IsAsync,
2768 pub fn is_const(&self) -> bool {
2769 matches!(&self.constness, Constness::Const)
2773 #[derive(Debug, HashStable_Generic)]
2774 pub enum ItemKind<'hir> {
2775 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2777 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2778 ExternCrate(Option<Symbol>),
2780 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2784 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2785 Use(&'hir Path<'hir>, UseKind),
2787 /// A `static` item.
2788 Static(&'hir Ty<'hir>, Mutability, BodyId),
2790 Const(&'hir Ty<'hir>, BodyId),
2791 /// A function declaration.
2792 Fn(FnSig<'hir>, Generics<'hir>, BodyId),
2795 /// An external module, e.g. `extern { .. }`.
2796 ForeignMod { abi: Abi, items: &'hir [ForeignItemRef<'hir>] },
2797 /// Module-level inline assembly (from `global_asm!`).
2798 GlobalAsm(&'hir InlineAsm<'hir>),
2799 /// A type alias, e.g., `type Foo = Bar<u8>`.
2800 TyAlias(&'hir Ty<'hir>, Generics<'hir>),
2801 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2802 OpaqueTy(OpaqueTy<'hir>),
2803 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2804 Enum(EnumDef<'hir>, Generics<'hir>),
2805 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2806 Struct(VariantData<'hir>, Generics<'hir>),
2807 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2808 Union(VariantData<'hir>, Generics<'hir>),
2809 /// A trait definition.
2810 Trait(IsAuto, Unsafety, Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
2812 TraitAlias(Generics<'hir>, GenericBounds<'hir>),
2814 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2818 #[derive(Debug, HashStable_Generic)]
2819 pub struct Impl<'hir> {
2820 pub unsafety: Unsafety,
2821 pub polarity: ImplPolarity,
2822 pub defaultness: Defaultness,
2823 // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata
2824 // decoding as `Span`s cannot be decoded when a `Session` is not available.
2825 pub defaultness_span: Option<Span>,
2826 pub constness: Constness,
2827 pub generics: Generics<'hir>,
2829 /// The trait being implemented, if any.
2830 pub of_trait: Option<TraitRef<'hir>>,
2832 pub self_ty: &'hir Ty<'hir>,
2833 pub items: &'hir [ImplItemRef<'hir>],
2837 pub fn generics(&self) -> Option<&Generics<'_>> {
2839 ItemKind::Fn(_, ref generics, _)
2840 | ItemKind::TyAlias(_, ref generics)
2841 | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
2842 | ItemKind::Enum(_, ref generics)
2843 | ItemKind::Struct(_, ref generics)
2844 | ItemKind::Union(_, ref generics)
2845 | ItemKind::Trait(_, _, ref generics, _, _)
2846 | ItemKind::Impl(Impl { ref generics, .. }) => generics,
2851 pub fn descr(&self) -> &'static str {
2853 ItemKind::ExternCrate(..) => "extern crate",
2854 ItemKind::Use(..) => "`use` import",
2855 ItemKind::Static(..) => "static item",
2856 ItemKind::Const(..) => "constant item",
2857 ItemKind::Fn(..) => "function",
2858 ItemKind::Mod(..) => "module",
2859 ItemKind::ForeignMod { .. } => "extern block",
2860 ItemKind::GlobalAsm(..) => "global asm item",
2861 ItemKind::TyAlias(..) => "type alias",
2862 ItemKind::OpaqueTy(..) => "opaque type",
2863 ItemKind::Enum(..) => "enum",
2864 ItemKind::Struct(..) => "struct",
2865 ItemKind::Union(..) => "union",
2866 ItemKind::Trait(..) => "trait",
2867 ItemKind::TraitAlias(..) => "trait alias",
2868 ItemKind::Impl(..) => "implementation",
2873 /// A reference from an trait to one of its associated items. This
2874 /// contains the item's id, naturally, but also the item's name and
2875 /// some other high-level details (like whether it is an associated
2876 /// type or method, and whether it is public). This allows other
2877 /// passes to find the impl they want without loading the ID (which
2878 /// means fewer edges in the incremental compilation graph).
2879 #[derive(Encodable, Debug, HashStable_Generic)]
2880 pub struct TraitItemRef {
2881 pub id: TraitItemId,
2882 #[stable_hasher(project(name))]
2884 pub kind: AssocItemKind,
2886 pub defaultness: Defaultness,
2889 /// A reference from an impl to one of its associated items. This
2890 /// contains the item's ID, naturally, but also the item's name and
2891 /// some other high-level details (like whether it is an associated
2892 /// type or method, and whether it is public). This allows other
2893 /// passes to find the impl they want without loading the ID (which
2894 /// means fewer edges in the incremental compilation graph).
2895 #[derive(Debug, HashStable_Generic)]
2896 pub struct ImplItemRef<'hir> {
2898 #[stable_hasher(project(name))]
2900 pub kind: AssocItemKind,
2902 pub vis: Visibility<'hir>,
2903 pub defaultness: Defaultness,
2906 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2907 pub enum AssocItemKind {
2909 Fn { has_self: bool },
2913 // The bodies for items are stored "out of line", in a separate
2914 // hashmap in the `Crate`. Here we just record the hir-id of the item
2915 // so it can fetched later.
2916 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
2917 pub struct ForeignItemId {
2918 pub def_id: LocalDefId,
2921 impl ForeignItemId {
2923 pub fn hir_id(&self) -> HirId {
2924 // Items are always HIR owners.
2925 HirId::make_owner(self.def_id)
2929 /// A reference from a foreign block to one of its items. This
2930 /// contains the item's ID, naturally, but also the item's name and
2931 /// some other high-level details (like whether it is an associated
2932 /// type or method, and whether it is public). This allows other
2933 /// passes to find the impl they want without loading the ID (which
2934 /// means fewer edges in the incremental compilation graph).
2935 #[derive(Debug, HashStable_Generic)]
2936 pub struct ForeignItemRef<'hir> {
2937 pub id: ForeignItemId,
2938 #[stable_hasher(project(name))]
2941 pub vis: Visibility<'hir>,
2945 pub struct ForeignItem<'hir> {
2947 pub kind: ForeignItemKind<'hir>,
2948 pub def_id: LocalDefId,
2950 pub vis: Visibility<'hir>,
2953 impl ForeignItem<'_> {
2955 pub fn hir_id(&self) -> HirId {
2956 // Items are always HIR owners.
2957 HirId::make_owner(self.def_id)
2960 pub fn foreign_item_id(&self) -> ForeignItemId {
2961 ForeignItemId { def_id: self.def_id }
2965 /// An item within an `extern` block.
2966 #[derive(Debug, HashStable_Generic)]
2967 pub enum ForeignItemKind<'hir> {
2968 /// A foreign function.
2969 Fn(&'hir FnDecl<'hir>, &'hir [Ident], Generics<'hir>),
2970 /// A foreign static item (`static ext: u8`).
2971 Static(&'hir Ty<'hir>, Mutability),
2976 /// A variable captured by a closure.
2977 #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)]
2979 // First span where it is accessed (there can be multiple).
2983 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2984 // has length > 0 if the trait is found through an chain of imports, starting with the
2985 // import/use statement in the scope where the trait is used.
2986 #[derive(Encodable, Decodable, Clone, Debug)]
2987 pub struct TraitCandidate {
2989 pub import_ids: SmallVec<[LocalDefId; 1]>,
2992 #[derive(Copy, Clone, Debug, HashStable_Generic)]
2993 pub enum OwnerNode<'hir> {
2994 Item(&'hir Item<'hir>),
2995 ForeignItem(&'hir ForeignItem<'hir>),
2996 TraitItem(&'hir TraitItem<'hir>),
2997 ImplItem(&'hir ImplItem<'hir>),
2998 MacroDef(&'hir MacroDef<'hir>),
2999 Crate(&'hir Mod<'hir>),
3002 impl<'hir> OwnerNode<'hir> {
3003 pub fn ident(&self) -> Option<Ident> {
3005 OwnerNode::Item(Item { ident, .. })
3006 | OwnerNode::ForeignItem(ForeignItem { ident, .. })
3007 | OwnerNode::ImplItem(ImplItem { ident, .. })
3008 | OwnerNode::TraitItem(TraitItem { ident, .. })
3009 | OwnerNode::MacroDef(MacroDef { ident, .. }) => Some(*ident),
3010 OwnerNode::Crate(..) => None,
3014 pub fn span(&self) -> Span {
3016 OwnerNode::Item(Item { span, .. })
3017 | OwnerNode::ForeignItem(ForeignItem { span, .. })
3018 | OwnerNode::ImplItem(ImplItem { span, .. })
3019 | OwnerNode::TraitItem(TraitItem { span, .. })
3020 | OwnerNode::MacroDef(MacroDef { span, .. })
3021 | OwnerNode::Crate(Mod { inner: span, .. }) => *span,
3025 pub fn fn_decl(&self) -> Option<&FnDecl<'hir>> {
3027 OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3028 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3029 | OwnerNode::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3030 OwnerNode::ForeignItem(ForeignItem {
3031 kind: ForeignItemKind::Fn(fn_decl, _, _),
3033 }) => Some(fn_decl),
3038 pub fn body_id(&self) -> Option<BodyId> {
3040 OwnerNode::TraitItem(TraitItem {
3041 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3044 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3045 | OwnerNode::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3050 pub fn generics(&self) -> Option<&'hir Generics<'hir>> {
3052 OwnerNode::TraitItem(TraitItem { generics, .. })
3053 | OwnerNode::ImplItem(ImplItem { generics, .. }) => Some(generics),
3054 OwnerNode::Item(item) => item.kind.generics(),
3059 pub fn def_id(self) -> LocalDefId {
3061 OwnerNode::Item(Item { def_id, .. })
3062 | OwnerNode::TraitItem(TraitItem { def_id, .. })
3063 | OwnerNode::ImplItem(ImplItem { def_id, .. })
3064 | OwnerNode::ForeignItem(ForeignItem { def_id, .. })
3065 | OwnerNode::MacroDef(MacroDef { def_id, .. }) => *def_id,
3066 OwnerNode::Crate(..) => crate::CRATE_HIR_ID.owner,
3070 pub fn expect_item(self) -> &'hir Item<'hir> {
3072 OwnerNode::Item(n) => n,
3077 pub fn expect_foreign_item(self) -> &'hir ForeignItem<'hir> {
3079 OwnerNode::ForeignItem(n) => n,
3084 pub fn expect_impl_item(self) -> &'hir ImplItem<'hir> {
3086 OwnerNode::ImplItem(n) => n,
3091 pub fn expect_trait_item(self) -> &'hir TraitItem<'hir> {
3093 OwnerNode::TraitItem(n) => n,
3098 pub fn expect_macro_def(self) -> &'hir MacroDef<'hir> {
3100 OwnerNode::MacroDef(n) => n,
3106 impl<'hir> Into<OwnerNode<'hir>> for &'hir Item<'hir> {
3107 fn into(self) -> OwnerNode<'hir> {
3108 OwnerNode::Item(self)
3112 impl<'hir> Into<OwnerNode<'hir>> for &'hir ForeignItem<'hir> {
3113 fn into(self) -> OwnerNode<'hir> {
3114 OwnerNode::ForeignItem(self)
3118 impl<'hir> Into<OwnerNode<'hir>> for &'hir ImplItem<'hir> {
3119 fn into(self) -> OwnerNode<'hir> {
3120 OwnerNode::ImplItem(self)
3124 impl<'hir> Into<OwnerNode<'hir>> for &'hir TraitItem<'hir> {
3125 fn into(self) -> OwnerNode<'hir> {
3126 OwnerNode::TraitItem(self)
3130 impl<'hir> Into<OwnerNode<'hir>> for &'hir MacroDef<'hir> {
3131 fn into(self) -> OwnerNode<'hir> {
3132 OwnerNode::MacroDef(self)
3136 impl<'hir> Into<Node<'hir>> for OwnerNode<'hir> {
3137 fn into(self) -> Node<'hir> {
3139 OwnerNode::Item(n) => Node::Item(n),
3140 OwnerNode::ForeignItem(n) => Node::ForeignItem(n),
3141 OwnerNode::ImplItem(n) => Node::ImplItem(n),
3142 OwnerNode::TraitItem(n) => Node::TraitItem(n),
3143 OwnerNode::MacroDef(n) => Node::MacroDef(n),
3144 OwnerNode::Crate(n) => Node::Crate(n),
3149 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3150 pub enum Node<'hir> {
3151 Param(&'hir Param<'hir>),
3152 Item(&'hir Item<'hir>),
3153 ForeignItem(&'hir ForeignItem<'hir>),
3154 TraitItem(&'hir TraitItem<'hir>),
3155 ImplItem(&'hir ImplItem<'hir>),
3156 Variant(&'hir Variant<'hir>),
3157 Field(&'hir FieldDef<'hir>),
3158 AnonConst(&'hir AnonConst),
3159 Expr(&'hir Expr<'hir>),
3160 Stmt(&'hir Stmt<'hir>),
3161 PathSegment(&'hir PathSegment<'hir>),
3163 TraitRef(&'hir TraitRef<'hir>),
3164 Binding(&'hir Pat<'hir>),
3165 Pat(&'hir Pat<'hir>),
3166 Arm(&'hir Arm<'hir>),
3167 Block(&'hir Block<'hir>),
3168 Local(&'hir Local<'hir>),
3169 MacroDef(&'hir MacroDef<'hir>),
3171 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
3172 /// with synthesized constructors.
3173 Ctor(&'hir VariantData<'hir>),
3175 Lifetime(&'hir Lifetime),
3176 GenericParam(&'hir GenericParam<'hir>),
3177 Visibility(&'hir Visibility<'hir>),
3179 Crate(&'hir Mod<'hir>),
3181 Infer(&'hir InferArg),
3184 impl<'hir> Node<'hir> {
3185 /// Get the identifier of this `Node`, if applicable.
3189 /// Calling `.ident()` on a [`Node::Ctor`] will return `None`
3190 /// because `Ctor`s do not have identifiers themselves.
3191 /// Instead, call `.ident()` on the parent struct/variant, like so:
3193 /// ```ignore (illustrative)
3196 /// .and_then(|ctor_id| tcx.hir().find(tcx.hir().get_parent_node(ctor_id)))
3197 /// .and_then(|parent| parent.ident())
3199 pub fn ident(&self) -> Option<Ident> {
3201 Node::TraitItem(TraitItem { ident, .. })
3202 | Node::ImplItem(ImplItem { ident, .. })
3203 | Node::ForeignItem(ForeignItem { ident, .. })
3204 | Node::Field(FieldDef { ident, .. })
3205 | Node::Variant(Variant { ident, .. })
3206 | Node::MacroDef(MacroDef { ident, .. })
3207 | Node::Item(Item { ident, .. })
3208 | Node::PathSegment(PathSegment { ident, .. }) => Some(*ident),
3209 Node::Lifetime(lt) => Some(lt.name.ident()),
3210 Node::GenericParam(p) => Some(p.name.ident()),
3212 | Node::AnonConst(..)
3221 | Node::Visibility(..)
3224 | Node::TraitRef(..)
3225 | Node::Infer(..) => None,
3229 pub fn fn_decl(&self) -> Option<&FnDecl<'hir>> {
3231 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3232 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3233 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3234 Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
3241 pub fn body_id(&self) -> Option<BodyId> {
3243 Node::TraitItem(TraitItem {
3244 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3247 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3248 | Node::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3253 pub fn generics(&self) -> Option<&'hir Generics<'hir>> {
3255 Node::TraitItem(TraitItem { generics, .. })
3256 | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
3257 Node::Item(item) => item.kind.generics(),
3262 pub fn hir_id(&self) -> Option<HirId> {
3264 Node::Item(Item { def_id, .. })
3265 | Node::TraitItem(TraitItem { def_id, .. })
3266 | Node::ImplItem(ImplItem { def_id, .. })
3267 | Node::ForeignItem(ForeignItem { def_id, .. })
3268 | Node::MacroDef(MacroDef { def_id, .. }) => Some(HirId::make_owner(*def_id)),
3269 Node::Field(FieldDef { hir_id, .. })
3270 | Node::AnonConst(AnonConst { hir_id, .. })
3271 | Node::Expr(Expr { hir_id, .. })
3272 | Node::Stmt(Stmt { hir_id, .. })
3273 | Node::Ty(Ty { hir_id, .. })
3274 | Node::Binding(Pat { hir_id, .. })
3275 | Node::Pat(Pat { hir_id, .. })
3276 | Node::Arm(Arm { hir_id, .. })
3277 | Node::Block(Block { hir_id, .. })
3278 | Node::Local(Local { hir_id, .. })
3279 | Node::Lifetime(Lifetime { hir_id, .. })
3280 | Node::Param(Param { hir_id, .. })
3281 | Node::Infer(InferArg { hir_id, .. })
3282 | Node::GenericParam(GenericParam { hir_id, .. }) => Some(*hir_id),
3283 Node::TraitRef(TraitRef { hir_ref_id, .. }) => Some(*hir_ref_id),
3284 Node::PathSegment(PathSegment { hir_id, .. }) => *hir_id,
3285 Node::Variant(Variant { id, .. }) => Some(*id),
3286 Node::Ctor(variant) => variant.ctor_hir_id(),
3287 Node::Crate(_) | Node::Visibility(_) => None,
3291 /// Returns `Constness::Const` when this node is a const fn/impl/item,
3293 /// HACK(fee1-dead): or an associated type in a trait. This works because
3294 /// only typeck cares about const trait predicates, so although the predicates
3295 /// query would return const predicates when it does not need to be const,
3296 /// it wouldn't have any effect.
3297 pub fn constness_for_typeck(&self) -> Constness {
3300 kind: ItemKind::Fn(FnSig { header: FnHeader { constness, .. }, .. }, ..),
3303 | Node::TraitItem(TraitItem {
3304 kind: TraitItemKind::Fn(FnSig { header: FnHeader { constness, .. }, .. }, ..),
3307 | Node::ImplItem(ImplItem {
3308 kind: ImplItemKind::Fn(FnSig { header: FnHeader { constness, .. }, .. }, ..),
3311 | Node::Item(Item { kind: ItemKind::Impl(Impl { constness, .. }), .. }) => *constness,
3313 Node::Item(Item { kind: ItemKind::Const(..), .. })
3314 | Node::TraitItem(TraitItem { kind: TraitItemKind::Const(..), .. })
3315 | Node::TraitItem(TraitItem { kind: TraitItemKind::Type(..), .. })
3316 | Node::ImplItem(ImplItem { kind: ImplItemKind::Const(..), .. }) => Constness::Const,
3318 _ => Constness::NotConst,
3322 pub fn as_owner(self) -> Option<OwnerNode<'hir>> {
3324 Node::Item(i) => Some(OwnerNode::Item(i)),
3325 Node::ForeignItem(i) => Some(OwnerNode::ForeignItem(i)),
3326 Node::TraitItem(i) => Some(OwnerNode::TraitItem(i)),
3327 Node::ImplItem(i) => Some(OwnerNode::ImplItem(i)),
3328 Node::MacroDef(i) => Some(OwnerNode::MacroDef(i)),
3329 Node::Crate(i) => Some(OwnerNode::Crate(i)),
3335 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3336 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
3338 rustc_data_structures::static_assert_size!(super::Block<'static>, 48);
3339 rustc_data_structures::static_assert_size!(super::Expr<'static>, 64);
3340 rustc_data_structures::static_assert_size!(super::Pat<'static>, 88);
3341 rustc_data_structures::static_assert_size!(super::QPath<'static>, 24);
3342 rustc_data_structures::static_assert_size!(super::Ty<'static>, 72);
3344 rustc_data_structures::static_assert_size!(super::Item<'static>, 184);
3345 rustc_data_structures::static_assert_size!(super::TraitItem<'static>, 128);
3346 rustc_data_structures::static_assert_size!(super::ImplItem<'static>, 152);
3347 rustc_data_structures::static_assert_size!(super::ForeignItem<'static>, 136);