1 //! HIR datatypes. See the [rustc guide] for more info.
3 //! [rustc guide]: https://rust-lang.github.io/rustc-guide/hir.html
5 pub use self::BlockCheckMode::*;
6 pub use self::FunctionRetTy::*;
7 pub use self::PrimTy::*;
9 pub use self::UnsafeSource::*;
11 use crate::hir::def::{Res, DefKind};
12 use crate::hir::def_id::{DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX};
13 use crate::hir::ptr::P;
14 use crate::mir::mono::Linkage;
15 use crate::ty::AdtKind;
16 use crate::ty::query::Providers;
17 use crate::util::nodemap::{NodeMap, FxHashSet};
19 use errors::{Applicability, DiagnosticBuilder, FatalError};
20 use syntax_pos::{Span, DUMMY_SP, MultiSpan};
21 use syntax::source_map::{Spanned, SourceMap};
22 use syntax::ast::{self, CrateSugar, Ident, Name, NodeId, AsmDialect};
23 use syntax::ast::{Attribute, Label, LitKind, StrStyle, FloatTy, IntTy, UintTy};
24 pub use syntax::ast::{Mutability, Constness, Unsafety, Movability, CaptureBy};
25 pub use syntax::ast::{IsAuto, ImplPolarity, BorrowKind};
26 use syntax::attr::{InlineAttr, OptimizeAttr};
27 use syntax::symbol::{Symbol, kw};
28 use syntax::tokenstream::TokenStream;
29 use syntax::util::parser::ExprPrecedence;
30 use rustc_target::spec::abi::Abi;
31 use rustc_data_structures::sync::{par_for_each_in, Send, Sync};
32 use rustc_data_structures::thin_vec::ThinVec;
33 use rustc_macros::HashStable;
34 use rustc_serialize::{self, Encoder, Encodable, Decoder, Decodable};
35 use std::collections::{BTreeSet, BTreeMap};
37 use smallvec::SmallVec;
39 /// HIR doesn't commit to a concrete storage type and has its own alias for a vector.
40 /// It can be `Vec`, `P<[T]>` or potentially `Box<[T]>`, or some other container with similar
41 /// behavior. Unlike AST, HIR is mostly a static structure, so we can use an owned slice instead
42 /// of `Vec` to avoid keeping extra capacity.
43 pub type HirVec<T> = P<[T]>;
45 macro_rules! hir_vec {
46 ($elem:expr; $n:expr) => (
47 $crate::hir::HirVec::from(vec![$elem; $n])
50 $crate::hir::HirVec::from(vec![$($x),*])
58 pub mod itemlikevisit;
66 /// Uniquely identifies a node in the HIR of the current crate. It is
67 /// composed of the `owner`, which is the `DefIndex` of the directly enclosing
68 /// `hir::Item`, `hir::TraitItem`, or `hir::ImplItem` (i.e., the closest "item-like"),
69 /// and the `local_id` which is unique within the given owner.
71 /// This two-level structure makes for more stable values: One can move an item
72 /// around within the source code, or add or remove stuff before it, without
73 /// the `local_id` part of the `HirId` changing, which is a very useful property in
74 /// incremental compilation where we have to persist things through changes to
76 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)]
79 pub local_id: ItemLocalId,
83 pub fn owner_def_id(self) -> DefId {
84 DefId::local(self.owner)
87 pub fn owner_local_def_id(self) -> LocalDefId {
88 LocalDefId::from_def_id(DefId::local(self.owner))
92 impl rustc_serialize::UseSpecializedEncodable for HirId {
93 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
105 impl rustc_serialize::UseSpecializedDecodable for HirId {
106 fn default_decode<D: Decoder>(d: &mut D) -> Result<HirId, D::Error> {
107 let owner = DefIndex::decode(d)?;
108 let local_id = ItemLocalId::decode(d)?;
117 impl fmt::Display for HirId {
118 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
119 write!(f, "{:?}", self)
123 // Hack to ensure that we don't try to access the private parts of `ItemLocalId` in this module.
124 mod item_local_id_inner {
125 use rustc_index::vec::Idx;
126 use rustc_macros::HashStable;
127 rustc_index::newtype_index! {
128 /// An `ItemLocalId` uniquely identifies something within a given "item-like";
129 /// that is, within a `hir::Item`, `hir::TraitItem`, or `hir::ImplItem`. There is no
130 /// guarantee that the numerical value of a given `ItemLocalId` corresponds to
131 /// the node's position within the owning item in any way, but there is a
132 /// guarantee that the `LocalItemId`s within an owner occupy a dense range of
133 /// integers starting at zero, so a mapping that maps all or most nodes within
134 /// an "item-like" to something else can be implemented by a `Vec` instead of a
135 /// tree or hash map.
136 pub struct ItemLocalId {
142 pub use self::item_local_id_inner::ItemLocalId;
144 /// The `HirId` corresponding to `CRATE_NODE_ID` and `CRATE_DEF_INDEX`.
145 pub const CRATE_HIR_ID: HirId = HirId {
146 owner: CRATE_DEF_INDEX,
147 local_id: ItemLocalId::from_u32_const(0)
150 pub const DUMMY_HIR_ID: HirId = HirId {
151 owner: CRATE_DEF_INDEX,
152 local_id: DUMMY_ITEM_LOCAL_ID,
155 pub const DUMMY_ITEM_LOCAL_ID: ItemLocalId = ItemLocalId::MAX;
157 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, HashStable)]
158 pub struct Lifetime {
162 /// Either "`'a`", referring to a named lifetime definition,
163 /// or "``" (i.e., `kw::Invalid`), for elision placeholders.
165 /// HIR lowering inserts these placeholders in type paths that
166 /// refer to type definitions needing lifetime parameters,
167 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
168 pub name: LifetimeName,
171 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy, HashStable)]
173 /// Some user-given name like `T` or `'x`.
176 /// Synthetic name generated when user elided a lifetime in an impl header.
178 /// E.g., the lifetimes in cases like these:
180 /// impl Foo for &u32
181 /// impl Foo<'_> for u32
183 /// in that case, we rewrite to
185 /// impl<'f> Foo for &'f u32
186 /// impl<'f> Foo<'f> for u32
188 /// where `'f` is something like `Fresh(0)`. The indices are
189 /// unique per impl, but not necessarily continuous.
192 /// Indicates an illegal name was given and an error has been
193 /// reported (so we should squelch other derived errors). Occurs
194 /// when, e.g., `'_` is used in the wrong place.
199 pub fn ident(&self) -> Ident {
201 ParamName::Plain(ident) => ident,
202 ParamName::Fresh(_) |
203 ParamName::Error => Ident::with_dummy_span(kw::UnderscoreLifetime),
207 pub fn modern(&self) -> ParamName {
209 ParamName::Plain(ident) => ParamName::Plain(ident.modern()),
210 param_name => param_name,
215 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy, HashStable)]
216 pub enum LifetimeName {
217 /// User-given names or fresh (synthetic) names.
220 /// User wrote nothing (e.g., the lifetime in `&u32`).
223 /// Implicit lifetime in a context like `dyn Foo`. This is
224 /// distinguished from implicit lifetimes elsewhere because the
225 /// lifetime that they default to must appear elsewhere within the
226 /// enclosing type. This means that, in an `impl Trait` context, we
227 /// don't have to create a parameter for them. That is, `impl
228 /// Trait<Item = &u32>` expands to an opaque type like `type
229 /// Foo<'a> = impl Trait<Item = &'a u32>`, but `impl Trait<item =
230 /// dyn Bar>` expands to `type Foo = impl Trait<Item = dyn Bar +
231 /// 'static>`. The latter uses `ImplicitObjectLifetimeDefault` so
232 /// that surrounding code knows not to create a lifetime
234 ImplicitObjectLifetimeDefault,
236 /// Indicates an error during lowering (usually `'_` in wrong place)
237 /// that was already reported.
240 /// User wrote specifies `'_`.
243 /// User wrote `'static`.
248 pub fn ident(&self) -> Ident {
250 LifetimeName::ImplicitObjectLifetimeDefault
251 | LifetimeName::Implicit
252 | LifetimeName::Error => Ident::invalid(),
253 LifetimeName::Underscore => Ident::with_dummy_span(kw::UnderscoreLifetime),
254 LifetimeName::Static => Ident::with_dummy_span(kw::StaticLifetime),
255 LifetimeName::Param(param_name) => param_name.ident(),
259 pub fn is_elided(&self) -> bool {
261 LifetimeName::ImplicitObjectLifetimeDefault
262 | LifetimeName::Implicit
263 | LifetimeName::Underscore => true,
265 // It might seem surprising that `Fresh(_)` counts as
266 // *not* elided -- but this is because, as far as the code
267 // in the compiler is concerned -- `Fresh(_)` variants act
268 // equivalently to "some fresh name". They correspond to
269 // early-bound regions on an impl, in other words.
270 LifetimeName::Error | LifetimeName::Param(_) | LifetimeName::Static => false,
274 fn is_static(&self) -> bool {
275 self == &LifetimeName::Static
278 pub fn modern(&self) -> LifetimeName {
280 LifetimeName::Param(param_name) => LifetimeName::Param(param_name.modern()),
281 lifetime_name => lifetime_name,
286 impl fmt::Display for Lifetime {
287 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
288 self.name.ident().fmt(f)
292 impl fmt::Debug for Lifetime {
293 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
297 print::to_string(print::NO_ANN, |s| s.print_lifetime(self)))
302 pub fn is_elided(&self) -> bool {
303 self.name.is_elided()
306 pub fn is_static(&self) -> bool {
307 self.name.is_static()
311 /// A `Path` is essentially Rust's notion of a name; for instance,
312 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
313 /// along with a bunch of supporting information.
314 #[derive(RustcEncodable, RustcDecodable, HashStable)]
317 /// The resolution for the path.
319 /// The segments in the path: the things separated by `::`.
320 pub segments: HirVec<PathSegment>,
324 pub fn is_global(&self) -> bool {
325 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
329 impl fmt::Debug for Path {
330 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
331 write!(f, "path({})", self)
335 impl fmt::Display for Path {
336 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
337 write!(f, "{}", print::to_string(print::NO_ANN, |s| s.print_path(self, false)))
341 /// A segment of a path: an identifier, an optional lifetime, and a set of
343 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
344 pub struct PathSegment {
345 /// The identifier portion of this path segment.
346 #[stable_hasher(project(name))]
348 // `id` and `res` are optional. We currently only use these in save-analysis,
349 // any path segments without these will not have save-analysis info and
350 // therefore will not have 'jump to def' in IDEs, but otherwise will not be
351 // affected. (In general, we don't bother to get the defs for synthesized
352 // segments, only for segments which have come from the AST).
353 pub hir_id: Option<HirId>,
354 pub res: Option<Res>,
356 /// Type/lifetime parameters attached to this path. They come in
357 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
358 /// this is more than just simple syntactic sugar; the use of
359 /// parens affects the region binding rules, so we preserve the
361 pub args: Option<P<GenericArgs>>,
363 /// Whether to infer remaining type parameters, if any.
364 /// This only applies to expression and pattern paths, and
365 /// out of those only the segments with no type parameters
366 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
367 pub infer_args: bool,
371 /// Converts an identifier to the corresponding segment.
372 pub fn from_ident(ident: Ident) -> PathSegment {
384 hir_id: Option<HirId>,
394 args: if args.is_empty() {
402 pub fn generic_args(&self) -> &GenericArgs {
403 if let Some(ref args) = self.args {
406 const DUMMY: &GenericArgs = &GenericArgs::none();
412 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
413 pub struct ConstArg {
414 pub value: AnonConst,
418 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
419 pub enum GenericArg {
426 pub fn span(&self) -> Span {
428 GenericArg::Lifetime(l) => l.span,
429 GenericArg::Type(t) => t.span,
430 GenericArg::Const(c) => c.span,
434 pub fn id(&self) -> HirId {
436 GenericArg::Lifetime(l) => l.hir_id,
437 GenericArg::Type(t) => t.hir_id,
438 GenericArg::Const(c) => c.value.hir_id,
442 pub fn is_const(&self) -> bool {
444 GenericArg::Const(_) => true,
450 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
451 pub struct GenericArgs {
452 /// The generic arguments for this path segment.
453 pub args: HirVec<GenericArg>,
454 /// Bindings (equality constraints) on associated types, if present.
455 /// E.g., `Foo<A = Bar>`.
456 pub bindings: HirVec<TypeBinding>,
457 /// Were arguments written in parenthesized form `Fn(T) -> U`?
458 /// This is required mostly for pretty-printing and diagnostics,
459 /// but also for changing lifetime elision rules to be "function-like".
460 pub parenthesized: bool,
464 pub const fn none() -> Self {
467 bindings: HirVec::new(),
468 parenthesized: false,
472 pub fn is_empty(&self) -> bool {
473 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
476 pub fn inputs(&self) -> &[Ty] {
477 if self.parenthesized {
478 for arg in &self.args {
480 GenericArg::Lifetime(_) => {}
481 GenericArg::Type(ref ty) => {
482 if let TyKind::Tup(ref tys) = ty.kind {
487 GenericArg::Const(_) => {}
491 bug!("GenericArgs::inputs: not a `Fn(T) -> U`");
494 pub fn own_counts(&self) -> GenericParamCount {
495 // We could cache this as a property of `GenericParamCount`, but
496 // the aim is to refactor this away entirely eventually and the
497 // presence of this method will be a constant reminder.
498 let mut own_counts: GenericParamCount = Default::default();
500 for arg in &self.args {
502 GenericArg::Lifetime(_) => own_counts.lifetimes += 1,
503 GenericArg::Type(_) => own_counts.types += 1,
504 GenericArg::Const(_) => own_counts.consts += 1,
512 /// A modifier on a bound, currently this is only used for `?Sized`, where the
513 /// modifier is `Maybe`. Negative bounds should also be handled here.
514 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
515 pub enum TraitBoundModifier {
520 /// The AST represents all type param bounds as types.
521 /// `typeck::collect::compute_bounds` matches these against
522 /// the "special" built-in traits (see `middle::lang_items`) and
523 /// detects `Copy`, `Send` and `Sync`.
524 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
525 pub enum GenericBound {
526 Trait(PolyTraitRef, TraitBoundModifier),
531 pub fn span(&self) -> Span {
533 &GenericBound::Trait(ref t, ..) => t.span,
534 &GenericBound::Outlives(ref l) => l.span,
539 pub type GenericBounds = HirVec<GenericBound>;
541 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable)]
542 pub enum LifetimeParamKind {
543 // Indicates that the lifetime definition was explicitly declared (e.g., in
544 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
547 // Indicates that the lifetime definition was synthetically added
548 // as a result of an in-band lifetime usage (e.g., in
549 // `fn foo(x: &'a u8) -> &'a u8 { x }`).
552 // Indication that the lifetime was elided (e.g., in both cases in
553 // `fn foo(x: &u8) -> &'_ u8 { x }`).
556 // Indication that the lifetime name was somehow in error.
560 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
561 pub enum GenericParamKind {
562 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
564 kind: LifetimeParamKind,
567 default: Option<P<Ty>>,
568 synthetic: Option<SyntheticTyParamKind>,
575 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
576 pub struct GenericParam {
579 pub attrs: HirVec<Attribute>,
580 pub bounds: GenericBounds,
582 pub pure_wrt_drop: bool,
583 pub kind: GenericParamKind,
587 pub struct GenericParamCount {
588 pub lifetimes: usize,
593 /// Represents lifetimes and type parameters attached to a declaration
594 /// of a function, enum, trait, etc.
595 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
596 pub struct Generics {
597 pub params: HirVec<GenericParam>,
598 pub where_clause: WhereClause,
603 pub const fn empty() -> Generics {
605 params: HirVec::new(),
606 where_clause: WhereClause {
607 predicates: HirVec::new(),
614 pub fn own_counts(&self) -> GenericParamCount {
615 // We could cache this as a property of `GenericParamCount`, but
616 // the aim is to refactor this away entirely eventually and the
617 // presence of this method will be a constant reminder.
618 let mut own_counts: GenericParamCount = Default::default();
620 for param in &self.params {
622 GenericParamKind::Lifetime { .. } => own_counts.lifetimes += 1,
623 GenericParamKind::Type { .. } => own_counts.types += 1,
624 GenericParamKind::Const { .. } => own_counts.consts += 1,
631 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam> {
632 for param in &self.params {
633 if name == param.name.ident().name {
640 pub fn spans(&self) -> MultiSpan {
641 if self.params.is_empty() {
644 self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
648 /// Suggest restricting a type param with a new bound.
649 pub fn suggest_constraining_type_param(
651 err: &mut DiagnosticBuilder<'_>,
654 source_map: &SourceMap,
657 let restrict_msg = "consider further restricting this bound";
658 if let Some(param) = self.params.iter().filter(|p| {
659 p.name.ident().as_str() == param_name
661 if param_name.starts_with("impl ") {
662 // `impl Trait` in argument:
663 // `fn foo(x: impl Trait) {}` → `fn foo(t: impl Trait + Trait2) {}`
667 // `impl CurrentTrait + MissingTrait`
668 format!("{} + {}", param_name, constraint),
669 Applicability::MachineApplicable,
671 } else if self.where_clause.predicates.is_empty() &&
672 param.bounds.is_empty()
674 // If there are no bounds whatsoever, suggest adding a constraint
675 // to the type parameter:
676 // `fn foo<T>(t: T) {}` → `fn foo<T: Trait>(t: T) {}`
679 "consider restricting this bound",
680 format!("{}: {}", param_name, constraint),
681 Applicability::MachineApplicable,
683 } else if !self.where_clause.predicates.is_empty() {
684 // There is a `where` clause, so suggest expanding it:
685 // `fn foo<T>(t: T) where T: Debug {}` →
686 // `fn foo<T>(t: T) where T: Debug, T: Trait {}`
688 self.where_clause.span().unwrap().shrink_to_hi(),
689 &format!("consider further restricting type parameter `{}`", param_name),
690 format!(", {}: {}", param_name, constraint),
691 Applicability::MachineApplicable,
694 // If there is no `where` clause lean towards constraining to the
696 // `fn foo<X: Bar, T>(t: T, x: X) {}` → `fn foo<T: Trait>(t: T) {}`
697 // `fn foo<T: Bar>(t: T) {}` → `fn foo<T: Bar + Trait>(t: T) {}`
698 let sp = param.span.with_hi(span.hi());
699 let span = source_map.span_through_char(sp, ':');
700 if sp != param.span && sp != span {
701 // Only suggest if we have high certainty that the span
702 // covers the colon in `foo<T: Trait>`.
706 format!("{}: {} + ", param_name, constraint),
707 Applicability::MachineApplicable,
712 &format!("consider adding a `where {}: {}` bound", param_name, constraint),
722 /// Synthetic type parameters are converted to another form during lowering; this allows
723 /// us to track the original form they had, and is useful for error messages.
724 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
725 pub enum SyntheticTyParamKind {
729 /// A where-clause in a definition.
730 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
731 pub struct WhereClause {
732 pub predicates: HirVec<WherePredicate>,
733 // Only valid if predicates isn't empty.
738 pub fn span(&self) -> Option<Span> {
739 if self.predicates.is_empty() {
746 /// The `WhereClause` under normal circumstances points at either the predicates or the empty
747 /// space where the `where` clause should be. Only of use for diagnostic suggestions.
748 pub fn span_for_predicates_or_empty_place(&self) -> Span {
753 /// A single predicate in a where-clause.
754 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
755 pub enum WherePredicate {
756 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
757 BoundPredicate(WhereBoundPredicate),
758 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
759 RegionPredicate(WhereRegionPredicate),
760 /// An equality predicate (unsupported).
761 EqPredicate(WhereEqPredicate),
764 impl WherePredicate {
765 pub fn span(&self) -> Span {
767 &WherePredicate::BoundPredicate(ref p) => p.span,
768 &WherePredicate::RegionPredicate(ref p) => p.span,
769 &WherePredicate::EqPredicate(ref p) => p.span,
774 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
775 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
776 pub struct WhereBoundPredicate {
778 /// Any generics from a `for` binding.
779 pub bound_generic_params: HirVec<GenericParam>,
780 /// The type being bounded.
781 pub bounded_ty: P<Ty>,
782 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
783 pub bounds: GenericBounds,
786 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
787 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
788 pub struct WhereRegionPredicate {
790 pub lifetime: Lifetime,
791 pub bounds: GenericBounds,
794 /// An equality predicate (e.g., `T = int`); currently unsupported.
795 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
796 pub struct WhereEqPredicate {
803 #[derive(RustcEncodable, RustcDecodable, Debug)]
804 pub struct ModuleItems {
805 // Use BTreeSets here so items are in the same order as in the
806 // list of all items in Crate
807 pub items: BTreeSet<HirId>,
808 pub trait_items: BTreeSet<TraitItemId>,
809 pub impl_items: BTreeSet<ImplItemId>,
812 /// The top-level data structure that stores the entire contents of
813 /// the crate currently being compiled.
815 /// For more details, see the [rustc guide].
817 /// [rustc guide]: https://rust-lang.github.io/rustc-guide/hir.html
818 #[derive(RustcEncodable, RustcDecodable, Debug)]
821 pub attrs: HirVec<Attribute>,
823 pub exported_macros: HirVec<MacroDef>,
824 // Attributes from non-exported macros, kept only for collecting the library feature list.
825 pub non_exported_macro_attrs: HirVec<Attribute>,
827 // N.B., we use a `BTreeMap` here so that `visit_all_items` iterates
828 // over the ids in increasing order. In principle it should not
829 // matter what order we visit things in, but in *practice* it
830 // does, because it can affect the order in which errors are
831 // detected, which in turn can make compile-fail tests yield
832 // slightly different results.
833 pub items: BTreeMap<HirId, Item>,
835 pub trait_items: BTreeMap<TraitItemId, TraitItem>,
836 pub impl_items: BTreeMap<ImplItemId, ImplItem>,
837 pub bodies: BTreeMap<BodyId, Body>,
838 pub trait_impls: BTreeMap<DefId, Vec<HirId>>,
840 /// A list of the body ids written out in the order in which they
841 /// appear in the crate. If you're going to process all the bodies
842 /// in the crate, you should iterate over this list rather than the keys
844 pub body_ids: Vec<BodyId>,
846 /// A list of modules written out in the order in which they
847 /// appear in the crate. This includes the main crate module.
848 pub modules: BTreeMap<HirId, ModuleItems>,
852 pub fn item(&self, id: HirId) -> &Item {
856 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem {
857 &self.trait_items[&id]
860 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem {
861 &self.impl_items[&id]
864 /// Visits all items in the crate in some deterministic (but
865 /// unspecified) order. If you just need to process every item,
866 /// but don't care about nesting, this method is the best choice.
868 /// If you do care about nesting -- usually because your algorithm
869 /// follows lexical scoping rules -- then you want a different
870 /// approach. You should override `visit_nested_item` in your
871 /// visitor and then call `intravisit::walk_crate` instead.
872 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
873 where V: itemlikevisit::ItemLikeVisitor<'hir>
875 for (_, item) in &self.items {
876 visitor.visit_item(item);
879 for (_, trait_item) in &self.trait_items {
880 visitor.visit_trait_item(trait_item);
883 for (_, impl_item) in &self.impl_items {
884 visitor.visit_impl_item(impl_item);
888 /// A parallel version of `visit_all_item_likes`.
889 pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
890 where V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send
893 par_for_each_in(&self.items, |(_, item)| {
894 visitor.visit_item(item);
897 par_for_each_in(&self.trait_items, |(_, trait_item)| {
898 visitor.visit_trait_item(trait_item);
901 par_for_each_in(&self.impl_items, |(_, impl_item)| {
902 visitor.visit_impl_item(impl_item);
907 pub fn body(&self, id: BodyId) -> &Body {
912 /// A macro definition, in this crate or imported from another.
914 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
915 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
916 pub struct MacroDef {
919 pub attrs: HirVec<Attribute>,
922 pub body: TokenStream,
926 /// A block of statements `{ .. }`, which may have a label (in this case the
927 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
928 /// the `rules` being anything but `DefaultBlock`.
929 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
931 /// Statements in a block.
932 pub stmts: HirVec<Stmt>,
933 /// An expression at the end of the block
934 /// without a semicolon, if any.
935 pub expr: Option<P<Expr>>,
936 #[stable_hasher(ignore)]
938 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
939 pub rules: BlockCheckMode,
941 /// If true, then there may exist `break 'a` values that aim to
942 /// break out of this block early.
943 /// Used by `'label: {}` blocks and by `try {}` blocks.
944 pub targeted_by_break: bool,
947 #[derive(RustcEncodable, RustcDecodable, HashStable)]
949 #[stable_hasher(ignore)]
955 impl fmt::Debug for Pat {
956 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
957 write!(f, "pat({}: {})", self.hir_id,
958 print::to_string(print::NO_ANN, |s| s.print_pat(self)))
963 // FIXME(#19596) this is a workaround, but there should be a better way
964 fn walk_short_(&self, it: &mut impl FnMut(&Pat) -> bool) -> bool {
971 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
972 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
973 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
974 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
975 Slice(before, slice, after) => {
979 .all(|p| p.walk_short_(it))
984 /// Walk the pattern in left-to-right order,
985 /// short circuiting (with `.all(..)`) if `false` is returned.
987 /// Note that when visiting e.g. `Tuple(ps)`,
988 /// if visiting `ps[0]` returns `false`,
989 /// then `ps[1]` will not be visited.
990 pub fn walk_short(&self, mut it: impl FnMut(&Pat) -> bool) -> bool {
991 self.walk_short_(&mut it)
994 // FIXME(#19596) this is a workaround, but there should be a better way
995 fn walk_(&self, it: &mut impl FnMut(&Pat) -> bool) {
1002 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {},
1003 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
1004 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
1005 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
1006 Slice(before, slice, after) => {
1008 .chain(slice.iter())
1009 .chain(after.iter())
1010 .for_each(|p| p.walk_(it))
1015 /// Walk the pattern in left-to-right order.
1017 /// If `it(pat)` returns `false`, the children are not visited.
1018 pub fn walk(&self, mut it: impl FnMut(&Pat) -> bool) {
1023 /// A single field in a struct pattern.
1025 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
1026 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
1027 /// except `is_shorthand` is true.
1028 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1029 pub struct FieldPat {
1030 #[stable_hasher(ignore)]
1032 /// The identifier for the field.
1033 #[stable_hasher(project(name))]
1035 /// The pattern the field is destructured to.
1037 pub is_shorthand: bool,
1041 /// Explicit binding annotations given in the HIR for a binding. Note
1042 /// that this is not the final binding *mode* that we infer after type
1044 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1045 pub enum BindingAnnotation {
1046 /// No binding annotation given: this means that the final binding mode
1047 /// will depend on whether we have skipped through a `&` reference
1048 /// when matching. For example, the `x` in `Some(x)` will have binding
1049 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
1050 /// ultimately be inferred to be by-reference.
1052 /// Note that implicit reference skipping is not implemented yet (#42640).
1055 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
1058 /// Annotated as `ref`, like `ref x`
1061 /// Annotated as `ref mut x`.
1065 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1071 impl fmt::Display for RangeEnd {
1072 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1073 f.write_str(match self {
1074 RangeEnd::Included => "..=",
1075 RangeEnd::Excluded => "..",
1080 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1082 /// Represents a wildcard pattern (i.e., `_`).
1085 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
1086 /// The `HirId` is the canonical ID for the variable being bound,
1087 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
1088 /// which is the pattern ID of the first `x`.
1089 Binding(BindingAnnotation, HirId, Ident, Option<P<Pat>>),
1091 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
1092 /// The `bool` is `true` in the presence of a `..`.
1093 Struct(QPath, HirVec<FieldPat>, bool),
1095 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
1096 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
1097 /// `0 <= position <= subpats.len()`
1098 TupleStruct(QPath, HirVec<P<Pat>>, Option<usize>),
1100 /// An or-pattern `A | B | C`.
1101 /// Invariant: `pats.len() >= 2`.
1104 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
1107 /// A tuple pattern (e.g., `(a, b)`).
1108 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
1109 /// `0 <= position <= subpats.len()`
1110 Tuple(HirVec<P<Pat>>, Option<usize>),
1112 /// A `box` pattern.
1115 /// A reference pattern (e.g., `&mut (a, b)`).
1116 Ref(P<Pat>, Mutability),
1121 /// A range pattern (e.g., `1..=2` or `1..2`).
1122 Range(P<Expr>, P<Expr>, RangeEnd),
1124 /// `[a, b, ..i, y, z]` is represented as:
1125 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`.
1126 Slice(HirVec<P<Pat>>, Option<P<Pat>>, HirVec<P<Pat>>),
1129 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1130 pub enum BinOpKind {
1131 /// The `+` operator (addition).
1133 /// The `-` operator (subtraction).
1135 /// The `*` operator (multiplication).
1137 /// The `/` operator (division).
1139 /// The `%` operator (modulus).
1141 /// The `&&` operator (logical and).
1143 /// The `||` operator (logical or).
1145 /// The `^` operator (bitwise xor).
1147 /// The `&` operator (bitwise and).
1149 /// The `|` operator (bitwise or).
1151 /// The `<<` operator (shift left).
1153 /// The `>>` operator (shift right).
1155 /// The `==` operator (equality).
1157 /// The `<` operator (less than).
1159 /// The `<=` operator (less than or equal to).
1161 /// The `!=` operator (not equal to).
1163 /// The `>=` operator (greater than or equal to).
1165 /// The `>` operator (greater than).
1170 pub fn as_str(self) -> &'static str {
1172 BinOpKind::Add => "+",
1173 BinOpKind::Sub => "-",
1174 BinOpKind::Mul => "*",
1175 BinOpKind::Div => "/",
1176 BinOpKind::Rem => "%",
1177 BinOpKind::And => "&&",
1178 BinOpKind::Or => "||",
1179 BinOpKind::BitXor => "^",
1180 BinOpKind::BitAnd => "&",
1181 BinOpKind::BitOr => "|",
1182 BinOpKind::Shl => "<<",
1183 BinOpKind::Shr => ">>",
1184 BinOpKind::Eq => "==",
1185 BinOpKind::Lt => "<",
1186 BinOpKind::Le => "<=",
1187 BinOpKind::Ne => "!=",
1188 BinOpKind::Ge => ">=",
1189 BinOpKind::Gt => ">",
1193 pub fn is_lazy(self) -> bool {
1195 BinOpKind::And | BinOpKind::Or => true,
1200 pub fn is_shift(self) -> bool {
1202 BinOpKind::Shl | BinOpKind::Shr => true,
1207 pub fn is_comparison(self) -> bool {
1214 BinOpKind::Ge => true,
1226 BinOpKind::Shr => false,
1230 /// Returns `true` if the binary operator takes its arguments by value.
1231 pub fn is_by_value(self) -> bool {
1232 !self.is_comparison()
1236 impl Into<ast::BinOpKind> for BinOpKind {
1237 fn into(self) -> ast::BinOpKind {
1239 BinOpKind::Add => ast::BinOpKind::Add,
1240 BinOpKind::Sub => ast::BinOpKind::Sub,
1241 BinOpKind::Mul => ast::BinOpKind::Mul,
1242 BinOpKind::Div => ast::BinOpKind::Div,
1243 BinOpKind::Rem => ast::BinOpKind::Rem,
1244 BinOpKind::And => ast::BinOpKind::And,
1245 BinOpKind::Or => ast::BinOpKind::Or,
1246 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1247 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1248 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1249 BinOpKind::Shl => ast::BinOpKind::Shl,
1250 BinOpKind::Shr => ast::BinOpKind::Shr,
1251 BinOpKind::Eq => ast::BinOpKind::Eq,
1252 BinOpKind::Lt => ast::BinOpKind::Lt,
1253 BinOpKind::Le => ast::BinOpKind::Le,
1254 BinOpKind::Ne => ast::BinOpKind::Ne,
1255 BinOpKind::Ge => ast::BinOpKind::Ge,
1256 BinOpKind::Gt => ast::BinOpKind::Gt,
1261 pub type BinOp = Spanned<BinOpKind>;
1263 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1265 /// The `*` operator (deferencing).
1267 /// The `!` operator (logical negation).
1269 /// The `-` operator (negation).
1274 pub fn as_str(self) -> &'static str {
1282 /// Returns `true` if the unary operator takes its argument by value.
1283 pub fn is_by_value(self) -> bool {
1285 UnNeg | UnNot => true,
1292 #[derive(RustcEncodable, RustcDecodable, HashStable)]
1299 impl fmt::Debug for Stmt {
1300 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1301 write!(f, "stmt({}: {})", self.hir_id,
1302 print::to_string(print::NO_ANN, |s| s.print_stmt(self)))
1306 /// The contents of a statement.
1307 #[derive(RustcEncodable, RustcDecodable, HashStable)]
1309 /// A local (`let`) binding.
1312 /// An item binding.
1315 /// An expression without a trailing semi-colon (must have unit type).
1318 /// An expression with a trailing semi-colon (may have any type).
1323 pub fn attrs(&self) -> &[Attribute] {
1325 StmtKind::Local(ref l) => &l.attrs,
1326 StmtKind::Item(_) => &[],
1327 StmtKind::Expr(ref e) |
1328 StmtKind::Semi(ref e) => &e.attrs,
1333 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1334 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1337 /// Type annotation, if any (otherwise the type will be inferred).
1338 pub ty: Option<P<Ty>>,
1339 /// Initializer expression to set the value, if any.
1340 pub init: Option<P<Expr>>,
1343 pub attrs: ThinVec<Attribute>,
1344 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1345 /// desugaring. Otherwise will be `Normal`.
1346 pub source: LocalSource,
1349 /// Represents a single arm of a `match` expression, e.g.
1350 /// `<pat> (if <guard>) => <body>`.
1351 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1353 #[stable_hasher(ignore)]
1356 pub attrs: HirVec<Attribute>,
1357 /// If this pattern and the optional guard matches, then `body` is evaluated.
1359 /// Optional guard clause.
1360 pub guard: Option<Guard>,
1361 /// The expression the arm evaluates to if this arm matches.
1365 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1370 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1372 #[stable_hasher(ignore)]
1377 pub is_shorthand: bool,
1380 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1381 pub enum BlockCheckMode {
1383 UnsafeBlock(UnsafeSource),
1384 PushUnsafeBlock(UnsafeSource),
1385 PopUnsafeBlock(UnsafeSource),
1388 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1389 pub enum UnsafeSource {
1394 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1399 /// The body of a function, closure, or constant value. In the case of
1400 /// a function, the body contains not only the function body itself
1401 /// (which is an expression), but also the argument patterns, since
1402 /// those are something that the caller doesn't really care about.
1407 /// fn foo((x, y): (u32, u32)) -> u32 {
1412 /// Here, the `Body` associated with `foo()` would contain:
1414 /// - an `params` array containing the `(x, y)` pattern
1415 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1416 /// - `generator_kind` would be `None`
1418 /// All bodies have an **owner**, which can be accessed via the HIR
1419 /// map using `body_owner_def_id()`.
1420 #[derive(RustcEncodable, RustcDecodable, Debug)]
1422 pub params: HirVec<Param>,
1424 pub generator_kind: Option<GeneratorKind>,
1428 pub fn id(&self) -> BodyId {
1430 hir_id: self.value.hir_id,
1434 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1439 /// The type of source expression that caused this generator to be created.
1440 #[derive(Clone, PartialEq, Eq, HashStable, RustcEncodable, RustcDecodable, Debug, Copy)]
1441 pub enum GeneratorKind {
1442 /// An explicit `async` block or the body of an async function.
1443 Async(AsyncGeneratorKind),
1445 /// A generator literal created via a `yield` inside a closure.
1449 impl fmt::Display for GeneratorKind {
1450 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1452 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1453 GeneratorKind::Gen => f.write_str("generator"),
1458 /// In the case of a generator created as part of an async construct,
1459 /// which kind of async construct caused it to be created?
1461 /// This helps error messages but is also used to drive coercions in
1462 /// type-checking (see #60424).
1463 #[derive(Clone, PartialEq, Eq, HashStable, RustcEncodable, RustcDecodable, Debug, Copy)]
1464 pub enum AsyncGeneratorKind {
1465 /// An explicit `async` block written by the user.
1468 /// An explicit `async` block written by the user.
1471 /// The `async` block generated as the body of an async function.
1475 impl fmt::Display for AsyncGeneratorKind {
1476 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1477 f.write_str(match self {
1478 AsyncGeneratorKind::Block => "`async` block",
1479 AsyncGeneratorKind::Closure => "`async` closure body",
1480 AsyncGeneratorKind::Fn => "`async fn` body",
1485 #[derive(Copy, Clone, Debug)]
1486 pub enum BodyOwnerKind {
1487 /// Functions and methods.
1493 /// Constants and associated constants.
1496 /// Initializer of a `static` item.
1500 impl BodyOwnerKind {
1501 pub fn is_fn_or_closure(self) -> bool {
1503 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1504 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1510 pub type Lit = Spanned<LitKind>;
1512 /// A constant (expression) that's not an item or associated item,
1513 /// but needs its own `DefId` for type-checking, const-eval, etc.
1514 /// These are usually found nested inside types (e.g., array lengths)
1515 /// or expressions (e.g., repeat counts), and also used to define
1516 /// explicit discriminant values for enum variants.
1517 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1518 pub struct AnonConst {
1524 #[derive(RustcEncodable, RustcDecodable)]
1528 pub attrs: ThinVec<Attribute>,
1532 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1533 #[cfg(target_arch = "x86_64")]
1534 static_assert_size!(Expr, 64);
1537 pub fn precedence(&self) -> ExprPrecedence {
1539 ExprKind::Box(_) => ExprPrecedence::Box,
1540 ExprKind::Array(_) => ExprPrecedence::Array,
1541 ExprKind::Call(..) => ExprPrecedence::Call,
1542 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1543 ExprKind::Tup(_) => ExprPrecedence::Tup,
1544 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1545 ExprKind::Unary(..) => ExprPrecedence::Unary,
1546 ExprKind::Lit(_) => ExprPrecedence::Lit,
1547 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1548 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1549 ExprKind::Loop(..) => ExprPrecedence::Loop,
1550 ExprKind::Match(..) => ExprPrecedence::Match,
1551 ExprKind::Closure(..) => ExprPrecedence::Closure,
1552 ExprKind::Block(..) => ExprPrecedence::Block,
1553 ExprKind::Assign(..) => ExprPrecedence::Assign,
1554 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1555 ExprKind::Field(..) => ExprPrecedence::Field,
1556 ExprKind::Index(..) => ExprPrecedence::Index,
1557 ExprKind::Path(..) => ExprPrecedence::Path,
1558 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1559 ExprKind::Break(..) => ExprPrecedence::Break,
1560 ExprKind::Continue(..) => ExprPrecedence::Continue,
1561 ExprKind::Ret(..) => ExprPrecedence::Ret,
1562 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1563 ExprKind::Struct(..) => ExprPrecedence::Struct,
1564 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1565 ExprKind::Yield(..) => ExprPrecedence::Yield,
1566 ExprKind::Err => ExprPrecedence::Err,
1570 // Whether this looks like a place expr, without checking for deref
1572 // This will return `true` in some potentially surprising cases such as
1573 // `CONSTANT.field`.
1574 pub fn is_syntactic_place_expr(&self) -> bool {
1575 self.is_place_expr(|_| true)
1578 // Whether this is a place expression.
1579 // `allow_projections_from` should return `true` if indexing a field or
1580 // index expression based on the given expression should be considered a
1581 // place expression.
1582 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1584 ExprKind::Path(QPath::Resolved(_, ref path)) => {
1587 | Res::Def(DefKind::Static, _)
1593 // Type ascription inherits its place expression kind from its
1595 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1596 ExprKind::Type(ref e, _) => {
1597 e.is_place_expr(allow_projections_from)
1600 ExprKind::Unary(UnDeref, _) => true,
1602 ExprKind::Field(ref base, _) |
1603 ExprKind::Index(ref base, _) => {
1604 allow_projections_from(base)
1605 || base.is_place_expr(allow_projections_from)
1608 // Partially qualified paths in expressions can only legally
1609 // refer to associated items which are always rvalues.
1610 ExprKind::Path(QPath::TypeRelative(..)) |
1612 ExprKind::Call(..) |
1613 ExprKind::MethodCall(..) |
1614 ExprKind::Struct(..) |
1616 ExprKind::Match(..) |
1617 ExprKind::Closure(..) |
1618 ExprKind::Block(..) |
1619 ExprKind::Repeat(..) |
1620 ExprKind::Array(..) |
1621 ExprKind::Break(..) |
1622 ExprKind::Continue(..) |
1624 ExprKind::Loop(..) |
1625 ExprKind::Assign(..) |
1626 ExprKind::InlineAsm(..) |
1627 ExprKind::AssignOp(..) |
1629 ExprKind::Unary(..) |
1631 ExprKind::AddrOf(..) |
1632 ExprKind::Binary(..) |
1633 ExprKind::Yield(..) |
1634 ExprKind::Cast(..) |
1635 ExprKind::DropTemps(..) |
1642 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1643 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1644 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1645 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1646 /// beyond remembering to call this function before doing analysis on it.
1647 pub fn peel_drop_temps(&self) -> &Self {
1648 let mut expr = self;
1649 while let ExprKind::DropTemps(inner) = &expr.kind {
1656 impl fmt::Debug for Expr {
1657 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1658 write!(f, "expr({}: {})", self.hir_id,
1659 print::to_string(print::NO_ANN, |s| s.print_expr(self)))
1663 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1665 /// A `box x` expression.
1667 /// An array (e.g., `[a, b, c, d]`).
1668 Array(HirVec<Expr>),
1669 /// A function call.
1671 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1672 /// and the second field is the list of arguments.
1673 /// This also represents calling the constructor of
1674 /// tuple-like ADTs such as tuple structs and enum variants.
1675 Call(P<Expr>, HirVec<Expr>),
1676 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1678 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1679 /// (within the angle brackets).
1680 /// The first element of the vector of `Expr`s is the expression that evaluates
1681 /// to the object on which the method is being called on (the receiver),
1682 /// and the remaining elements are the rest of the arguments.
1683 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1684 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1686 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1687 /// the `hir_id` of the `MethodCall` node itself.
1689 /// [`type_dependent_def_id`]: ../ty/struct.TypeckTables.html#method.type_dependent_def_id
1690 MethodCall(P<PathSegment>, Span, HirVec<Expr>),
1691 /// A tuple (e.g., `(a, b, c, d)`).
1693 /// A binary operation (e.g., `a + b`, `a * b`).
1694 Binary(BinOp, P<Expr>, P<Expr>),
1695 /// A unary operation (e.g., `!x`, `*x`).
1696 Unary(UnOp, P<Expr>),
1697 /// A literal (e.g., `1`, `"foo"`).
1699 /// A cast (e.g., `foo as f64`).
1700 Cast(P<Expr>, P<Ty>),
1701 /// A type reference (e.g., `Foo`).
1702 Type(P<Expr>, P<Ty>),
1703 /// Wraps the expression in a terminating scope.
1704 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1706 /// This construct only exists to tweak the drop order in HIR lowering.
1707 /// An example of that is the desugaring of `for` loops.
1709 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1711 /// I.e., `'label: loop { <block> }`.
1712 Loop(P<Block>, Option<Label>, LoopSource),
1713 /// A `match` block, with a source that indicates whether or not it is
1714 /// the result of a desugaring, and if so, which kind.
1715 Match(P<Expr>, HirVec<Arm>, MatchSource),
1716 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1718 /// The `Span` is the argument block `|...|`.
1720 /// This may also be a generator literal or an `async block` as indicated by the
1721 /// `Option<Movability>`.
1722 Closure(CaptureBy, P<FnDecl>, BodyId, Span, Option<Movability>),
1723 /// A block (e.g., `'label: { ... }`).
1724 Block(P<Block>, Option<Label>),
1726 /// An assignment (e.g., `a = foo()`).
1727 Assign(P<Expr>, P<Expr>),
1728 /// An assignment with an operator.
1731 AssignOp(BinOp, P<Expr>, P<Expr>),
1732 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1733 Field(P<Expr>, Ident),
1734 /// An indexing operation (`foo[2]`).
1735 Index(P<Expr>, P<Expr>),
1737 /// Path to a definition, possibly containing lifetime or type parameters.
1740 /// A referencing operation (i.e., `&a`, `&mut a`, `&raw const a`, or `&raw mut a`).
1741 AddrOf(BorrowKind, Mutability, P<Expr>),
1742 /// A `break`, with an optional label to break.
1743 Break(Destination, Option<P<Expr>>),
1744 /// A `continue`, with an optional label.
1745 Continue(Destination),
1746 /// A `return`, with an optional value to be returned.
1747 Ret(Option<P<Expr>>),
1749 /// Inline assembly (from `asm!`), with its outputs and inputs.
1750 InlineAsm(P<InlineAsm>),
1752 /// A struct or struct-like variant literal expression.
1754 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1755 /// where `base` is the `Option<Expr>`.
1756 Struct(P<QPath>, HirVec<Field>, Option<P<Expr>>),
1758 /// An array literal constructed from one repeated element.
1760 /// E.g., `[1; 5]`. The first expression is the element
1761 /// to be repeated; the second is the number of times to repeat it.
1762 Repeat(P<Expr>, AnonConst),
1764 /// A suspension point for generators (i.e., `yield <expr>`).
1765 Yield(P<Expr>, YieldSource),
1767 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1771 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1773 /// To resolve the path to a `DefId`, call [`qpath_res`].
1775 /// [`qpath_res`]: ../ty/struct.TypeckTables.html#method.qpath_res
1776 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1778 /// Path to a definition, optionally "fully-qualified" with a `Self`
1779 /// type, if the path points to an associated item in a trait.
1781 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1782 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1783 /// even though they both have the same two-segment `Clone::clone` `Path`.
1784 Resolved(Option<P<Ty>>, P<Path>),
1786 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1787 /// Will be resolved by type-checking to an associated item.
1789 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1790 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1791 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1792 TypeRelative(P<Ty>, P<PathSegment>)
1795 /// Hints at the original code for a let statement.
1796 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1797 pub enum LocalSource {
1798 /// A `match _ { .. }`.
1800 /// A desugared `for _ in _ { .. }` loop.
1802 /// When lowering async functions, we create locals within the `async move` so that
1803 /// all parameters are dropped after the future is polled.
1805 /// ```ignore (pseudo-Rust)
1806 /// async fn foo(<pattern> @ x: Type) {
1808 /// let <pattern> = x;
1813 /// A desugared `<expr>.await`.
1817 /// Hints at the original code for a `match _ { .. }`.
1818 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
1819 pub enum MatchSource {
1820 /// A `match _ { .. }`.
1822 /// An `if _ { .. }` (optionally with `else { .. }`).
1824 contains_else_clause: bool,
1826 /// An `if let _ = _ { .. }` (optionally with `else { .. }`).
1828 contains_else_clause: bool,
1830 /// A `while _ { .. }` (which was desugared to a `loop { match _ { .. } }`).
1832 /// A `while let _ = _ { .. }` (which was desugared to a
1833 /// `loop { match _ { .. } }`).
1835 /// A desugared `for _ in _ { .. }` loop.
1837 /// A desugared `?` operator.
1839 /// A desugared `<expr>.await`.
1844 pub fn name(self) -> &'static str {
1848 IfDesugar { .. } | IfLetDesugar { .. } => "if",
1849 WhileDesugar | WhileLetDesugar => "while",
1850 ForLoopDesugar => "for",
1852 AwaitDesugar => ".await",
1857 /// The loop type that yielded an `ExprKind::Loop`.
1858 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1859 pub enum LoopSource {
1860 /// A `loop { .. }` loop.
1862 /// A `while _ { .. }` loop.
1864 /// A `while let _ = _ { .. }` loop.
1866 /// A `for _ in _ { .. }` loop.
1871 pub fn name(self) -> &'static str {
1873 LoopSource::Loop => "loop",
1874 LoopSource::While | LoopSource::WhileLet => "while",
1875 LoopSource::ForLoop => "for",
1880 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1881 pub enum LoopIdError {
1883 UnlabeledCfInWhileCondition,
1887 impl fmt::Display for LoopIdError {
1888 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1889 f.write_str(match self {
1890 LoopIdError::OutsideLoopScope => "not inside loop scope",
1891 LoopIdError::UnlabeledCfInWhileCondition =>
1892 "unlabeled control flow (break or continue) in while condition",
1893 LoopIdError::UnresolvedLabel => "label not found",
1898 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1899 pub struct Destination {
1900 // This is `Some(_)` iff there is an explicit user-specified `label
1901 pub label: Option<Label>,
1903 // These errors are caught and then reported during the diagnostics pass in
1904 // librustc_passes/loops.rs
1905 pub target_id: Result<HirId, LoopIdError>,
1908 /// The yield kind that caused an `ExprKind::Yield`.
1909 #[derive(Copy, Clone, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable, HashStable)]
1910 pub enum YieldSource {
1911 /// An `<expr>.await`.
1913 /// A plain `yield`.
1917 impl fmt::Display for YieldSource {
1918 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1919 f.write_str(match self {
1920 YieldSource::Await => "`await`",
1921 YieldSource::Yield => "`yield`",
1926 // N.B., if you change this, you'll probably want to change the corresponding
1927 // type structure in middle/ty.rs as well.
1928 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1931 pub mutbl: Mutability,
1934 /// Represents a function's signature in a trait declaration,
1935 /// trait implementation, or a free function.
1936 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1938 pub header: FnHeader,
1939 pub decl: P<FnDecl>,
1942 // The bodies for items are stored "out of line", in a separate
1943 // hashmap in the `Crate`. Here we just record the node-id of the item
1944 // so it can fetched later.
1945 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1946 pub struct TraitItemId {
1950 /// Represents an item declaration within a trait declaration,
1951 /// possibly including a default implementation. A trait item is
1952 /// either required (meaning it doesn't have an implementation, just a
1953 /// signature) or provided (meaning it has a default implementation).
1954 #[derive(RustcEncodable, RustcDecodable, Debug)]
1955 pub struct TraitItem {
1958 pub attrs: HirVec<Attribute>,
1959 pub generics: Generics,
1960 pub kind: TraitItemKind,
1964 /// Represents a trait method's body (or just argument names).
1965 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1966 pub enum TraitMethod {
1967 /// No default body in the trait, just a signature.
1968 Required(HirVec<Ident>),
1970 /// Both signature and body are provided in the trait.
1974 /// Represents a trait method or associated constant or type
1975 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1976 pub enum TraitItemKind {
1977 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
1978 Const(P<Ty>, Option<BodyId>),
1979 /// A method with an optional body.
1980 Method(FnSig, TraitMethod),
1981 /// An associated type with (possibly empty) bounds and optional concrete
1983 Type(GenericBounds, Option<P<Ty>>),
1986 // The bodies for items are stored "out of line", in a separate
1987 // hashmap in the `Crate`. Here we just record the node-id of the item
1988 // so it can fetched later.
1989 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1990 pub struct ImplItemId {
1994 /// Represents anything within an `impl` block.
1995 #[derive(RustcEncodable, RustcDecodable, Debug)]
1996 pub struct ImplItem {
1999 pub vis: Visibility,
2000 pub defaultness: Defaultness,
2001 pub attrs: HirVec<Attribute>,
2002 pub generics: Generics,
2003 pub kind: ImplItemKind,
2007 /// Represents various kinds of content within an `impl`.
2008 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2009 pub enum ImplItemKind {
2010 /// An associated constant of the given type, set to the constant result
2011 /// of the expression.
2012 Const(P<Ty>, BodyId),
2013 /// A method implementation with the given signature and body.
2014 Method(FnSig, BodyId),
2015 /// An associated type.
2017 /// An associated `type = impl Trait`.
2018 OpaqueTy(GenericBounds),
2021 /// Bind a type to an associated type (i.e., `A = Foo`).
2023 /// Bindings like `A: Debug` are represented as a special type `A =
2024 /// $::Debug` that is understood by the astconv code.
2026 /// FIXME(alexreg): why have a separate type for the binding case,
2027 /// wouldn't it be better to make the `ty` field an enum like the
2031 /// enum TypeBindingKind {
2036 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2037 pub struct TypeBinding {
2039 #[stable_hasher(project(name))]
2041 pub kind: TypeBindingKind,
2045 // Represents the two kinds of type bindings.
2046 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2047 pub enum TypeBindingKind {
2048 /// E.g., `Foo<Bar: Send>`.
2050 bounds: HirVec<GenericBound>,
2052 /// E.g., `Foo<Bar = ()>`.
2059 pub fn ty(&self) -> &Ty {
2061 TypeBindingKind::Equality { ref ty } => ty,
2062 _ => bug!("expected equality type binding for parenthesized generic args"),
2067 #[derive(RustcEncodable, RustcDecodable)]
2074 impl fmt::Debug for Ty {
2075 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2076 write!(f, "type({})",
2077 print::to_string(print::NO_ANN, |s| s.print_type(self)))
2081 /// Not represented directly in the AST; referred to by name through a `ty_path`.
2082 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
2092 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2093 pub struct BareFnTy {
2094 pub unsafety: Unsafety,
2096 pub generic_params: HirVec<GenericParam>,
2097 pub decl: P<FnDecl>,
2098 pub param_names: HirVec<Ident>,
2101 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2102 pub struct OpaqueTy {
2103 pub generics: Generics,
2104 pub bounds: GenericBounds,
2105 pub impl_trait_fn: Option<DefId>,
2106 pub origin: OpaqueTyOrigin,
2109 /// From whence the opaque type came.
2110 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2111 pub enum OpaqueTyOrigin {
2112 /// `type Foo = impl Trait;`
2120 /// The various kinds of types recognized by the compiler.
2121 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2123 /// A variable length slice (i.e., `[T]`).
2125 /// A fixed length array (i.e., `[T; n]`).
2126 Array(P<Ty>, AnonConst),
2127 /// A raw pointer (i.e., `*const T` or `*mut T`).
2129 /// A reference (i.e., `&'a T` or `&'a mut T`).
2130 Rptr(Lifetime, MutTy),
2131 /// A bare function (e.g., `fn(usize) -> bool`).
2132 BareFn(P<BareFnTy>),
2133 /// The never type (`!`).
2135 /// A tuple (`(A, B, C, D, ...)`).
2137 /// A path to a type definition (`module::module::...::Type`), or an
2138 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2140 /// Type parameters may be stored in each `PathSegment`.
2142 /// A type definition itself. This is currently only used for the `type Foo = impl Trait`
2143 /// item that `impl Trait` in return position desugars to.
2145 /// The generic argument list contains the lifetimes (and in the future possibly parameters)
2146 /// that are actually bound on the `impl Trait`.
2147 Def(ItemId, HirVec<GenericArg>),
2148 /// A trait object type `Bound1 + Bound2 + Bound3`
2149 /// where `Bound` is a trait or a lifetime.
2150 TraitObject(HirVec<PolyTraitRef>, Lifetime),
2153 /// `TyKind::Infer` means the type should be inferred instead of it having been
2154 /// specified. This can appear anywhere in a type.
2156 /// Placeholder for a type that has failed to be defined.
2160 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable, PartialEq)]
2161 pub struct InlineAsmOutput {
2162 pub constraint: Symbol,
2164 pub is_indirect: bool,
2168 // NOTE(eddyb) This is used within MIR as well, so unlike the rest of the HIR,
2169 // it needs to be `Clone` and use plain `Vec<T>` instead of `HirVec<T>`.
2170 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable, PartialEq)]
2171 pub struct InlineAsmInner {
2173 pub asm_str_style: StrStyle,
2174 pub outputs: Vec<InlineAsmOutput>,
2175 pub inputs: Vec<Symbol>,
2176 pub clobbers: Vec<Symbol>,
2178 pub alignstack: bool,
2179 pub dialect: AsmDialect,
2182 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2183 pub struct InlineAsm {
2184 pub inner: InlineAsmInner,
2185 pub outputs_exprs: HirVec<Expr>,
2186 pub inputs_exprs: HirVec<Expr>,
2189 /// Represents a parameter in a function header.
2190 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2192 pub attrs: HirVec<Attribute>,
2198 /// Represents the header (not the body) of a function declaration.
2199 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2201 /// The types of the function's parameters.
2203 /// Additional argument data is stored in the function's [body](Body::parameters).
2204 pub inputs: HirVec<Ty>,
2205 pub output: FunctionRetTy,
2206 pub c_variadic: bool,
2207 /// Does the function have an implicit self?
2208 pub implicit_self: ImplicitSelfKind,
2211 /// Represents what type of implicit self a function has, if any.
2212 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2213 pub enum ImplicitSelfKind {
2214 /// Represents a `fn x(self);`.
2216 /// Represents a `fn x(mut self);`.
2218 /// Represents a `fn x(&self);`.
2220 /// Represents a `fn x(&mut self);`.
2222 /// Represents when a function does not have a self argument or
2223 /// when a function has a `self: X` argument.
2227 impl ImplicitSelfKind {
2228 /// Does this represent an implicit self?
2229 pub fn has_implicit_self(&self) -> bool {
2231 ImplicitSelfKind::None => false,
2237 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, HashStable,
2238 Ord, RustcEncodable, RustcDecodable, Debug)]
2244 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2245 pub enum Defaultness {
2246 Default { has_value: bool },
2251 pub fn has_value(&self) -> bool {
2253 Defaultness::Default { has_value, .. } => has_value,
2254 Defaultness::Final => true,
2258 pub fn is_final(&self) -> bool {
2259 *self == Defaultness::Final
2262 pub fn is_default(&self) -> bool {
2264 Defaultness::Default { .. } => true,
2270 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2271 pub enum FunctionRetTy {
2272 /// Return type is not specified.
2274 /// Functions default to `()` and
2275 /// closures default to inference. Span points to where return
2276 /// type would be inserted.
2277 DefaultReturn(Span),
2278 /// Everything else.
2282 impl fmt::Display for FunctionRetTy {
2283 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2285 Return(ref ty) => print::to_string(print::NO_ANN, |s| s.print_type(ty)).fmt(f),
2286 DefaultReturn(_) => "()".fmt(f),
2291 impl FunctionRetTy {
2292 pub fn span(&self) -> Span {
2294 DefaultReturn(span) => span,
2295 Return(ref ty) => ty.span,
2300 #[derive(RustcEncodable, RustcDecodable, Debug)]
2302 /// A span from the first token past `{` to the last token until `}`.
2303 /// For `mod foo;`, the inner span ranges from the first token
2304 /// to the last token in the external file.
2306 pub item_ids: HirVec<ItemId>,
2309 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2310 pub struct ForeignMod {
2312 pub items: HirVec<ForeignItem>,
2315 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2316 pub struct GlobalAsm {
2320 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2321 pub struct EnumDef {
2322 pub variants: HirVec<Variant>,
2325 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2326 pub struct Variant {
2327 /// Name of the variant.
2328 #[stable_hasher(project(name))]
2330 /// Attributes of the variant.
2331 pub attrs: HirVec<Attribute>,
2332 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2334 /// Fields and constructor id of the variant.
2335 pub data: VariantData,
2336 /// Explicit discriminant (e.g., `Foo = 1`).
2337 pub disr_expr: Option<AnonConst>,
2342 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2344 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2345 /// Also produced for each element of a list `use`, e.g.
2346 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2349 /// Glob import, e.g., `use foo::*`.
2352 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2353 /// an additional `use foo::{}` for performing checks such as
2354 /// unstable feature gating. May be removed in the future.
2358 /// References to traits in impls.
2360 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2361 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2362 /// trait being referred to but just a unique `HirId` that serves as a key
2363 /// within the resolution map.
2364 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2365 pub struct TraitRef {
2367 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2368 #[stable_hasher(ignore)]
2369 pub hir_ref_id: HirId,
2373 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2374 pub fn trait_def_id(&self) -> DefId {
2375 match self.path.res {
2376 Res::Def(DefKind::Trait, did) => did,
2377 Res::Def(DefKind::TraitAlias, did) => did,
2381 _ => unreachable!(),
2386 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2387 pub struct PolyTraitRef {
2388 /// The `'a` in `<'a> Foo<&'a T>`.
2389 pub bound_generic_params: HirVec<GenericParam>,
2391 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2392 pub trait_ref: TraitRef,
2397 pub type Visibility = Spanned<VisibilityKind>;
2399 #[derive(RustcEncodable, RustcDecodable, Debug)]
2400 pub enum VisibilityKind {
2403 Restricted { path: P<Path>, hir_id: HirId },
2407 impl VisibilityKind {
2408 pub fn is_pub(&self) -> bool {
2410 VisibilityKind::Public => true,
2415 pub fn is_pub_restricted(&self) -> bool {
2417 VisibilityKind::Public |
2418 VisibilityKind::Inherited => false,
2419 VisibilityKind::Crate(..) |
2420 VisibilityKind::Restricted { .. } => true,
2424 pub fn descr(&self) -> &'static str {
2426 VisibilityKind::Public => "public",
2427 VisibilityKind::Inherited => "private",
2428 VisibilityKind::Crate(..) => "crate-visible",
2429 VisibilityKind::Restricted { .. } => "restricted",
2434 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2435 pub struct StructField {
2437 #[stable_hasher(project(name))]
2439 pub vis: Visibility,
2442 pub attrs: HirVec<Attribute>,
2446 // Still necessary in couple of places
2447 pub fn is_positional(&self) -> bool {
2448 let first = self.ident.as_str().as_bytes()[0];
2449 first >= b'0' && first <= b'9'
2453 /// Fields and constructor IDs of enum variants and structs.
2454 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2455 pub enum VariantData {
2456 /// A struct variant.
2458 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2459 Struct(HirVec<StructField>, /* recovered */ bool),
2460 /// A tuple variant.
2462 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2463 Tuple(HirVec<StructField>, HirId),
2466 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2471 /// Return the fields of this variant.
2472 pub fn fields(&self) -> &[StructField] {
2474 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2479 /// Return the `HirId` of this variant's constructor, if it has one.
2480 pub fn ctor_hir_id(&self) -> Option<HirId> {
2482 VariantData::Struct(_, _) => None,
2483 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2488 // The bodies for items are stored "out of line", in a separate
2489 // hashmap in the `Crate`. Here we just record the node-id of the item
2490 // so it can fetched later.
2491 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2498 /// The name might be a dummy name in case of anonymous items
2499 #[derive(RustcEncodable, RustcDecodable, Debug)]
2503 pub attrs: HirVec<Attribute>,
2505 pub vis: Visibility,
2509 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2510 pub struct FnHeader {
2511 pub unsafety: Unsafety,
2512 pub constness: Constness,
2513 pub asyncness: IsAsync,
2518 pub fn is_const(&self) -> bool {
2519 match &self.constness {
2520 Constness::Const => true,
2526 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2528 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2530 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2531 ExternCrate(Option<Name>),
2533 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2537 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2538 Use(P<Path>, UseKind),
2540 /// A `static` item.
2541 Static(P<Ty>, Mutability, BodyId),
2543 Const(P<Ty>, BodyId),
2544 /// A function declaration.
2545 Fn(FnSig, Generics, BodyId),
2548 /// An external module, e.g. `extern { .. }`.
2549 ForeignMod(ForeignMod),
2550 /// Module-level inline assembly (from `global_asm!`).
2551 GlobalAsm(P<GlobalAsm>),
2552 /// A type alias, e.g., `type Foo = Bar<u8>`.
2553 TyAlias(P<Ty>, Generics),
2554 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2556 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2557 Enum(EnumDef, Generics),
2558 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2559 Struct(VariantData, Generics),
2560 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2561 Union(VariantData, Generics),
2562 /// A trait definition.
2563 Trait(IsAuto, Unsafety, Generics, GenericBounds, HirVec<TraitItemRef>),
2565 TraitAlias(Generics, GenericBounds),
2567 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2572 Option<TraitRef>, // (optional) trait this impl implements
2574 HirVec<ImplItemRef>),
2578 pub fn descriptive_variant(&self) -> &str {
2580 ItemKind::ExternCrate(..) => "extern crate",
2581 ItemKind::Use(..) => "use",
2582 ItemKind::Static(..) => "static item",
2583 ItemKind::Const(..) => "constant item",
2584 ItemKind::Fn(..) => "function",
2585 ItemKind::Mod(..) => "module",
2586 ItemKind::ForeignMod(..) => "foreign module",
2587 ItemKind::GlobalAsm(..) => "global asm",
2588 ItemKind::TyAlias(..) => "type alias",
2589 ItemKind::OpaqueTy(..) => "opaque type",
2590 ItemKind::Enum(..) => "enum",
2591 ItemKind::Struct(..) => "struct",
2592 ItemKind::Union(..) => "union",
2593 ItemKind::Trait(..) => "trait",
2594 ItemKind::TraitAlias(..) => "trait alias",
2595 ItemKind::Impl(..) => "impl",
2599 pub fn adt_kind(&self) -> Option<AdtKind> {
2601 ItemKind::Struct(..) => Some(AdtKind::Struct),
2602 ItemKind::Union(..) => Some(AdtKind::Union),
2603 ItemKind::Enum(..) => Some(AdtKind::Enum),
2608 pub fn generics(&self) -> Option<&Generics> {
2610 ItemKind::Fn(_, ref generics, _) |
2611 ItemKind::TyAlias(_, ref generics) |
2612 ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. }) |
2613 ItemKind::Enum(_, ref generics) |
2614 ItemKind::Struct(_, ref generics) |
2615 ItemKind::Union(_, ref generics) |
2616 ItemKind::Trait(_, _, ref generics, _, _) |
2617 ItemKind::Impl(_, _, _, ref generics, _, _, _)=> generics,
2623 /// A reference from an trait to one of its associated items. This
2624 /// contains the item's id, naturally, but also the item's name and
2625 /// some other high-level details (like whether it is an associated
2626 /// type or method, and whether it is public). This allows other
2627 /// passes to find the impl they want without loading the ID (which
2628 /// means fewer edges in the incremental compilation graph).
2629 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2630 pub struct TraitItemRef {
2631 pub id: TraitItemId,
2632 #[stable_hasher(project(name))]
2634 pub kind: AssocItemKind,
2636 pub defaultness: Defaultness,
2639 /// A reference from an impl to one of its associated items. This
2640 /// contains the item's ID, naturally, but also the item's name and
2641 /// some other high-level details (like whether it is an associated
2642 /// type or method, and whether it is public). This allows other
2643 /// passes to find the impl they want without loading the ID (which
2644 /// means fewer edges in the incremental compilation graph).
2645 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2646 pub struct ImplItemRef {
2648 #[stable_hasher(project(name))]
2650 pub kind: AssocItemKind,
2652 pub vis: Visibility,
2653 pub defaultness: Defaultness,
2656 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2657 pub enum AssocItemKind {
2659 Method { has_self: bool },
2664 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2665 pub struct ForeignItem {
2666 #[stable_hasher(project(name))]
2668 pub attrs: HirVec<Attribute>,
2669 pub kind: ForeignItemKind,
2672 pub vis: Visibility,
2675 /// An item within an `extern` block.
2676 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2677 pub enum ForeignItemKind {
2678 /// A foreign function.
2679 Fn(P<FnDecl>, HirVec<Ident>, Generics),
2680 /// A foreign static item (`static ext: u8`).
2681 Static(P<Ty>, Mutability),
2686 impl ForeignItemKind {
2687 pub fn descriptive_variant(&self) -> &str {
2689 ForeignItemKind::Fn(..) => "foreign function",
2690 ForeignItemKind::Static(..) => "foreign static item",
2691 ForeignItemKind::Type => "foreign type",
2696 /// A variable captured by a closure.
2697 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable, HashStable)]
2699 // First span where it is accessed (there can be multiple).
2703 pub type CaptureModeMap = NodeMap<CaptureBy>;
2705 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2706 // has length > 0 if the trait is found through an chain of imports, starting with the
2707 // import/use statement in the scope where the trait is used.
2708 #[derive(Clone, Debug)]
2709 pub struct TraitCandidate {
2711 pub import_ids: SmallVec<[NodeId; 1]>,
2714 // Trait method resolution
2715 pub type TraitMap = NodeMap<Vec<TraitCandidate>>;
2717 // Map from the NodeId of a glob import to a list of items which are actually
2719 pub type GlobMap = NodeMap<FxHashSet<Name>>;
2721 pub fn provide(providers: &mut Providers<'_>) {
2722 check_attr::provide(providers);
2723 map::provide(providers);
2724 upvars::provide(providers);
2727 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
2728 pub struct CodegenFnAttrs {
2729 pub flags: CodegenFnAttrFlags,
2730 /// Parsed representation of the `#[inline]` attribute
2731 pub inline: InlineAttr,
2732 /// Parsed representation of the `#[optimize]` attribute
2733 pub optimize: OptimizeAttr,
2734 /// The `#[export_name = "..."]` attribute, indicating a custom symbol a
2735 /// function should be exported under
2736 pub export_name: Option<Symbol>,
2737 /// The `#[link_name = "..."]` attribute, indicating a custom symbol an
2738 /// imported function should be imported as. Note that `export_name`
2739 /// probably isn't set when this is set, this is for foreign items while
2740 /// `#[export_name]` is for Rust-defined functions.
2741 pub link_name: Option<Symbol>,
2742 /// The `#[link_ordinal = "..."]` attribute, indicating an ordinal an
2743 /// imported function has in the dynamic library. Note that this must not
2744 /// be set when `link_name` is set. This is for foreign items with the
2745 /// "raw-dylib" kind.
2746 pub link_ordinal: Option<usize>,
2747 /// The `#[target_feature(enable = "...")]` attribute and the enabled
2748 /// features (only enabled features are supported right now).
2749 pub target_features: Vec<Symbol>,
2750 /// The `#[linkage = "..."]` attribute and the value we found.
2751 pub linkage: Option<Linkage>,
2752 /// The `#[link_section = "..."]` attribute, or what executable section this
2753 /// should be placed in.
2754 pub link_section: Option<Symbol>,
2758 #[derive(RustcEncodable, RustcDecodable, HashStable)]
2759 pub struct CodegenFnAttrFlags: u32 {
2760 /// `#[cold]`: a hint to LLVM that this function, when called, is never on
2762 const COLD = 1 << 0;
2763 /// `#[rustc_allocator]`: a hint to LLVM that the pointer returned from this
2764 /// function is never null.
2765 const ALLOCATOR = 1 << 1;
2766 /// `#[unwind]`: an indicator that this function may unwind despite what
2767 /// its ABI signature may otherwise imply.
2768 const UNWIND = 1 << 2;
2769 /// `#[rust_allocator_nounwind]`, an indicator that an imported FFI
2770 /// function will never unwind. Probably obsolete by recent changes with
2771 /// #[unwind], but hasn't been removed/migrated yet
2772 const RUSTC_ALLOCATOR_NOUNWIND = 1 << 3;
2773 /// `#[naked]`: an indicator to LLVM that no function prologue/epilogue
2774 /// should be generated.
2775 const NAKED = 1 << 4;
2776 /// `#[no_mangle]`: an indicator that the function's name should be the same
2778 const NO_MANGLE = 1 << 5;
2779 /// `#[rustc_std_internal_symbol]`: an indicator that this symbol is a
2780 /// "weird symbol" for the standard library in that it has slightly
2781 /// different linkage, visibility, and reachability rules.
2782 const RUSTC_STD_INTERNAL_SYMBOL = 1 << 6;
2783 /// `#[no_debug]`: an indicator that no debugging information should be
2784 /// generated for this function by LLVM.
2785 const NO_DEBUG = 1 << 7;
2786 /// `#[thread_local]`: indicates a static is actually a thread local
2788 const THREAD_LOCAL = 1 << 8;
2789 /// `#[used]`: indicates that LLVM can't eliminate this function (but the
2791 const USED = 1 << 9;
2792 /// `#[ffi_returns_twice]`, indicates that an extern function can return
2794 const FFI_RETURNS_TWICE = 1 << 10;
2795 /// `#[track_caller]`: allow access to the caller location
2796 const TRACK_CALLER = 1 << 11;
2800 impl CodegenFnAttrs {
2801 pub fn new() -> CodegenFnAttrs {
2803 flags: CodegenFnAttrFlags::empty(),
2804 inline: InlineAttr::None,
2805 optimize: OptimizeAttr::None,
2809 target_features: vec![],
2815 /// Returns `true` if `#[inline]` or `#[inline(always)]` is present.
2816 pub fn requests_inline(&self) -> bool {
2818 InlineAttr::Hint | InlineAttr::Always => true,
2819 InlineAttr::None | InlineAttr::Never => false,
2823 /// Returns `true` if it looks like this symbol needs to be exported, for example:
2825 /// * `#[no_mangle]` is present
2826 /// * `#[export_name(...)]` is present
2827 /// * `#[linkage]` is present
2828 pub fn contains_extern_indicator(&self) -> bool {
2829 self.flags.contains(CodegenFnAttrFlags::NO_MANGLE) ||
2830 self.export_name.is_some() ||
2831 match self.linkage {
2832 // These are private, so make sure we don't try to consider
2835 Some(Linkage::Internal) |
2836 Some(Linkage::Private) => false,
2842 #[derive(Copy, Clone, Debug)]
2843 pub enum Node<'hir> {
2846 ForeignItem(&'hir ForeignItem),
2847 TraitItem(&'hir TraitItem),
2848 ImplItem(&'hir ImplItem),
2849 Variant(&'hir Variant),
2850 Field(&'hir StructField),
2851 AnonConst(&'hir AnonConst),
2854 PathSegment(&'hir PathSegment),
2856 TraitRef(&'hir TraitRef),
2862 MacroDef(&'hir MacroDef),
2864 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
2865 /// with synthesized constructors.
2866 Ctor(&'hir VariantData),
2868 Lifetime(&'hir Lifetime),
2869 GenericParam(&'hir GenericParam),
2870 Visibility(&'hir Visibility),
2876 pub fn ident(&self) -> Option<Ident> {
2878 Node::TraitItem(TraitItem { ident, .. }) |
2879 Node::ImplItem(ImplItem { ident, .. }) |
2880 Node::ForeignItem(ForeignItem { ident, .. }) |
2881 Node::Item(Item { ident, .. }) => Some(*ident),